0👍
✅
You need to write a few conditionals it appears. You need to create these objects before you can get them so first create them like so. Then once the objects are created you can do what you where trying to do, get_or_create would not work well here because you want to give your user a form to enter their profile information, even though you could set defaults but this is much simpler to understand.
import django.shortcuts import render
def add_profile(request):
context = {}
if request.method == 'POST':
address_form = AddressForm(request.POST)
job_form = JobForm(request.POST)
user_picture_form = UserPictureForm(request.POST)
if address_form.is_valid() and job_form.is_valid() and user_picture_form.is_valid():
adress_form.save()
job_form.save()
user_picture_form.save()
else:
print adress_form.errors, job_form.errors, user_picture_form.errors
else:
context['address_form'] = AddressForm()
context['job_form'] = JobForm()
context['user_picture_form'] = UserPictureForm()
return render(request, 'profiles/add_profiles.html', context)
def edit_profile(request):
context = {}
user = request.user
adress = Adress.objects.get(user=user)
job = Job.objects.get(user=user)
picture = UserPicture.objects.get(user=user)
if request.method == 'POST':
address_form = AddressForm(request.POST, instance=adress)
job_form = JobForm(request.POST, instance=job)
user_picture_form = UserPictureForm(request.POST, instance=picture)
if address_form.is_valid() and job_form.is_valid() and user_picture_form.is_valid():
adress_form.save()
job_form.save()
user_picture_form.save()
else:
print adress_form.errors, job_form.errors, user_picture_form.errors
else:
context['address_form'] = AddressForm(instance=adress)
context['job_form'] = JobForm(instance=job)
context['user_picture_form'] = UserPictureForm(instance=picture)
return render(request, 'profiles/edit_profiles.html', context)
1👍
address = Address.objects.get(user=user)
It looks like there isn’t an address yet for this user, so you need to create it before this. There is a handy shortcut get_or_create that does this for you.
- Invalid file exception on trying to read file with mutagen
- Can't activate django python environment in docker django application
Source:stackexchange.com