def register(request): context = RequestContext(request) # boolean to tell template whether the registration was successful registered = False if request.method == 'POST': # attempt to grab raw info user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # if 2 forms valid if user_form.is_valid() and profile_form.is_valid(): # save user form to database user = user_form.save() # hash user with set password method user.set_password(user.password) user.save() # sort out UserProfile instance profile = profile_form.save(commit=False) profile.user = user # Did user provide profile picture? if 'picture' in request.FILES: profile.picture = request.FILES['picture'] # save user profile profile.save() # update register boolean registered = True else: print(user_form.errors, profile_form.errors) # Not a HTTP POST, render form using 2 ModelForm instances else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context return render_to_response( 'polls/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context)
def profile(request): response_data = {} try: profile = UserProfile.objects.get(user=request.user.id) except: profile = None try: find_img = request.user.id.__str__()+'/profile/' imagems = ImageUpload.objects.filter(upload__startswith=find_img) except: imagems = None try: establisments = Establishment.objects.filter(user=request.user.id) except: establisments = None if request.method == "POST": prof_form = UserProfileForm(request.POST, instance=profile) user_form = UserForm(request.POST, instance=request.user) if prof_form.is_valid() and user_form.is_valid(): user = user_form.save(commit=False) user.username = user_form.cleaned_data['email'] user.save() profile = prof_form.save(commit=False) profile.user = request.user profile.save() response_data['objectid'] = profile.id response_data['sucess'] = 'Perfil salvo com sucesso!' return HttpResponse(json.dumps(response_data), content_type='application/json') else: response_data['erro'] = prof_form.errors.values() return HttpResponse(json.dumps(response_data), content_type='application/json') else: user_form = UserForm(instance=request.user) prof_form = UserProfileForm(instance=profile) return render(request, "profile.html", {'profile': profile, 'establisments': establisments, 'imagems': imagems, 'user_form': user_form, 'prof_form': prof_form})