I have made some custom fields in my user model of django,what i was trying to do is to offer the user to set his/her profile by submitting those fields.although my custom model is working fine.since I can edit or add those fields in my admin site mode.
But when I try to submit that form as a user, it gives an error like this:-
Exception Type: IntegrityError
Exception Value: UNIQUE constraint failed: blog_profile.user_id
my models.py:-
class Profile(models.Model):
user = models.OneToOneField(User,unique=True,on_delete=models.CASCADE,default=1)
bio = models.TextField(max_length=500,null=True,blank=True)
location = models.CharField(max_length=30,null=True,blank=True)
birth_date = models.DateField(null=True,blank=True)
pic=models.FileField(default='/user.png',null=True,blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
forms.py:-
class ProfileForm(forms.ModelForm):
class Meta:
model=Profile
fields = ['bio','location','birth_date','pic']
views.py:-
def set(request):
if request.user.is_authenticated():
if request.method == 'POST':
form=ProfileForm(request.POST,request.FILES)
if form.is_valid():
item=form.save(commit=False)
item.pic=request.FILES['pic']
item.save()
return redirect('/blog')
else:
return HttpResponse('Invalid')
else:
form=ProfileForm()
return render(request,'blog/set.html',{'form':form})
My template for set is:-
{% extends 'blog/base.html' %}
{%block body%}
<div class="container">
<div class="row">{{hell}}
<div class="col-md-6 col-md-offset-3">
<div class="alert alert-success" role="alert"><strong>Well Done!</strong> {{user.username}} You Have Succesfully Registered!</div>
</div>
</div>
<form method="POST" enctype="multipart/form-data">{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Edit">
</form>
</div>
{%endblock%}
This is my attempt please help me i am new to all of these stuffs thanks in advance.
Firstly, I dont think you should provide a default value to User field, since its a OneToOneField, and specifying a default defeats the whole purpose.
Secondly, I think the issue is with your post save signals, since you have specified two signals, and one might conflict with another. I, somehow am unable to understand the purpose of the second signal handler (save_user_profile). Can you remove this and try?
Most likely you already have profile with that user id in the database. Because the relation is one-to-one. One profile can only have one and only one user. When you save the form, if the profile already exist then you should update instead of create.