bernardo
bernardo

Reputation: 193

How to save user when saving a form using post within Class-Based Views in Django

Currently the form instance is being saved but the user who filled out the information isn't being saved when I save this form. I am wondering how to grab the user and have it be added to the creation of the new form object.

class ObjectListView(LoginRequiredMixin, FormMixin, ListView):
    model = Object
    template_name = 'ui/home.html'
    context_object_name = 'objects'
    form_class = OrderForm

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            form.save()
            order_type = form.cleaned_data.get('order_type')
            price = form.cleaned_data.get('price')
            **user = request.user**
            messages.success(request, f'Your order has been placed.')
        return redirect('account')

Upvotes: 2

Views: 2149

Answers (2)

Mugoma
Mugoma

Reputation: 324

In order to add more info before saving a form, you can use the parameter commit=False

views.py

class ObjectListView(LoginRequiredMixin, FormMixin, ListView):
    ...
    def post(self, request, *args, **kwargs):
        ...
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user ## Assuming that the relevant field is named user, it will save the user accessing the form using request.user
            obj.save()
            ...
        return redirect('account')  ## this should be indented if it is to work only on successfully saving the form

Upvotes: 3

Ajay Lingayat
Ajay Lingayat

Reputation: 1673

You can fetch the user object from User model of django and save the object using save method.

from django.contrib.auth.models import User

class ObjectListView(LoginRequiredMixin, FormMixin, ListView):
    model = Object
    template_name = 'ui/home.html'
    context_object_name = 'objects'
    form_class = OrderForm

    def post(self, request, *args, **kwargs):
        user = User.objects.get(id=request.user.id) #fetch the user object
        form = self.get_form()
        if form.is_valid():
            form.save()
            order_type = form.cleaned_data.get('order_type')
            price = form.cleaned_data.get('price')
            user.save() #saves/updates the user
            messages.success(request, f'Your order has been placed.')
        return redirect('account')

Upvotes: 0

Related Questions