[Django]-Django how to assign posts to user


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
            return redirect('atrakcje:after') 
        ogloszenie = DodajForm()
    context = {'form': form}
    return render(request, 'formularz.html', context)

Leave a comment