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 username
s (instead of id
s) 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
- [Answered ]-Django 1.9.13 complains SubfieldBase is deprecated, but I'm not using it. How to resolve?
- [Answered ]-Can I return a response in a function within a view function?
- [Answered ]-Python django run bash script in server
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()
- [Answered ]-How to save data into foriegn key in django
- [Answered ]-Django : get() returned more than one
- [Answered ]-Django Signal request_finished
- [Answered ]-Django installation on MS Windows, manage.py "Couldn't import Django"
- [Answered ]-Multiply Django Apache servers
Source:stackexchange.com