I have a form that works perfectly fine
models.py:
class Location(models.Model):
title = models.CharField(max_length=300)
description = models.TextField(null=True, blank=True)
address = models.TextField(null=True, blank=True)
class Review (models.Model):
location = models.ForeignKey(Location)
description = models.TextField(null=True, blank=True)
views.py:
class Create(CreateView):
model = coremodels.Review
template_name = 'location/test.html'
fields = '__all__'
def form_valid(self, form):
form.save()
return HttpResponseRedirect('')
return super(Create, self).form_valid(form)
html:
<form action="" method="post">{% csrf_token %}
{{ form}}
<input type="submit" value="Create" />
</form>
When I open the site I can select a location and give a review over the create button. However, now I am dependent on the prefilled values in the Location class. What if I want that a user can directly create a description as well as a title of the location (I don't want the title to be in class Review
) I already tried looking for this in the docs but couldn't find anything. Somewhere I read that I could create two different forms that handle to different things but I'm not sure how to merge that all in the class Create
. Is there something like model = coremodels.Review & coremodels.Location
and then in the html I could do
{{form.title}}
{{form.description}}
Anyone any ideas or search terms I could look for?
Thanks !
EDIT Ok thanks to Ruddra and this post , here is the working solution. I had to edit it a little in order to get it working for me,
class SomeForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SomeForm, self).__init__(*args, **kwargs)
self.fields['title'] = forms.CharField(label='Title', required = False)
self.fields['description'] = forms.CharField(label='Description', required = False)
self.fields['location'] = forms.ModelChoiceField(queryset= Location.objects.all(), required = False) # This line is for making location not required in form field for input
class Meta:
model = Review
fields = '__all__'
def save(self, commit=True):
"""
It will save location from choice field or inputs of title and description
"""
instance = super(SomeForm, self).save(commit=False)
if instance.location_id:
instance.save()
else:
new_location = Location.objects.create(title=self.cleaned_data['title'])
instance.location = new_location
instance.save()
return instance
and the views.py
class Create(CreateView):
model = coremodels.Review
template_name = 'location/test.html'
form_class = SomeForm