def setup(request): form = UserProfileForm() if request.method == 'POST': form = UserProfileForm(request.POST) form.save(request.user) context = {'form': form} return render(request, 'users/setup.html', context)
def update(self, request, *args, **kwargs): form = UserProfileForm(data=request.data, files=request.FILES, instance=request.user) if form.is_valid(): form.save() return Response({'detail': 'user details saved'}, status=200)
def post(self, request, user_id): user = self.get_user(request, user_id) form = UserProfileForm(instance=user, data=request.POST, files=request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(user.get_absolute_url()) return render(request, 'users/profile.html', { 'user': user, 'form': form, 'msg': 'ko' })
def editProfileView(request): if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance=request.user.userprofile) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('users:user_profile')) else: return render(request, 'users/userprofile_edit_form.html') else: form = UserProfileForm(instance=request.user.userprofile) args = {'form': form} return render(request, 'users/userprofile_edit_form.html', args)
def user_profile(request, username): try: profile_user = User.objects.get(username=username) piechart_data = get_user_statistics(profile_user) render_data = {} render_data['profile_user'] = profile_user render_data['piechart_data'] = dumps(piechart_data) if request.user == profile_user and not is_public_user(profile_user): render_data['profile_form'] = UserProfileForm( instance=profile_user) if can_change_userlevel(request.user, profile_user): render_data['userlevel_form'] = UserLevelForm(instance=profile_user, request_user=request.user) if request.user == profile_user and request.method == 'POST' \ and 'profile_form' in request.POST: profile_form = UserProfileForm(request.POST, instance=profile_user) render_data['profile_form'] = profile_form if profile_form.is_valid() and request.user == profile_user: logger.info('User %s update profile' % username) profile_form.save() update_session_auth_hash(request, profile_user) request.user = profile_user messages.success(request, 'Update profile successfully!') if request.method == 'POST' and 'userlevel_form' in request.POST: userlevel_form = UserLevelForm( request.POST, request_user=request.user) if can_change_userlevel(request.user, profile_user): if userlevel_form.is_valid(request.user): user_level = userlevel_form.cleaned_data['user_level'] logger.info("User %s update %s's user level to %s" % (request.user, username, user_level)) profile_user.user_level = user_level profile_user.save() render_data['userlevel_form'] = userlevel_form messages.success( request, 'Update user level successfully!') else: user_level = userlevel_form.cleaned_data['user_level'] messages.warning(request, "You can't switch user %s to %s" % (profile_user, user_level)) return render_index(request, 'users/profile.html', render_data) except User.DoesNotExist: logger.warning('User %s does not exist' % username) raise Http404('User %s does not exist' % username)
def post(self, request): form = UserProfileForm() args = {} data = {'email':request.user.email} email = request.POST['email'] # проверка: ввёл ли пользователь новый пароль if not email: # если нет, то оставляем текущий email = request.user.email # проверка: есть ли в базе профайл пользователя try: # если есть, то привяжем найденный объект к форме (для обновления данных в базе, иначе orm попробует добавить новую запись) user_profile = Profile.objects.get(user=request.user) form = UserProfileForm(request.POST, request.FILES, instance=user_profile) except: form = UserProfileForm(request.POST) if form.is_valid(): user_profile = form.save(commit=False) user_profile.user = request.user # обновляем email User.objects.filter(pk=request.user.id).update(email=email) # добавляем/обновляем пользовательские данные user_profile.save() return render_to_response('user_info.html', RequestContext(request, {'form':form,'image_url':user_profile.avatar, 'success':True, 'user_form':CustomUserForm(), 'email': email})) else: return render_to_response('user_info.html', RequestContext(request, {'form':form, 'image_url':user_profile.avatar, 'error':True,'user_form':CustomUserForm(), 'email': email}))
def register(request): Context = RequestContext(request) if request.method == 'POST': #user bilgilerini girmis kayit ol butonuna basmis. user_form = UserForm(data = request.POST) profile_form = UserProfileForm(data = request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() #registered = True profile = profile_form.save(commit = False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() return render(request, 'users/register_success.html') else: print user_form.errors, profile_form.errors else: # henuz yeni register ekrani goren user icin user_form = UserForm() profile_form = UserProfileForm() return render_to_response( 'users/registration.html', {'user_form':user_form, 'profile_form':profile_form}, Context)
def RegistrationView(request, usertype): if usertype in ["consumer", "shopadmin"]: context = {"userType": usertype} registered = False if request.method == 'POST': user_form = UserProfileForm(data=request.POST) context['user_form'] = user_form if user_form.is_valid(): user = user_form.save() user.set_password(user.password) g = Group.objects.get(name=usertype) g.user_set.add(user) user.save() registered = True #else: #context["user_form_errors"] = user_form.errors else: user_form = UserProfileForm() context['user_form'] = user_form context["registered"] = registered if registered: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return render_to_response("core/registration.html", context, context_instance=RequestContext(request)) else: return HttpResponse("invalid user type provided")#TODO replace with 404 error
def userprofile(request): user = request.user if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance=user.profile) if form.is_valid(): profile = form.save(commit=False) profile.user = user profile.save() int_list = form.cleaned_data['interest'] #remove unchecked interests for i in profile.interest.all(): if i not in int_list: profile.interest.remove(i) #add new interests for i in int_list: if i not in profile.interest.all(): profile.interest.add(i) return redirect(reverse_lazy('dashboard')) else: form = UserProfileForm(instance=user.profile) return render(request, 'users/profile.html', {'form': form})
def Register(request): context = RequestContext(request) registered = False if request.method == 'POST': user_form = UserForm(request.POST) profile_form = UserProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() registered = True login(request, user) return redirect('home') else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'users/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
def register_pharmacy(request): if request.method == 'POST': u_form = UserRegisterForm(request.POST) p_form = UserProfileForm(request.POST) p1_form = PharmacyProfileForm(request.POST) if u_form.is_valid() and p_form.is_valid() and p1_form.is_valid(): user = u_form.save() username = u_form.cleaned_data.get('username') profile = p_form.save(commit=False) profile.user = user profile.is_pharmacy = True profile.save() pharmacy_profile = p1_form.save(commit=False) pharmacy_profile.user = user pharmacy_profile.save() messages.success( request, f'O λογαριασμός δημιουργήθηκε. Μπορείτε τώρα να συνδεθείτε') return redirect('login') else: u_form = UserRegisterForm() p_form = UserProfileForm() p1_form = PharmacyProfileForm() context = { 'title': 'Εγγραφή Φαρμακευτικής Εταιρείας', 'role': 'pharmacy', 'u_form': u_form, 'p_form': p_form, 'p1_form': p1_form } return render(request, 'users/register.html', context)
def create(self, request, *args, **kwargs): registered = False flag =1 user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) User = get_user_model() if user_form.is_valid() and profile_form.is_valid(): for User in User.objects.filter(): if user_form.cleaned_data['email'] == User.email: flag =0 user_form.cleaned_data['username'] = "******" print("This mail address already exists!") if flag ==1: user = user_form.save() print("user saved") user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: print('found it') profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else : print("not-saved") else: print(user_form.errors,profile_form.errors) return render(request,'users/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered, 'flag':flag})
def register(request): if request.method == 'POST': u_form = UserRegistrationForm(request.POST) p_form = UserProfileForm(request.POST, request.FILES) if u_form.is_valid() and p_form.is_valid(): check = User.objects.filter( email=u_form.cleaned_data.get('email')).exists() if check is False: user = u_form.save() user.save() designation = p_form.cleaned_data.get('designation') if designation == 'TEACHER': group = Group.objects.get(name='Teacher') user.groups.add(group) else: group = Group.objects.get(name='Student') user.groups.add(group) profile = p_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() messages.success(request, "Your account has been created. Log In") return redirect('login') else: messages.warning(request, "Email already exists") return redirect('register') else: u_form = UserRegistrationForm() p_form = UserProfileForm() context = {'u_form': u_form, 'p_form': p_form} return render(request, 'users/signup.html', context)
def AplikacjaConfirm2(request, pk, username): podanie = Podanie.objects.get(pk=pk) username = username profile_for = CustomUser.objects.get(username=username) new_profile = None if request.method == 'POST': form = UserProfileForm(pk, username, request.POST) if form.is_valid(): new_profile = form.save(commit=False) new_profile.user = profile_for new_profile.save() return redirect('aplikacja_confirm3', podanie.pk, username) else: print(form.errors) else: form = UserProfileForm(pk, username) context_dict = { 'podanie': podanie, 'username': username, 'profile_for': profile_for, 'new_profile': new_profile, 'form': form, } response = render(request, 'aplikacje/aplikacja_confirm2.html', context=context_dict) return response
def profile(request): td = {} profile_form = UserProfileForm() email_form = UserEmailForm(instance = request.user) if request.POST: try: profile_form = UserProfileForm(request.POST, instance = request.user.get_profile()) email_form = UserEmailForm(request.POST, instance = request.user) except: profile_form = UserProfileForm(request.POST) email_form = UserEmailForm(request.POST, instance = request.user) if profile_form.is_valid() and email_form.is_valid(): user_profile = profile_form.save(commit = False) user_profile.user = request.user user_profile.save() email_form.save() else: try: profile = get_or_create_user_profile(request) profile_form = UserProfileForm(instance = profile) except: print sys.exc_info()[0] td["creating_profile"] = True td["profile_form"] = profile_form td["email_form"] = email_form td["is_profile_page"] = True return render(request, "profile.html", td)
def register(request): if request.user.is_authenticated(): return redirect("users.views.profile") if request.POST: creation_form = UserCreationForm(request.POST) profile_form = UserProfileForm(request.POST) if creation_form.is_valid() and profile_form.is_valid(): assert creation_form.cleaned_data.get("password1") == creation_form.cleaned_data.get("password2") new_user = creation_form.save(commit = False) new_profile = profile_form.save(commit = False) new_user.save() new_profile.user = new_user new_profile.save() return login(request) else: creation_form = UserCreationForm() profile_form = UserProfileForm() return render(request, "register.html", { "creation_form": creation_form, "profile_form": profile_form })
def register(request): context = RequestContext(request) # Set boolean to false registered = False # if request is post if request.method == 'POST': # Initialize forms to collect user data user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # create user and userprofile classes to add data if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user # retrieve profile registration information if 'first name' in request.FILES: profile.fistName = request.FILES['first name'] if 'last name' in request.FILES: profile.lastName = request.FILES['last name'] if 'picture' in request.FILES: profile.picture = request.FILES['picture'] if 'school' in request.FILES: profile.school = request.FILES['school'] if 'are you a teacher?' in request.FILES: profile.isTeacher = request.FILES['are you a teacher?'] profile.save() registered = True # logs you in if your registration details check out user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, user) return HttpResponseRedirect('/forum/') else: print user_form.errors, profile_form.errors # if request is not post else: user_form = UserForm() profile_form = UserProfileForm() return render_to_response( 'users/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context)
def registration(request): context = RequestContext(request) # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. user = user_form.save(commit=False) # Now we hash the password with the set_password method. user.set_password(user.password) profile = profile_form.save(commit=False) # Did the user provide a profile picture? # If so, we need to get it from the input form and put it in the UserProfile model. if 'avatar' in request.FILES: profile.avatar = request.FILES['avatar'] # Now we save the UserProfile and User model instance. user.save() profile.user = user profile.save() # Update our variable to tell the template registration was successful. messages.success(request, _('Registration successful, you can log in.')) return HttpResponseRedirect(reverse('users:login')) # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. else: print user_form.errors, profile_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context. return render_to_response( 'users/registration.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context)
def edit_profile(request, pk): """Edit an existing profile.""" profile = get_object_or_404(UserProfile, pk=pk) user = profile.user if request.method != "POST": # Initial request; pre-fill form with the current entry. form = UserProfileForm(instance=profile) else: # POST data submitted; process data. form = UserProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() return redirect('users:profile', pk=pk) context = {"profile": profile, "user": user, "form": form} return render(request, "users/edit_profile.html", context)
class UserSettingsView(TemplateView): template_name = 'users/settings.html' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): action = request.POST.get('action') self.profile_form = UserProfileForm( (request.POST if action == 'profile' else None), (request.FILES if action == 'profile' else None), prefix='profile', instance=request.user) self.password_form = UserPasswordChangeForm( request.user, (request.POST if action == 'password' else None), prefix='password') self.email_form = UserEmailChangeForm( request.user, (request.POST if action == 'email' else None), prefix='email') return super(UserSettingsView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(UserSettingsView, self).get_context_data(**kwargs) context['profile_form'] = self.profile_form context['password_form'] = self.password_form context['email_form'] = self.email_form return context def post(self, request, *args, **kwargs): if self.profile_form.is_valid(): self.profile_form.save() messages.success(request, _(u'Профиль успешно сохранен.')) return redirect(request.path) elif self.password_form.is_valid(): self.password_form.save() request.user.backend = request.session[BACKEND_SESSION_KEY] login(request, request.user) messages.success(request, _(u'Пароль успешно изменен.')) return redirect(request.path) elif self.email_form.is_valid(): self.email_form.save() messages.success(request, _(u'Email успешно изменен.')) return redirect(request.path) return self.get(request, *args, **kwargs)
def user_profile(request, pk=None): user = request.user if pk is None else User.objects.get(pk=pk) if request.method == 'GET': context = { 'profile_user': user, 'profile': user.userprofile, 'profile_form': UserProfileForm(), 'e_form': EmailSignupForm(), } return render(request, 'users/profile.html', context) else: form = UserProfileForm(request.POST, request.FILES, instance=user.userprofile) if form.is_valid(): form.save() return redirect('current user profile') return redirect('current user profile')
def register(request): # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now we hash the password with the set_password method. # Once hashed, we can update the user object. user.set_password(user.password) user.save() # Now sort out the UserProfile instance. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. profile = profile_form.save(commit=False) profile.user = user # Now we save the UserProfile model instance. profile.save() # Update our variable to tell the template registration was successful. registered = True # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. else: print(user_form.errors, profile_form.errors) # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context. return render( request, 'register.html', { 'user_form': user_form, 'profile_form': profile_form, 'registered': registered })
def edit_profile(request, username): user = get_object_or_404(User, username=username) if request.user != user: return HttpResponseForbidden() # Processing a submitted form if request.method == 'POST': form = UserProfileForm(request.POST, instance=user.profile) if form.is_valid(): form.save() request.session['django_timezone'] = pytz.timezone(form.cleaned_data['timezone']) messages.success(request, "Your profile has been updated.") return redirect(reverse('users_profile', kwargs={'username': user.username})) else: form = UserProfileForm(instance=user.profile) return render(request, 'users/edit_profile.html', { 'profile': user.profile, 'form': form, })
class UserSettingsView(TemplateView): template_name = 'users/settings.html' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): action = request.POST.get('action') self.profile_form = UserProfileForm( (request.POST if action == 'profile' else None), (request.FILES if action == 'profile' else None), prefix='profile', instance=request.user ) self.password_form = UserPasswordChangeForm(request.user, (request.POST if action == 'password' else None), prefix='password') self.email_form = UserEmailChangeForm(request.user, (request.POST if action == 'email' else None), prefix='email') return super(UserSettingsView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(UserSettingsView, self).get_context_data(**kwargs) context['profile_form'] = self.profile_form context['password_form'] = self.password_form context['email_form'] = self.email_form return context def post(self, request, *args, **kwargs): if self.profile_form.is_valid(): self.profile_form.save() messages.success(request, _(u'Профиль успешно сохранен.')) return redirect(request.path) elif self.password_form.is_valid(): self.password_form.save() request.user.backend = request.session[BACKEND_SESSION_KEY] login(request, request.user) messages.success(request, _(u'Пароль успешно изменен.')) return redirect(request.path) elif self.email_form.is_valid(): self.email_form.save() messages.success(request, _(u'Email успешно изменен.')) return redirect(request.path) return self.get(request, *args, **kwargs)
def register(request): # Initial value set to False. Code changes value to True when registration succeeds. registered = False if request.method == 'POST': # Get form information. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) picture_form = PictureForm(data=request.POST) # If the forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Hash the password with the set_password method. user.set_password(user.password) user.save() # Sort out the UserProfile instance. profile = profile_form.save(commit=False) image = picture_form.save(commit=False) profile.user_extended = user image.user = user # User provides a photo if 'file' in request.FILES: image.file = request.FILES['file'] # Save the UserProfile model instance. profile.save() image.save() # Update our variable to tell the template registration was successful. registered = True return HttpResponseRedirect('/login/') # Print problems to the terminal, show to the user. else: print(user_form.errors, profile_form.errors) # Blank forms, ready for user input. else: user_form = UserForm() profile_form = UserProfileForm() picture_form = PictureForm() # Render the template depending on the context. return render(request, 'register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered, 'picture_form': picture_form} )
def info(request): user = request.user profile = user.get_profile() if request.method == 'GET': fbProfile = profile.fbProfile view_count = get_view_count(request.user) credits = profile.listing_credits credits_spent = profile.total_credits - credits profile_completed_once = profile.profile_completed_once twitter_connected_once = profile.twitter_connected_once facebook_connected_once = profile.facebook_connected_once user_profile_form = UserProfileForm(instance=profile) cxt = { 'user': user, 'form': user_profile_form, 'fb': fbProfile, 'credits':credits, 'credits_spent':credits_spent, 'view_count': view_count, 'profile_completed_once':profile_completed_once, 'twitter_connected_once':twitter_connected_once, 'facebook_connected_once':facebook_connected_once } return TemplateResponse(request, 'users/info.html', cxt) else: # POST request user_profile_form = UserProfileForm(request.POST, instance=profile) if user_profile_form.is_valid(): userObject = User.objects.get(username=user) userObject.email = user_profile_form.cleaned_data['email'] userObject.save() responseData = {} for key, value in user_profile_form.cleaned_data.iteritems(): if key != "default_listing_type" and key != "default_category": responseData[key] = escape(value) responseData['profile'] = True responseData['credits_added'] = 0 if profile.filled_out() and not profile.profile_completed_once: profile.profile_completed_once = True profile.add_credit(2) responseData['credits_added'] = 2 responseData['profile_completed'] = True user_profile = user_profile_form.save() return HttpResponse(json.dumps(responseData), content_type="application/json") else: errors = user_profile_form.errors return HttpResponse(json.dumps(errors), content_type="application/json")
def new_profile(request, pk): '''Create a new user profile.''' user = User.objects.get(pk=pk) form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): new_profile = form.save(commit=False) new_profile.user = user new_profile.save() return redirect('users:profile', pk=pk) context = {'form': form} return render(request, 'users/new_profile.html', context)
def register(request): #Get the request context context = RequestContext(request) #Registration success/failure boolean registered = False #If HTTP POST, process form if request.method == 'POST': #Grab raw data from UserForm and UserProfileForm user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) #If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): #Save the user's form data to the database user = user_form.save() #Hash the password and update the user object user.set_password(user.password) user.save() #Save UserProfile data profile = profile_form.save(commit=False) profile.user = user #Did the user provide a profile image if 'profile_image' in request.FILES: profile.profile_image = request.FILES['profile_image'] #Save the UserProfile model instance profile.save() #Set registration boolean to true registered = True #Invalid forms? else: print(user_form.errors, profile_form.errors) #Not a HTTP POST? Render blank forms else: user_form = UserForm() profile_form = UserProfileForm() #Render the template return render_to_response( 'users/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered':registered}, context)
def user_register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.is_active = False user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] if 'bio' in request.POST: profile.bio = request.POST['bio'] profile.save() registered = True # send account confirmation email current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string( 'users/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'userid': user.pk, 'token': account_activation_token.make_token(user), }) to_email = user_form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() return render( request, 'users/register.html', { 'user_form': user_form, 'profile_form': profile_form, 'registered': registered })
def post(self, request): form = UserProfileForm(request.POST, instance=User.objects.get(pk=request.user.pk)) if form.is_valid() and form.has_changed(): form.save() initial_user = User.objects.get(pk=request.user.pk) initial_form = UserProfileForm(instance=initial_user) initial = initial_form.initial leagues = get_objects_for_user(request.user, 'league_member', klass=League.objects.all(), accept_global_perms=False) # Send notifications for all leagues that this user is a member of. for league in leagues.all(): notify_admin_of_user_changes.delay(league.pk, initial, form.initial) messages.info(request, "Updated profile saved. Thanks.") return HttpResponseRedirect(reverse("users:profile")) else: return render(request, self.template_name, {'form': form})
def edit(request): context = RequestContext(request) # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserEditForm(data=request.POST, instance=request.user) profile_form = UserProfileForm(data=request.POST, instance=request.user.userprofile) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. user = user_form.save(commit=False) profile = profile_form.save(commit=False) # Did the user provide a profile picture? # If so, we need to get it from the input form and put it in the UserProfile model. if 'avatar' in request.FILES: profile.avatar = request.FILES['avatar'] # Now we save the UserProfile and User model instance. user.save() profile.save() # Update our variable to tell the template registration was successful. messages.success(request, _('Your changes have been saved.')) return HttpResponseRedirect(reverse('users:profile', args=(user.username,))) # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. else: print user_form.errors, profile_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. else: user_form = UserEditForm(instance=request.user) profile_form = UserProfileForm(instance=request.user.userprofile) # Render the template depending on the context. return render_to_response( 'users/edit.html', {'user_form': user_form, 'profile_form': profile_form}, context)
class UserAboutSettings(TemplateView, CategoryListMixin): template_name, form = None, None def get(self, request, *args, **kwargs): from users.forms import UserProfileForm from users.model.profile import UserProfile try: self.info = UserProfile.objects.get(user=request.user) except: self.info = UserProfile.objects.create(user=request.user) self.form = UserProfileForm(instance=self.info) self.template_name = get_my_template("profile/settings/about.html", request.user, request.META['HTTP_USER_AGENT']) return super(UserAboutSettings, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(UserAboutSettings, self).get_context_data(**kwargs) context["user"] = self.request.user context["form"] = self.form context["info"] = self.info return context def post(self, request, *args, **kwargs): from users.forms import UserProfileForm from users.model.profile import UserProfile from datetime import datetime from users.model.profile import UserCheck self.info = UserProfile.objects.get(user=request.user) self.form = UserProfileForm(request.POST, instance=self.info) if request.is_ajax() and self.form.is_valid(): new_info = self.form.save(commit=False) new_info.save() try: check = UserCheck.objects.get(user_id=request.user.pk) except: check = UserCheck.objects.create(user_id=request.user.pk) if not check.profile_info: info = UserProfile.objects.get(user_id=request.user.pk) if info.education and info.employment: check.profile_info = True check.save(update_fields=['profile_info']) request.user.plus_carma(100, "ADD") return HttpResponse()
def edit(request, username): if request.user.username == username: user = request.user profile = user.get_profile() if request.method == 'POST': user_profile_form = UserProfileForm(request.POST, instance=profile) if user_profile_form.is_valid(): user_profile = user_profile_form.save() return redirect(user_profile) else: return render(request, 'user_edit.html', {'form': user_profile_form}) else: return render(request, 'user_edit.html', { 'form': UserProfileForm(instance=profile), }) else: raise PermissionDenied
def register(request): registered = False if request.method == 'POST': user_form = UserForm(request.POST) profile_form = UserProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) profile = profile_form.save(commit=False) if User.objects.filter(email=user.email).exists(): messages.error(request, f'Your Email already exist') return redirect("signup") else: user = user_form.save() user.set_password(user.password) user.save() #profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True if user and profile: subject = 'Thank you for registering to our site' message = ' Welcome to Credrank \n Thank you for registration ' email_from = settings.EMAIL_HOST_USER recipient_list = [user.email] send_mail(subject, message, email_from, recipient_list) messages.error( request, f'Your account has been created. Please login.') return redirect("login") else: messages.error(request, f'Your Email already exist') return redirect("signup") else: messages.error(request, f'Your username already exist') return redirect("signup") else: user_form = UserForm() profile_form = UserProfileForm() return render( request, 'registration.html', { 'user_form': user_form, 'profile_form': profile_form, 'registered': registered })
def register(request): if request.method == "GET": form = CustomUserCreationForm() profile_form = UserProfileForm() context = {'form': form, 'profile_form': profile_form} return render(request, "register.html", context) elif request.method == "POST": form = CustomUserCreationForm(request.POST) profile_form = UserProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() login(request, user) return redirect(reverse("home"))
def register(request): # init vars register_failure = [] registered = False if request.method == 'POST': # get main user form user_form = UserForm(data=request.POST) # get user profile form profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): # save main user details user = user_form.save() user.set_password(user.password) user.save() # use the user details and save profile form profile = profile_form.save(commit=False) profile.user = user profile.save() # use the user details and create oauth new_oauth = Oauth(user=user) new_oauth.save() # login the new user user_login = auth.authenticate(username=request.POST.get('username'),password=request.POST.get('password')) loggedin = auth.login(request, user_login) if loggedin: registered = True else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'users/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
def registerView(request): if request.method == 'POST': # POST: create forms and populate with request data userForm = UserCreationForm(request.POST, prefix="userForm"); profileForm = UserProfileForm(request.POST, prefix="profileForm"); if (userForm.is_valid() and profileForm.is_valid()): savedUser = userForm.save() # Save profile without committing, so we can manually add the user savedProfile = profileForm.save(commit=False) savedProfile.user = savedUser savedProfile.save() savedUser.save() return redirect(reverse('welcome')) else: # GET (or other method): create blank forms userForm = UserCreationForm(prefix="userForm"); profileForm = UserProfileForm(prefix="profileForm"); # Render template with forms return render(request, 'users/register.html', {'userForm': userForm, 'profileForm' : profileForm})
def register(request): if request.method=='POST': u_form=UserRegistrationForm(request.POST) p_form=UserProfileForm(request.POST,request.FILES) if u_form.is_valid() and p_form.is_valid(): u=User.objects.get(email=u_form.cleaned_data.get('email')) if u is None: user=u_form.save() user.save() profile=p_form.save(commit=False) profile.user=user if 'image' in request.FILES: profile.image=request.FILES['image'] profile.save() messages.success(request,"Your account has been created") return redirect('login') else: messages.error(request,"Email already present") return redirect('register') else: u_form=UserRegistrationForm() p_form=UserProfileForm() context={'u_form':u_form,'p_form':p_form} return render(request,'users/register.html',context)
def registerView(request): if request.method == 'POST': # POST: create forms and populate with request data userForm = UserCreationForm(request.POST, prefix="userForm") profileForm = UserProfileForm(request.POST, prefix="profileForm") if (userForm.is_valid() and profileForm.is_valid()): savedUser = userForm.save() # Save profile without committing, so we can manually add the user savedProfile = profileForm.save(commit=False) savedProfile.user = savedUser savedProfile.save() savedUser.save() return redirect(reverse('welcome')) else: # GET (or other method): create blank forms userForm = UserCreationForm(prefix="userForm") profileForm = UserProfileForm(prefix="profileForm") # Render template with forms return render(request, 'users/register.html', { 'userForm': userForm, 'profileForm': profileForm })
def register(request): # Like before, get the request's context. context = RequestContext(request) # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now we hash the password with the set_password method. # Once hashed, we can update the user object. user.set_password(user.password) user.save() # Now sort out the UserProfile instance. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. profile = profile_form.save(commit=False) restaurant_boolean = find_restaurant(context, profile.address, profile.city, profile.state) if restaurant_boolean[0] == True: profile.restaurant = restaurant_boolean[1] else: return HttpResponse("Unfortunately, we are not currently serving your area. Please try again soon.") profile.user = user print profile.address # Now we save the UserProfile model instance. profile.save() r0 = randint(0, 9) r1 = randint(0, 9) r2 = randint(0, 9) r3 = randint(0, 9) str_sec = str(r0)+str(r1)+str(r2)+str(r3) account_sid = "ACd2d6a002416aad11df6d7b3d529506b2" auth_token = "616085bee1e2c14db70339a86bfa9dda" client = TwilioRestClient(account_sid, auth_token) message = client.sms.messages.create(body=user.first_name + ", thanks for signing up for Dormserv! Your code is " + str_sec, to= profile.phone, from_="+19146185355") # Replace with your Twilio number registered = True return render_to_response('confirm_account.html', {'profile': profile.id, 'user':profile.user.id, 'str_sec':str_sec}, context) # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. else: print user_form.errors, profile_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context. return render_to_response( 'register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context)
def regist(request): # Like before, get the request's context. context = RequestContext(request) # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registeration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now we hash the password with the set_password method. # Once hashed, we can update the user object. user.set_password(user.password) user.save() # Now sort out the UserProfile instance. # Since we need to set the user attribute ourselves, we set commit=False. # Thi s delays saving the model until we're ready to avoid integrity problems. profile = profile_form.save(commit=False) profile.user = user # Did the user provide a profile a profile picture? # If so, we need to get it from the input form and put it in the UserProfile model. #if 'picture' in request.FILES: # profile.picture = request.FILES['picture'] # Now we save the UserProfile model instance. profile.save() # Update our variable to tell the template registration was successful. registered = True messages.warning(request, "You have successfully created an account!") subject = '[QuickActivity - Do Not Reply] You Have Created an Account!' message = 'Hi ' + user.username + ',\n\n' + 'You have successfully created an account on the QuickActivity website' + '.\n\nYours,\nQuickActivity Team\n' try: send_mail(subject, message, '*****@*****.**', [user.email], fail_silently=True) except BadHeaderError: return HttpResponse('Invalid header found.') # Invalid form or forms - mistakes or somethi ng else? # Print problems to the terminal. # They'll also be shown to the user. else: messages.info(request, user_form.errors) messages.info(request, profile_form.errors) print user_form.errors, profile_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. # Render the template depending on the context. return HttpResponseRedirect(reverse('users:index'))
def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = UserProfileForm(request.POST, instance=request.user.userprofile) if request.user.userprofile.is_doctor: p1_form = DoctorProfileForm(request.POST, instance=request.user.doctorprofile) elif request.user.userprofile.is_pharmacist: p1_form = PharmacistProfileForm( request.POST, instance=request.user.pharmacistprofile) elif request.user.userprofile.is_pharmacy: p1_form = PharmacyProfileForm( request.POST, instance=request.user.pharmacyprofile) elif request.user.userprofile.is_patient: p1_form = PatientProfileForm(request.POST, instance=request.user.patientprofile) else: pass if u_form.is_valid() and p_form.is_valid() and p1_form.is_valid(): u_form.save() p_form.save() p1_form.save() messages.success(request, f'Το προφίλ σας ενημερώθηκε') return redirect('users:profile') else: u_form = UserUpdateForm(instance=request.user) p_form = UserProfileForm(instance=request.user.userprofile) if request.user.userprofile.is_doctor: p1_form = DoctorProfileForm(instance=request.user.doctorprofile) elif request.user.userprofile.is_pharmacist: p1_form = PharmacistProfileForm( instance=request.user.pharmacistprofile) elif request.user.userprofile.is_pharmacy: p1_form = PharmacyProfileForm( instance=request.user.pharmacyprofile) elif request.user.userprofile.is_patient: p1_form = PatientProfileForm(instance=request.user.patientprofile) else: pass if request.user.userprofile.is_doctor: role = 'doctor' title = 'Ενημέρωση Προφίλ Ιατρού' elif request.user.userprofile.is_pharmacist: role = 'pharmacist' title = 'Ενημέρωση Προφίλ Φαρμακοποιού' elif request.user.userprofile.is_pharmacy: role = 'pharmacy' title = 'Ενημέρωση Προφίλ Φαρμακευτικής Εταιρείας' elif request.user.userprofile.is_patient: role = 'patient' title = 'Ενημέρωση Προφίλ Ασθενούς' else: role = 'user' title = 'Ενημέρωση Προφίλ Χρήστη' context = { 'title': title, 'role': role, 'u_form': u_form, 'p_form': p_form, 'p1_form': p1_form } return render(request, 'users/profile.html', context)
def regist(request): # Like before, get the request's context. context = RequestContext(request) # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registeration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now we hash the password with the set_password method. # Once hashed, we can update the user object. user.set_password(user.password) user.save() # Now sort out the UserProfile instance. # Since we need to set the user attribute ourselves, we set commit=False. # Thi s delays saving the model until we're ready to avoid integrity problems. profile = profile_form.save(commit=False) profile.user = user # Did the user provide a profile a profile picture? # If so, we need to get it from the input form and put it in the UserProfile model. #if 'picture' in request.FILES: # profile.picture = request.FILES['picture'] # Now we save the UserProfile model instance. profile.save() # Update our variable to tell the template registration was successful. registered = True messages.warning(request, "You have successfully created an account!") subject = '[QuickActivity - Do Not Reply] You Have Created an Account!' message = 'Hi ' + user.username + ',\n\n' + 'You have successfully created an account on the QuickActivity website' + '.\n\nYours,\nQuickActivity Team\n' try: send_mail(subject, message, '*****@*****.**', [user.email], fail_silently=True) except BadHeaderError: return HttpResponse('Invalid header found.') # Invalid form or forms - mistakes or somethi ng else? # Print problems to the terminal. # They'll also be shown to the user. else: messages.info(request, user_form.errors) messages.info(request, profile_form.errors) print user_form.errors, profile_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. # Render the template depending on the context. return HttpResponseRedirect(reverse('users:index'))