I have an existing entry in the database, and i want to check in my views.py if the entry already exists in the DB, if it does then the new values will replace the old data in that row, otherwise create a new row for that user. How can i do that?
#models.py
class Member(models.Model):
username = models.CharField(max_length=16, primary_key=True)
password = models.CharField(max_length=16)
profile = models.OneToOneField(Profile, null=True)
following = models.ManyToManyField("self", symmetrical=True)
class Message(models.Model):
user = models.ForeignKey(Member, related_name='%(class)s_user')
recip = models.ForeignKey(Member, related_name='%(class)s_recip')
pm = models.BooleanField(default=True)
time = models.DateTimeField()
text = models.CharField(max_length=4096)
def __str__(self):
return self.username
#forms.py
class UploadFileForm(forms.ModelForm):
class Meta:
model = ProfilePic
fields = ['text','thumbnail']
#models.py
class ProfilePic(models.Model):
user = models.ForeignKey(Member, related_name='%(class)s_user', null=True)
text = models.TextField(max_length=4096)
thumbnail = models.FileField(upload_to='media', null=True)
#views.py
if request.POST:
username = request.session['username']
member_obj = Member.objects.get(pk=username)
form = UploadFileForm(request.POST,request.FILES)
profile_pic = form.save(commit=False)
**#checking if username already exists in the DB:**
member_obj = Member.objects.update_or_create(username=username)
**#if yes then replace data in the row with the new one,
# if not create a new row**
profile_pic.user = member_obj
profile_pic.save()
usernamecoming from here?usernameexists in the db already, if it does then replace the row with the new data provided in the form