Home > Enterprise >  Passing Data From View to Model Django
Passing Data From View to Model Django

Time:11-20

I'm working on how to passing data from View to Model. I want to pass request.user.id from view to model through save method and put it on created_by field.

Here is my view.py codes:

    def dashboardCategoryCreate(request):
        form = CategoryForm()
        if request.method == 'POST':
            form = CategoryForm(request.POST, request.FILES)
                form.save(request.user.id) # I Wanto To Pass This Value
                return redirect('dashboard-category')
        context = {'form': form}
        return render(request, 'category/category_form.html', context)

And I try to catch this data on models.py and modify field created_by with userId value

    def save(self, userId=None):
        self.created_by = userId 
        super().save()

There is no error but value is not passing. How to do that? Or maybe there is another way to do that?

CodePudding user response:

Pass commit=False to form.save(), this returns an unsaved instance, then manually set the user on this instance before saving

        form = CategoryForm(request.POST, request.FILES)
        if form.is_valid():
            category = form.save(commit=False)
            category.created_by = request.user
            category.save()
            return redirect('dashboard-category')
  • Related