[Django]-How to do i automatically set the user field to current user in django modelform

5πŸ‘

Your views, may looks like that:

def your_view(request):
    form = YourForm(request.POST or None)

    if form.is_valid():
        your_object = form.save(commit=False)
        your_object.user = request.user
        your_object.save()
        return redirect('your_success_url')

    context = {'form': form}
    return render(request, 'your_template.html', context)

You need to adapt some parts, but in the general the should be your view. You need to pay attention to that this view needs a login_required decorator in order to not allow non-logged users to create objects.

πŸ‘€Luan Fonseca

0πŸ‘

Use the request.user. I don’t know how your app works but when creating, do this:

model = ModelName(user = request.user)
model.save()

I used ModelName because it is best practise to start a class name with a capital, which is not fulfilled in your create model. I suggest you change this.

There also seems to be a mistake in your view, it should be request not reques.


Your view could be like so:

def index(request):
    form = FormName(request.POST or None)
    if form.is_valid():
        form.save()
    return render(request, "path/to/template", {"form": form})

And your template could be:

<form method="POST" action="">
    {{ form }}
    <input type="submit">
</form>
πŸ‘€monte

0πŸ‘

So i solved my problem
in my model.py

class SetdistributorProfile(models.Model):
      user=modelss.foreignkey(settings.AUTH_USER_MODEL,null=True,unique=True)

views.py

def SetDistribution(request):
    if not requested.user.is_authenticated:
    return redirect('app_name:url_name)
    if request.method === 'POST':
       dis = MymodelForm(request.POST or None)
       if dis.is_valid():
       instance=dis.save(commit=False)
       instance.user=request.user
       instance.save()
       return redirect('myappname:urlname')
     else:
        instance=MymodelFomr()
     context={'intance':intance}
     return render(request,'page.hmtl',context)
πŸ‘€Scofield

0πŸ‘

Another way to solve this in your views.py

if request.method == "POST":
        yourModel = YourModel(user_id = request.user.id)
        form = YourModelForm(request.POST, request.FILES, instance=yourModel)
        if form.is_valid():
            form.save()
πŸ‘€medz

Leave a comment