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 create_user(request): if request.method == 'POST': uform = UserForm(data=request.POST) pform = UserProfileForm(data=request.POST) if uform.is_valid() and pform.is_valid(): new_user = User.objects.create_user( username=uform.cleaned_data['username'], email=uform.cleaned_data['email'], password=uform.cleaned_data['password1'], first_name=uform.cleaned_data['first_name'], last_name=uform.cleaned_data['last_name']) role = pform.cleaned_data['role'] if role == 'M': manager = Manager(manager=new_user) manager.save() if role == 'W': waiter = Waiter(waiter=new_user) waiter.save() if role == 'B': bartender = Bartender(bartender=new_user) bartender.save() return HttpResponseRedirect('/manager/') else: uform = UserForm(data=request.POST) pform = UserForm(data=request.POST) variables = RequestContext(request, { 'uform': uform, 'pform': pform }) return render_to_response('create_user.html', variables)
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): 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 post(self,request): print(request.POST) _userForm = UserProfileForm(request.POST) # print(_userForm) if _userForm.is_valid(): try: _userForm.cleaned_data['password'] = make_password('12345678') _userForm.cleaned_data['is_active'] = True data = _userForm.cleaned_data print(data) self.model.objects.create(**data) res = {'code': 0, 'next_url': reverse("users:user_list"), 'result': '添加用户成功'} except: res = {'code': 1, 'next_url': reverse("users:user_list"), 'errmsg': '添加用户失败'} # logging.error("edit user group pwoer error: %s" % traceback.format_exc()) else: try: # 获取自定义的表单错误的两种常用方式 print(_userForm.errors) print(_userForm.errors.as_json()) print(_userForm.errors['phone'][0]) print(_userForm.errors['username'][0]) except Exception as e: # res = {'code': 1, 'errmsg': _userForm.errors.as_json()} res = {'code': 1, 'errmsg': _userForm.errors} return render(request, settings.JUMP_PAGE, res)
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 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 post(self, request): _userForm = UserProfileForm(request.POST) if _userForm.is_valid(): try: _userForm.cleaned_data['password'] = make_password("12345678") _userForm.cleaned_data['is_active'] = True data = _userForm.cleaned_data self.model.objects.create(**data) res = {'code': 0, 'result': '添加用户成功。'} except: #logger.error("create user error: %s" % traceback.format_exc()) res = {'code': 1, 'errmsg': '添加用户失败。'} else: # 获取自定义的表单错误的两种常用方式 print(_userForm.errors) # <ul class="errorlist"> # <li>phone<ul class="errorlist"><li>手机号码非法</li></ul></li> # <li>username<ul class="errorlist"><li>已存在一位使用该名字的用户。</li></ul></li> # </ul> print(_userForm.errors.as_json()) # {"phone": [{"message": "\u624b\u673a\u53f7\u7801\u975e\u6cd5", "code": "invalid"}], # "username": [{"message": "\u5df2\u5b4f7f\u7528\u8be5\u540d\u5b57\u7684\u7528\u6237\u3002", # "code": "unique"}]} if _userForm.errors.get('phone'): print(_userForm.errors['phone'][0]) # 手机号码非法 if _userForm.errors.get('username'): print(_userForm.errors['username'][0]) # 已存在一位使用该名字的用户 res = {'code': 1, 'errmsg': _userForm.errors.as_json()} return JsonResponse(res, safe=True)
def send_update_profile(request): if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): userProfile = UserProfile.objects.get(user=request.user) description = form.cleaned_data['description'] userProfile.description = description birth_date = form.cleaned_data['birth_date'] userProfile.birth_date = birth_date avatar = form.cleaned_data['avatar'] userProfile.avatar = avatar thumbnail = form.cleaned_data['thumbnail'] userProfile.thumbnail = thumbnail image = form.cleaned_data['image'] userProfile.image = image # avatar = form.cleaned_data['avatar'] # imagefile = File.objects.get(file=avatar) #UserProfile.avatar = imagefile userProfile.save() return redirect('/user/profile') return redirect('http://127.0.0.1:8000/') else: form = UserProfileForm() return redirect('/user/profile')
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 user_login(request): post = request.POST.copy() if request.method == 'POST': post['username'] = post['username'].lower() email = post['username'] first_name = post['first_name'] form = UserForm(post) user_profile_form = UserProfileForm(post) if email and first_name: try: user = User.objects.get(email=email) except User.DoesNotExist: if form.is_valid(): user = form.save(commit=False) user.set_password(user.username) user = form.save() user = authenticate(username=email, password=email) if user is not None: if user.is_active: login(request, user) # FIXME post['user'] = user.id user_profile_form = UserProfileForm(post) if user_profile_form.is_valid(): try: profile = user.get_profile() except: aux = UserProfile.objects profile, created = aux.get_or_create(user=user) newsletter = user_profile_form.clean()['newsletter'] profile.newsletter = newsletter profile.save() try: spectacle = Spectacle.objects.get(status=True) if spectacle.mode == SPECTACLE_MODE_EASY or \ spectacle.mode == SPECTACLE_MODE_RESET: url = spectacle.get_easy_show_url() else: url = spectacle.get_hard_show_url() return HttpResponseRedirect(url) except Spectacle.MultipleObjectsReturned: msg = '<h1>%s</h1>' % _('Spectacle not found') return HttpResponseNotFound(msg) else: form = UserForm() user_profile_form = UserProfileForm() c = { 'form':form, 'user_profile_form':user_profile_form } return render(request, 'login.html', c)
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 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 upload_pic(request): #cur_user = models.User if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): m = UserProfile.objects.get() m.model_pic = form.cleaned_data['image'] m.save() return HttpResponse('image upload success') return HttpResponseForbidden('allowed only via POST')
def test_save(self): form = UserProfileForm(data=self.data, files=self.files, instance=self.profile) form.save() self.profile.refresh_from_db() assert self.profile.user.first_name == 'new' assert self.profile.user.last_name == 'name' assert self.profile.bio == 'test' assert self.profile.user.username == 'rain2'
def post(self,request,username): user = User.objects.get(username=username) active_user_id = request.session.get('user_id') active_user = User.objects.filter(id=active_user_id) if active_user_id == user.id: updated_form = UserProfileForm(request.POST) if updated_form.is_valid(): user.about = updated_form.cleaned_data.get('about') user.save() return redirect('/users/{}'.format(user.username)) return render(request, self.template, {'error':'Invalid input; please try again','user':user,'profile_form':self.profile_form}) return redirect('/users/login')
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 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 edit_profile(request, username): user = User.objects.get(username=username) user_profile = UserProfile.objects.get(user=user) message = None if request.user != user: raise PermissionDenied elif request.method == 'POST': form = UserProfileForm(request.POST) if form.is_valid(): user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.email = form.cleaned_data['email'] if form.cleaned_data['password']: user.set_password(form.cleaned_data['password']) user_profile.alternate_email = form.cleaned_data['alternate_email'] user_profile.phone = form.cleaned_data['phone'] user_profile.tshirt = form.cleaned_data['tshirt'] user_profile.diet = form.cleaned_data['diet'] user_profile.location = form.cleaned_data['location'] user_profile.description = form.cleaned_data['description'] user_profile.notify_by_email = form.cleaned_data['notify_by_email'] user.save() user_profile.save() message = 'Updated profile.' else: form = UserProfileForm( initial={ 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'alternate_email': user_profile.alternate_email, 'phone': user_profile.phone, 'tshirt': user_profile.tshirt, 'diet': user_profile.diet, 'location': user_profile.location, 'description': user_profile.description, 'notify_by_email': user_profile.notify_by_email, }) env = common_env() env['form'] = form env['user_'] = user env['message'] = message env['user_profile'] = user_profile return render(request, 'users/edit_profile.html', env)
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 test_big_file(self, monkeypatch): image = get_test_image() monkeypatch.setattr(image, 'path', str(settings.MEDIA_ROOT / image.name), raising=False) monkeypatch.setattr(image, 'size', 3 << 20) self.files['avatar'] = image form = UserProfileForm(data=self.data, files=self.files, instance=self.profile) assert not form.is_valid() assert list(form.errors.keys()) == ['avatar']
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 edit_profile(request, username): user = User.objects.get(username=username) user_profile = UserProfile.objects.get(user=user) message = None if request.user != user: raise PermissionDenied elif request.method == 'POST': form = UserProfileForm(request.POST) if form.is_valid(): user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.email = form.cleaned_data['email'] if form.cleaned_data['password']: user.set_password(form.cleaned_data['password']) user_profile.alternate_email = form.cleaned_data['alternate_email'] user_profile.phone = form.cleaned_data['phone'] user_profile.tshirt = form.cleaned_data['tshirt'] user_profile.diet = form.cleaned_data['diet'] user_profile.location = form.cleaned_data['location'] user_profile.description = form.cleaned_data['description'] user_profile.notify_by_email = form.cleaned_data['notify_by_email'] user.save() user_profile.save() message = 'Updated profile.' else: form = UserProfileForm(initial={ 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'alternate_email': user_profile.alternate_email, 'phone': user_profile.phone, 'tshirt': user_profile.tshirt, 'diet': user_profile.diet, 'location': user_profile.location, 'description': user_profile.description, 'notify_by_email': user_profile.notify_by_email, }) env = common_env() env['form'] = form env['user_'] = user env['message'] = message env['user_profile'] = user_profile return render(request, 'users/edit_profile.html', env)
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 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 test_unique_email(self): User.objects.create_user('stanne', '*****@*****.**', 'testpass') User.objects.create_user('test42', '*****@*****.**', 'testpass') form = UserProfileForm({ 'email': '*****@*****.**', 'search_visibility': 0, 'email_privacy': 0, }, instance=User.objects.get(username='******')) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, {'email': ['Please use a unique email address.']} )
def edit_profile(request, username): user = User.objects.get(username=username) user_profile = UserProfile.objects.get(user=user) message = None if request.user != user: raise PermissionDenied elif request.method == "POST": form = UserProfileForm(request.POST) if form.is_valid(): user.first_name = form.cleaned_data["first_name"] user.last_name = form.cleaned_data["last_name"] user.email = form.cleaned_data["email"] if form.cleaned_data["password"]: user.set_password(form.cleaned_data["password"]) user_profile.tshirt = form.cleaned_data["tshirt"] user_profile.diet = form.cleaned_data["diet"] user_profile.location = form.cleaned_data["location"] user_profile.description = form.cleaned_data["description"] user_profile.notify_by_email = form.cleaned_data["notify_by_email"] user.save() user_profile.save() message = "Updated profile." else: form = UserProfileForm( initial={ "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "tshirt": user_profile.tshirt, "diet": user_profile.diet, "location": user_profile.location, "description": user_profile.description, "notify_by_email": user_profile.notify_by_email, } ) env = common_env() env["form"] = form env["user_"] = user env["message"] = message env["user_profile"] = user_profile return render(request, "users/edit_profile.html", env)
def post(self, request, *args, **kwargs): """ Handles POST requests and update data of forms with the passed POST adn FILES variables and the checked for validity. """ self.object = self.get_object() user_form = self.get_form() profile_form = UserProfileForm(instance=self.object.profile, data=self.request.POST, files=self.request.FILES) if user_form.is_valid() and profile_form.is_valid(): return self.form_valid(user_form, profile_form) else: return self.form_invalid(user_form, profile_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)
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 get(self, request, user_id): user = self.get_user(request, user_id) form = UserProfileForm(instance=user) return render(request, 'users/profile.html', { 'user': user, 'form': form, })
def category(request): categories = Category.__members__.items() user_ip = get_client_ip(request) ip = user_ip[0] request.session['ip'] = ip if request.user.is_authenticated: user = CustomUser.objects.get(pk=request.user.pk) user_form = UserProfileForm(instance=user) ProfileInlineFormset = inlineformset_factory(CustomUser, UserProfile, fields=('photo',)) formset = ProfileInlineFormset(instance=user) if request.user.id == user.id: if request.method == "POST": formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) return { 'categories' : categories, 'signup_form': CustomUserCreationForm(), 'isLoggedIn': True, 'userprofile': formset, } else : return { 'categories' : categories, 'signup_form': CustomUserCreationForm(), 'isLoggedIn': False, }
def post(self, request): _userForm = UserProfileForm(request.POST) # data1 = QueryDict(request.body).dict() if _userForm.is_valid(): try: '''设置默认的密码和默认激活''' _userForm.cleaned_data['password'] = make_password('123456') _userForm.cleaned_data['is_active'] = True data = _userForm.cleaned_data self.model.objects.create(**data) res = {'code': 0, 'result': '添加用户成功'} except: res = {'code': 1, 'result': '添加用户失败'} else: res = {'code': 1, 'result': _userForm.errors.as_json()} # print(res) return JsonResponse(res, safe=True)
def post(self, request, username): user = User.objects.get(username=username) active_user_id = request.session.get('user_id') active_user = User.objects.filter(id=active_user_id) if active_user_id == user.id: updated_form = UserProfileForm(request.POST) if updated_form.is_valid(): user.about = updated_form.cleaned_data.get('about') user.save() return redirect('/users/{}'.format(user.username)) return render( request, self.template, { 'error': 'Invalid input; please try again', 'user': user, 'profile_form': self.profile_form }) return redirect('/users/login')
def all_categories(request): signup_form = UserProfileForm() login_form = UserLoginForm() data = {} for category in SUPERCATEGORY_CHOICES: data.update( {category[1]: Category.objects.filter(superCategory=category[0])}) return {'login_form': login_form, 'signup_form': signup_form, 'data': data}
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 update(self, request, *args, **kwargs): # save avatar if request.FILES: avatar = check_avatar(request.FILES) request.user.avatar = avatar request.user.save() return Response({'detail': 'avatar saved'}, status=200) # save user details else: 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) return Response({'detail': 'Incorrect request'}, status=422)
def list(self, request, *args, **kwargs): registered = False flag =1 user_form = UserForm() profile_form = UserProfileForm() return render(request,'users/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered, 'flag':flag})
def profile(request): user = get_object_or_404(UserProfile, user__username=request.user.username) if request.user != user.user and not request.user.is_superuser: raise Http404 if request.method == "POST": form = UserProfileForm(user, request.POST) if form.is_valid(): user.workunit = form.cleaned_data["company"] user.telephone = form.cleaned_data["telephone"] user.address = form.cleaned_data["location"] user.save() HttpResponseRedirect("/settings/profile") else: form = UserProfileForm(user) data = {"form": form} return render(request, "widgets/settings/profile.html", data)
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): # 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 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, })
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 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 user_details(request, pk): user = CustomUser.objects.get(pk=pk) user_form = UserProfileForm(instance=user) ProfileInlineFormset = inlineformset_factory(CustomUser, UserProfile, fields=('photo',)) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated and request.user.id == user.id: if request.method == "POST": user_form = UserProfileForm(request.POST, request.FILES, instance=user) formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) if formset.is_valid(): created_user.save() formset.save() return render(request, "blog/user_settings_profile_upd.html") return render(request, "blog/user_details.html", { "noodle": pk, "noodle_form": user_form, "formset": formset, }) else: raise PermissionDenied
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 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 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 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 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)
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 post(self, request, username): empty_profile_form = UserProfileForm empty_extended_form = UserExtendedProfileForm if request.session.get('_auth_user_id'): active_user_id = int(request.session.get('_auth_user_id')) active_user = User.objects.filter(id=active_user_id)[0] if User.objects.filter(username=username): profiled_user = User.objects.filter(username=username)[0] viewed_user_profile = UserProfile.objects.filter(user=profiled_user)[0] if active_user_id == profiled_user.id: updated_form = UserProfileForm(request.POST) updated_extended_form = UserExtendedProfileForm(request.POST,request.FILES) if updated_form.is_valid() and updated_extended_form.is_valid(): profiled_user.first_name = updated_form.cleaned_data.get('first_name') profiled_user.last_name = updated_form.cleaned_data.get('last_name') profiled_user.save() viewed_user_profile.about = updated_extended_form.cleaned_data.get('about') viewed_user_profile.picture = updated_extended_form.cleaned_data.get('picture') viewed_user_profile.save() return redirect('/users/{}/'.format(profiled_user)) return render(request, self.template, {'error':'Invalid input; please try again','user':profiled_user,'profile_form':empty_profile_form,'extended_profile_form':empty_extended_form}) return redirect('/game/index/')
def post(self, request, username): if not request.user.is_anonymous(): active_user_id = request.user.id active_user = User.objects.filter(id=active_user_id)[0] if User.objects.filter(username=username): profiled_user = User.objects.filter(username=username)[0] viewed_user_profile = UserProfile.objects.filter(user=profiled_user)[0] if active_user_id == profiled_user.id: updated_form = UserProfileForm(request.POST) updated_extended_form = UserExtendedProfileForm(request.POST,request.FILES) if updated_form.is_valid() and updated_extended_form.is_valid(): profiled_user.first_name = updated_form.cleaned_data.get('first_name') profiled_user.last_name = updated_form.cleaned_data.get('last_name') profiled_user.email = updated_form.cleaned_data.get('email') profiled_user.save() viewed_user_profile.about = updated_extended_form.cleaned_data.get('about') if updated_extended_form.cleaned_data.get('picture') is not None: viewed_user_profile.picture = updated_extended_form.cleaned_data.get('picture') viewed_user_profile.save() return redirect('interface:profile', username = profiled_user.username) return redirect('interface:profile', username = profiled_user.username) return redirect('interface:login')
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 update_profile(request): if request.user.is_authenticated(): print('User is logged in.') if request.method == 'GET': form = UserProfileForm() user = request.user context = { 'form': form, 'user': user } return render(request, 'users/update_profile.html', context) else: form = UserProfileForm(request.POST) if form.is_valid(): user = User.objects.get(username=request.user) profile = UserProfile.objects.get(user=user) profile.gravatar_email = form.cleaned_data['gravatar_email'] profile.bio = form.cleaned_data['bio'] profile.save() return redirect('/profile/') else: print(form.errors) else: print('No user is logged in.')
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)