1

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()
6
  • Where is username coming from here? Commented Feb 25, 2016 at 9:44
  • Do you want check is membe exist or not and want to update profile_pic right ?? Commented Feb 25, 2016 at 9:49
  • yes i want to check if username exists in the db already, if it does then replace the row with the new data provided in the form Commented Feb 25, 2016 at 9:51
  • in username which value you are passing user id or username ? because ur checking for pk in your code Commented Feb 25, 2016 at 9:52
  • post your member model also Commented Feb 25, 2016 at 9:53

3 Answers 3

2

Try this,

if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        cd = form.cleaned_data
        username = request.session['username']
        if Member.objects.filter(username=username).exists():
            member_obj = Member.objects.get(username=username)
            profile_pic = ProfilePic.objects.get(user=member_obj)
            profile_pic.user = member_obj
            # you can update other fields by using object.field_name (e.g. profile_pic.text = request.POST.get['text']
            profile_pic.save()
        else:
            ProfilePic.objects.create(user=username)
        return HttpResponse('success')
    else:
        return HttpResponse(form.errors)
else:
    form = UploadFileForm
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for your suggestion, i am getting this error in line ProfilePic.save : unbound method save() must be called with ProfilePic instance as first argument (got nothing instead)
okay so it doesn't go into the if statement if Member.objects.filter(username=username).exists(): even though the username exists in the db... goes straight into else: ProfilePic.objects.create(user=username) return HttpResponse('success')
exactly what value you are passing in username ? and please also post your member model
well the username i am logged with atm is 'lol' so in username = request.session['username'] the username = lol
can you post your member model ?
|
0

As you did, update_or_create is here for that. However, you should use it as follow:

defaults = {} # Here you should specify the values that will be updated on the member object,
              # Or the default values to pass to the newly created instance

# Update or create return a tuple (object, created), created being a boolean
member_obj, created = Member.objects.update_or_create(username=username, defaults=defaults)

# This part seems correct to me
profile_pic.user = member_obj
profile_pic.save()

2 Comments

Thank you for your reply, i am a little confused as to what i need to be putting in defaults, because my data comes from forms.. so user, text, thumbnail is in forms, how would i put them in these curly braces? apologies if this is a stupid question, i am new to django and python in general
Your form data is present in form.cleaned_data, which is a dictionary (curly braces are a way to declare dictionaries in Python, dictionaries are key/value stores). So you can just do defaults['field_name'] = cleaned_data['field_name'] to get the values you want to keep from cleaned data.
0

You should change the queryset:

member_obj = Member.objects.get(pk=username)

to

member_obj = Member.objects.get(username=username)

if username = request.session['username'] is the username attribute of the user object. If you work with usernames (instead of ids) you have to enforce distinct usernames.

If you want to work with pk (id) you should store it in session and then the query would be:

user_id = request.session['id']
member_obj = Member.objects.get(pk=user_id)

3 Comments

unfortunately this didnt work, it still creates a new row even though there is an entry for that username in the db
@user3395936 have you tried to work with the ids instead of usernames?
well my whole project is based on validating usernames and not ids, i just don't want to change all my code and use id's.. and it doesn't fit with my app logic anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.