Answer the question
In order to leave comments, you need to log in
How to save a record?
Good night, I spent 2 hours on the question of how to save a record in the database? Here is the code
#form
class AddPerformerForm(ModelForm):
categories = forms.ModelChoiceField(queryset=Category.objects.all(),
widget=forms.CheckboxSelectMultiple,
empty_label=None)
class Meta:
model = Performer
fields = ['user', 'categories']
#models
class Category(models.Model):
name = models.CharField(max_length=64)
def __str__(self):
return self.name
class Performer(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
categories = models.ManyToManyField(Category)
#view
def create_performer(request):
form = AddPerformerForm({'user': request.user})
if request.method == 'POST':
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
return HttpResponse('No')
context = {"form": form}
return render(request, "performerslist/addperformer.html", context)
<form action="/create-performer/" method="POST">
{% csrf_token %}
<div class="row">
{% for category in form.categories %}
{{category.tag}}
<label for="{{category.id_for_label}}">{{category.choice_label}}</label>
<br>
{% endfor %}
<button class="btn">button</button>
</div>
</form>
Answer the question
In order to leave comments, you need to log in
form = AddPerformerForm({'user': request.user})
In this line, you initialize the form with just the user, without passing in the required categories. Of course it won't pass validation.
if request.method == 'POST':
form = AddPerformerForm({'user': request.user, 'categories': request.POST['ключ-с-категориями']})
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
return HttpResponse('No')
form = AddPerformerForm()
context = {"form": form}
return render(request, "performerslist/addperformer.html", context)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question