I’m following This Answer from stack overflow to add model form set in class base views, as you can see everything is working fine, the album_form
and formset form
is shown in the template, but when add this code:
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.fields['name'].queryset = Album.objects.filter(user=self.request.user)
return form
what this code tells is: When the user is trying to create a column
model, this code will allow him to select only the Album
object that he created, but the code is not working as I’m expecting.
the full code:
class CreateOurColumn(CreateView):
model = Column
success_url = reverse_lazy('List-Of-Column')
form_class = ColumnForm
template_name = 'create_column.html'
def get_context_data(self, *args, **kwargs):
context = super(CreateOurColumn, self).get_context_data(**kwargs)
context['formset'] = ColumnFormSet(queryset=Column.objects.none())
context['album_form'] = AlbumForm()
return context
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.fields['name'].queryset = Album.objects.filter(user=self.request.user)
return form
def post(self, request, *args, **kwargs):
formset = ColumnFormSet(request.POST)
album_form = AlbumForm(data=request.POST)
if formset.is_valid() and album_form.is_valid():
return self.form_valid(formset, album_form)
def form_valid(self, formset, album_form):
album = album_form.cleaned_data['album']
instances = formset.save(commit=False)
for instance in instances:
instance.album = album
instance.save()
return HtppResponseRedirect('List-Of-Column')
the models:
class Album(models.Model):
name = models.CharField(max_length=25)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return str(self.name)
class Column(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=20, blank=True, null=True)
field_type = models.ForeignKey(Type, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return str(self.name)
Template:
<form method='post'>
{% csrf_token %}
{{ album_form|crispy }}
{{ formset.management_form}}
{% for form in formset %}
{{form.as_p}}
{% endfor %}
<button type='submit'>Save<button/>
<form/>