E
E
Enter_a_nickname2022-03-29 13:39:09
Django
Enter_a_nickname, 2022-03-29 13:39:09

How to assign the current user in the user field?

In my project I have a form with access to filling only for authorized users.
Here are the approximate fields of the model on which the form is built:

number=models.PositiveSmallIntegerField()
    owner = models.ForeignKey(settings.AUTH_USER_MODEL,
                              on_delete=models.CASCADE)
    gogs=models.ForeignKey('dog', on_delete=models.CASCADE, blank=True)
    zones=models.ManyToManyField('zoness')


my views:
мой views.py:
from .forms import DogFormSet 

    def dog(request):
    formset = DogFormSet (queryset=dog.objects.none())

    if request.method == 'POST' and 'speed' in request.POST:
        form2 = SpeedsForms(request.POST)
        if form2.is_valid():
            form2.save()

    if request.method == 'POST' and 'dogs' in request.POST:
        formset = DogFormSet(request.POST)
        if formset.is_valid():
            formset.save()

    if request.method == 'POST' and 'color' in request.POST:
        form4 = ColorForms(request.POST)
        if form4.is_valid():
            form4.save()

    if request.method == 'POST' and 'Req' in request.POST:
        form5 = DogRequestsForm(request.POST)
        if form5.is_valid():
            form5.save()

    form2 = SpeedsForms()
    form4 = ColorForms()
    form5 = DogRequestsForm()
    data = {
        'form2': form2,
        'formset': formset,
        'form4': form4,
        'form5': form5,
    }

    return render(request, 'main/dogsform.html', data)

How to automatically assign to "owner" the current authorized user or the user who fills out this form?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2022-03-29
@Enter_a_nickname

Take from request.user. The question was asked a bunch of times, it is described in the docks, it is easy to find in Google. are you sure django is yours?
For example docs, https://docs.djangoproject.com/en/4.0/topics/class...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question