Reputation: 1538
I'm using a CreateView and UpdateView for managing saving and updating. Before my data is saved I need combine 3 form fields into one field for storing it in my model. Basically, I'm taking a longitude, latitude, and range and converting it to a single value that is stored in my database. In my ModelForm I create the extra fields that I need and remove the one field that I don't:
class FilterForm(ModelForm):
lat = forms.FloatField()
lgt = forms.FloatField()
range = forms.FloatField()
class Meta:
model = AdFilter
fields = ['title', 'tags', 'start_date', 'end_date', 'start_time', 'end_time', 'week_days', 'ad']
To create new I implement form_valid() in order to combine the longitude, latitude, and range and store it in my model correctly:
class FilterCreate(CreateView):
form_class = FilterForm
template_name = 'filter_form.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(FilterCreate, self).dispatch(*args, **kwargs)
def form_valid(self, form):
new_filter = form.save(commit=False)
new_filter.creator = self.request.user
utm_coordinates = utm.from_latlon(float(form.data['lat']), float(form.data['lgt']))
center = geos.Point(utm_coordinates[0], utm_coordinates[1])
broadcast_area_geometry = center.buffer(float(form.data['range']))
# Set the right SRID
utm_epsg = int('326' + str(utm_coordinates[2]))
broadcast_area_geometry.srid = utm_epsg
new_filter.filter_geometry = broadcast_area_geometry
new_filter.save()
return super(FilterCreate, self).form_valid(new_filter)
This all works fine. Now I'm trying to do the opposite of what form_valid() does in my UpdateView for the situation when someone gets the form. So I need to go from my single model value and create a longitude, latitude, and range values. I tried doing this inside get_context_data() but I've only been able to figure out how to add fields and not how to modify existing ones.
This seems like a very common problem but I can't seem to find an example of how to implement this. Maybe I'm looking in the wrong place.
Upvotes: 0
Views: 1011
Reputation: 599600
You probably want to override the get_initial
method to provide default values. The method should return a dictionary mapping field names to their default values.
Upvotes: 1