djangoformsviewdjango-forms

Django how to assign posts to user


I need to assign posts to user in Django. I created

    user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE)

and then if I display this model in my form.html I have to choice one of all users, if I don't display user in my form.html the form's isn't save my views file :

def formularz(request):
form = DodajForm(request.POST)   
if form.is_valid():
    ogloszenie = form.save(commit=False)
    ogloszenie.user = request.user 
    ogloszenie.save()
    return redirect('atrakcje:after') 
else:
    ogloszenie = DodajForm()
context = {
            'form': form,}
return render(request, 'formularz.html', context)

Can i please know how to resolve it?


Solution

  • Rewrite the form to exclude the user field:

    class DodajForm(forms.ModelForm):
        class Meta:
            model = Dodaj
            exclude = ['user']

    In the view, you better alter the instance, and let the form do the save logic, since a ModelForm can also save many-to-many fields:

    def formularz(request):
        if request.method == 'POST':
            form = DodajForm(request.POST, request.FILES)
            if form.is_valid():
                form.instance.user = request.user
                form.save()
                return redirect('atrakcje:after') 
        else:
            ogloszenie = DodajForm()
        context = {'form': form}
        return render(request, 'formularz.html', context)