Reputation: 391
I need to create admin panel in django , admin will be able to add students"which extended from users " , I finally be able to add them , but after that I get "'AnonymousUser' object has no attribute '_meta' User is added to the database correctly , But django logged me out ! How Can I keep my current user session !
class student(models.Model):
Computers = 1
Communications = 2
Dep_CHOICES = (
(Computers, 'Computers'),
(Communications, 'Communications'),
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
dep = models.PositiveSmallIntegerField(choices=Dep_CHOICES, null=True, blank=True)
deg = models.FloatField(null=True, blank=True)
def __str__(self): # __unicode__ for Python 2
return self.user.username
def create_user_profile(sender, instance, created):
if created:
student.objects.create(user=instance)
def save_user_profile(sender, instance , **kwargs):
instance.student.save()
class UserForm(ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'password')
class studentForm(ModelForm):
class Meta:
model = student
fields = ('dep', 'deg')
The view
def add_stu(request):
if request.method == 'GET':
return render(request, "add_student.html")
else:
user_form = UserForm(request.POST, instance=request.user)
profile_form = studentForm(request.POST, instance=request.user.student)
user_form.save()
profile_form.save()
Upvotes: 0
Views: 169
Reputation: 1019
you can't save profile_form directly as it has a foreign key relation to user and is required. so before you can save profile_form you need to save user and then add the user to profile.
def add_stu(request):
if request.method == 'GET':
return render(request, "add_student.html")
else:
user_form = UserForm(request.POST)
profile_form = studentForm(request.POST)
new_user = user_form.save()
profile = profile_form.save(commit=False)
profile.user = new_user
profile.save()
Upvotes: 1