A
A
Alexander2018-03-05 02:11:03
Django
Alexander, 2018-03-05 02:11:03

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>

The fact is that the form does not pass validation, because only categories are transferred to the form without the user himself.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Matveev, 2018-03-08
@Shlem

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 question

Ask a Question

731 491 924 answers to any question