[Answered ]-Update existing row in database in forms – Django

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

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)
👤doru

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()
👤Agate

Leave a comment