If your are using Django 4 and making project crud operation with the help if Mixins and Generic View
like list View , Create View, Update View etc,
And Your are phasing Attribute error on form_valid () function with current user instance so I also got this error in my project i have researched and find one solution hope its work for your problem too its works with me
You can use this
You can use try and except of python with this form_valid () function of CBV or mixin view with object
Solution:
try:
form.instance.owner = self.request.user
except:
form.owner = self.request.user
Here is Full Function With My Solution
def form_valid(self,form):
try:
form.instance.owner = self.request.user
except:
form.owner = self.request.user
return super().form_valid(form)
#form.instance.owner = self.request.user
return super().form_valid(form)
Here is Full Code of my project may be it can help you more
from django.shortcuts import render
# Create your views here.
from django.urls import reverse_lazy
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, \
DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, \
PermissionRequiredMixin
from .models import ModelName
class UserMixin(object):
def get_queryset(self):
qs = super().get_queryset()
return qs.filter(user=self.request.user)
class UserEditMixin(object):
def form_valid(self,form):
try:
form.instance.user = self.request.user
except:
form.user = self.request.user
return super().form_valid(form)
#form.instance.User = self.request.user
class UserModelNameMixin(UserMixin, LoginRequiredMixin,PermissionRequiredMixin):
model = ModelName
fields = ['subject', 'title', 'slug', 'overview']
success_url = reverse_lazy('manage_ModelName_list')
class UserModelNameEditMixin(UserModelNameMixin, UserEditMixin):
template_name = 'ModelNames/manage/ModelName/form.html'
class ManageModelNameListView(UserModelNameMixin, ListView):
template_name = 'ModelNames/manage/ModelName/list.html'
permission_required = 'ModelNames.view_ModelName'
class ModelNameCreateView(UserModelNameEditMixin, CreateView):
permission_required = 'ModelNames.add_ModelName'
class ModelNameUpdateView(UserModelNameEditMixin, UpdateView):
permission_required = 'ModelNames.change_ModelName'
class ModelNameDeleteView(UserModelNameEditMixin, DeleteView):
template_name = 'ModelNames/manage/ModelName/delete.html'
permission_required = 'ModelNames.delete_ModelName'
#Finally, you create the following views that subclass
This Error Specific for latest Django version 4 because this code are using in Django 3 by Example by Antinio Mele Books I am learning from that books but i have stuck in this so i have to find solution So, I got this Hope It will also Help in Your Problem
Follow us for more:
Thank you
Comment your Query
Put Your Thought or Query Here