def post(self, request): if request.GET.get('login'): self.post_login(request) username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return redirect('tasks:index') return render(request, 'users/login.html', {'user_form': UserForm(), 'profile_form': ProfileForm()}) else: user_form = UserForm(data=request.POST) profile_form = ProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): with atomic(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.creating = True profile.updating = True thread = Thread() thread.save() profile.thread = thread profile.save() login(request, user) return redirect('tasks:index') else: return render(request, 'users/login.html', {'user_form':user_form, 'profile_form': profile_form})
def update_profile(request): """Update a user's profile view.""" user = request.user if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data if not hasattr(user, 'profiles'): Profiles.objects.create(**{ 'website': "add your website", 'bio': 'add your bio', 'picture': '', 'user': user }) user.profiles.website = data['website'] user.profiles.bio = data['bio'] user.profiles.picture = data['picture'] user.profiles.save() return redirect('users/update_profile.html') else: form = ProfileForm() return render( request=request, template_name='users/update_profile.html', context={ 'profile': user, 'user': request.user, 'form': form } )
def update_profile(request): profile = request.user.profile if request.method == "POST": form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data["website"] profile.biography = data["biography"] profile.phone_number = data["phone_number"] profile.picture = data["picture"] profile.save() url = reverse('users:detail', kwargs={'username': request.user.username}) return redirect(url) else: form = ProfileForm() return render(request=request, template_name='users/update_profile.html', context={ 'profile': profile, 'user': request.user, 'form': form })
def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): u = user_form.save() u.set_password(request.POST['password']) u.save() Profile.objects.get_or_create( user=u, position=request.POST.get('position'), phone=request.POST.get('phone'), address=request.POST.get('address'), birth_date=request.POST.get('birth_date'), joined_date=request.POST.get('joined_date'), image=request.FILES.get('image')) # profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('core:main_dashboard') else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm() profile_form = ProfileForm() # user_form = UserForm(instance=request.user) # profile_form = ProfileForm(instance=request.user.profile) return render(request, 'core/register_new_member.html', { 'user_form': user_form, 'profile_form': profile_form })
def update_profile(request): """ Update user's profile view. """ # Initialize profile form profile_form = ProfileForm() # Get profile from user profile = request.user.profile if request.method == 'POST': profile_form = ProfileForm(request.POST, request.FILES) if profile_form.is_valid(): data = profile_form.cleaned_data profile.website = data['website'] profile.phone_number = data['phone_number'] profile.biography = data['biography'] if 'picture' in data: profile.picture = data['picture'] profile.save() return redirect( reverse('users:detail ', kwargs={'username': request.user.username})) return render(request=request, template_name='users/update_profile.html', context={ 'profile': profile, 'user': request.user, 'form': profile_form })
def post(self, request): user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() password = user.password user.set_password(password) user.save() user = authenticate(username=user.username, password=password) login(self.request, user) messages.add_message( request, messages.SUCCESS, "Account Successfully Created.") return redirect("/") else: return render(request, "users/register.html", {"form1": user_form, "form2": profile_form})
def sign_up(request): if request.method == "POST": form = UserCreationForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid(): new_user = form.save() group = Group.objects.get(name='normal') new_user.groups.add(group) new_user.save() profile = profile_form.save(commit=False) profile.user = new_user profile.save() if new_user: login(request, new_user) return redirect(index) else: form = UserCreationForm() profile_form = ProfileForm() context = { 'form': form, 'profile_form': profile_form, } return render(request, 'signup.html', context)
def UserProfile(request): api_key = 'AIzaSyBLHrLLu1EqgDq0kNKAS-j38YeFidGKpWc' myschedule = AvailableDay.objects.filter(user=request.user) if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid and p_form.is_valid: data = p_form.save(commit=False) city = data.city address_coordinates = get_address_location(city) if address_coordinates is not None: # overrite save method latitide = address_coordinates[1] longitude = address_coordinates[2] location = Point(latitide, longitude) data.location = location data.save() u_form.save() return redirect('users:profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'myschedule': myschedule, 'api_key': api_key } return render(request, 'profile/profile.html', context)
def edit_view(request): context = dict() context['user'] = request.user context['edit_form'] = ProfileForm(instance=UserProfile.objects.get(user=request.user)) context.update(csrf(request)) if request.POST: form = ProfileForm(request.POST, request.FILES) context['edit_form'] = form if form.is_valid(): user_profile = UserProfile.objects.get(user=request.user) user_profile.first_name = form.cleaned_data['first_name'] user_profile.last_name = form.cleaned_data['last_name'] user_profile.birthday = form.cleaned_data['birthday'] user_profile.about_user = form.cleaned_data['about_user'] user_profile.url_height = 200 user_profile.url_width = 200 if request.POST.get('avatar', True): user_profile.avatar = request.FILES['avatar'] user_profile.save() return redirect('profile', user_id=request.user.id) else: context['form'] = form return render(request, "edit_profile.html", context)
def update_profile(request): profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data['website'] profile.phone_number = data['phone_number'] profile.biography = data['biography'] profile.picture = data['picture'] profile.save() url = reverse('users:detail', kwargs={'username': request.user.username}) return redirect(url) else: form = ProfileForm() return render(request, 'users/update_profile.html', { 'profile': profile, 'user': request.user, 'form': form })
def update_profile(request): """Update a user's profile view.""" profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.pasa_tiempos_dia = data['pasa_tiempos_dia'] profile.pasa_tiempos_medio_dia = data['pasa_tiempos_medio_dia'] profile.pasa_tiempos_noche = data['pasa_tiempos_noche'] profile.biography = data['biography'] profile.picture = data['picture'] profile.save() return redirect('update_profile') else: form = ProfileForm() return render(request=request, template_name='users/update_profile.html', context={ 'profile': profile, 'user': request.user, 'form': form })
def user_register(request): if request.method == "GET": user_form = UserForm() profile_form = ProfileForm() elif request.method == "POST": user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() password = user.password # The form doesn't know to call this special method on user. user.set_password(password) user.save() # You must call authenticate before login. :( user = authenticate(username=user.username, password=password) login(request, user) messages.add_message( request, messages.SUCCESS, "Congratulations, {}, on creating your new account! You are now logged in.".format( user.username)) return redirect('index') return render(request, "users/register.html", {'user_form': user_form, 'profile_form': profile_form})
def post(self, request, *args, **kwargs): user_form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST) voluntary_form = VoluntaryForm(request.POST) member_form = None voluntary_form = None if request.user.is_member: member_form = MemberForm(request.POST) elif request.user.is_voluntary: voluntary_form = VoluntaryForm(request.POST) if member_form and voluntary_form: if user_form.is_valid() and profile_form.is_valid( ) and voluntary_form.is_valid() and member_form.is_valid(): return self.form_valid(user_form) elif member_form: if user_form.is_valid() and profile_form.is_valid( ) and member_form.is_valid(): return self.form_valid(user_form) elif voluntary_form: if user_form.is_valid() and profile_form.is_valid( ) and voluntary_form.is_valid(): return self.form_valid(user_form) else: self.send_form_error_messages(request, messages, user_form, profile_form) return self.render_to_response(self.get_context_data())
def update_profile(request): profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data['website'] profile.telefono = data['telefono'] profile.biografia = data['biografia'] profile.foto = data['foto'] profile.save() return redirect('update_profile') else: form = ProfileForm() return render(request=request, template_name='users/update_profile.html', context={ 'profile': profile, 'user': request.user, 'form': form })
def update_profile(request): perfil = request.user.perfil if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data perfil.website = data['website'] perfil.phone_number = data['phone_number'] perfil.biography = data['biography'] perfil.picture = data['picture'] perfil.save() url= reverse('perfil', kwargs={'username':request.user.username}) return redirect(url) else: form = ProfileForm() return render( request=request, template_name='users/update_profile.html', context={ 'perfil': perfil, 'user': request.user, 'form': form } )
def update_profile(request): # Request es una clase """ Update a user´s profile view. """ profile = request.user.profile # creamos el objeto profile a partír de instanciar la clase profile #pdb.set_trace() if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) #pdb.set_trace() if form.is_valid(): data = form.cleaned_data #print(data) profile.website = data['website'] profile.phone_number = data['phone_number'] profile.biography = data['biography'] profile.picture = data['picture'] profile.save() url = reverse('users:detail', kwargs={'username': request.user.username}) return redirect(url) else: form = ProfileForm() return render(request=request, template_name='users/update_profile.html', context={ 'profile': profile, 'user': request.user, 'form': form })
def edit_profile(request): url = '/editprofile' sub = 'Submit' u = OjUser.objects.get(username=request.user.username) if request.method == "POST": form = ProfileForm(request.POST) if form.is_valid(): if u.check_password(form.cleaned_data['oldpassword']): u.set_password(form.cleaned_data['password']) else: text = 'Sorry. The old password did not match' return render(request, 'message.html', {'text': text}) u.first_name = form.cleaned_data['name'] u.gender = form.cleaned_data['gender'] u.reg_no = form.cleaned_data['reg_no'] u.save() return HttpResponseRedirect('/profile') else: return render(request, 'register.html', { 'form': form, 'url': url, 'sub': sub }) else: form = ProfileForm(initial={ 'name': u.first_name, 'gender': u.gender, 'reg_no': u.reg_no }) return render(request, 'register.html', { 'form': form, 'sub': sub, 'url': url })
def update_profile(request): profile = request.user.profile if request.method == "POST": form = ProfileForm(data=request.POST, files=request.FILES) if form.is_valid(): # print(form.cleaned_data) data = form.cleaned_data profile.website = data["website"] profile.biography = data["biography"] profile.phone_number = data["phone_number"] if data["picture"]: profile.picture = data["picture"] else: profile.picture = profile.picture profile.save() url = reverse('users:detail', kwargs={'username': request.user.username}) return redirect(url) else: form = ProfileForm() return render( request=request, template_name="users/update_profile.html", context={ "profile": profile, "user": request.user, "form": form }, )
def update_profile(request): """ Update a user's profile view """ profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data['website'] profile.bio = data['bio'] profile.picture = data['picture'] profile.save() messages.success(request, 'Your profile has been updated!') return redirect('feed') else: form = ProfileForm() return render(request=request, template_name='users/update_profile.html', context={ 'profile': profile, 'user': request.user, 'form': form })
def register(request): userid = "_none" form_errors = {} if request.session.has_key('userid'): u = request.session['userid'] return render(request, 'main.html', {'userid': u}) if request.method == 'POST': MyProfileForm = ProfileForm(request.POST) if MyProfileForm.is_valid(): u = MyProfileForm.cleaned_data['userid'] p = MyProfileForm.cleaned_data['password'] data_dict = {} for trigger, descr in trigger_types.types: data_dict[trigger] = MyProfileForm.cleaned_data[trigger] profile = Profiles.objects.create(userid=u, password=p, **data_dict) return render(request, 'main.html', {'userid': u}) else: userid = "_invalid" form_errors = MyProfileForm.errors else: MyProfileForm = ProfileForm() return render( request, 'register.html', { 'userid': userid, "trigger_types": trigger_types.types, 'errors': form_errors, 'myform': MyProfileForm })
def edit_profile(request): user = request.user users = User.objects.get(username=user) profile = Profile.objects.get(user=user) group = Group.objects.get(name='user') user_members = group.user_set.all() if user in user_members: if request.method == 'POST': form1 = EditUserForm(request.POST, instance=users) form2 = ProfileForm(request.POST, instance=profile) if form1.is_valid() and form2.is_valid(): form2.save() form1.save() return HttpResponseRedirect('/') else: form1 = EditUserForm(instance=users) form2 = ProfileForm(instance=profile) variables = RequestContext(request, {'user':user,'user_members':user_members,'form1': form1, 'form2':form2}) else: if request.method == 'POST': form1 = MerchantForm(request.POST, instance=users) if form1.is_valid(): form1.save() return HttpResponseRedirect('/') else: form1 = MerchantForm(instance=users) variables = RequestContext(request, {'user':user,'user_members':user_members,'form1': form1}) return render_to_response('users/edit_profile.html', variables)
def update_profile(request): profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.webside = data['webside'] profile.phone_number = data['phone_number'] profile.biography = data['biography'] profile.picture = data['picture'] profile.save() url = reverse('users:detail', kwargs={'username': request.user.username}) return redirect(url) else: form = ProfileForm() return render( request=request, template_name='users/update_profile.html', context={ 'profile': profile, #Se nesecitan estas lines de codigo pra jalar los datos al formulario del middleware 'user': request.user, 'form': form })
def update_profile(request): """Update a user´s profile view""" profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data['website'] profile.phone_number = data['phone_number'] profile.biography = data['biography'] profile.picture = data['picture'] profile.save() return redirect('update_profile') print(form.cleaned_data) else: form = ProfileForm() return render( request = request, template_name='users/update_profile.html', context={ 'profile': profile, 'user' : request.user, 'form':form })
def edit_profile(request): """Edit user profile.""" try: user_profile = request.user.get_profile() except Profile.DoesNotExist: # TODO: Once we do user profile migrations, all users should have a # a profile. We can remove this fallback. user_profile = Profile.objects.create(user=request.user) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=user_profile) if form.is_valid(): user_profile = form.save() new_timezone = user_profile.timezone if request.session.get('timezone', None) != new_timezone: request.session['timezone'] = new_timezone return HttpResponseRedirect(reverse('users.profile', args=[request.user.id])) else: # request.method == 'GET' form = ProfileForm(instance=user_profile) # TODO: detect timezone automatically from client side, see # http://rocketscience.itteco.org/2010/03/13/automatic-users-timezone-determination-with-javascript-and-django-timezones/ return jingo.render(request, 'users/edit_profile.html', {'form': form, 'profile': user_profile})
def post(self, request, *args, **kwargs): profile, created = Profile.objects.get_or_create( user=self.get_user(request)) form = ProfileForm(data=request.POST, instance=profile) if form.is_valid(): form.save() return self.render({'form_1': form, 'update': True})
def get(self, request, *args, **kwargs): user = self.get_user(request) profile = Profile.objects.filter(user=user) if profile: form = ProfileForm(instance=profile[0]) else: form = ProfileForm() return self.render({'form_1': form})
def create(request): context = {} if (request.method == 'POST'): u_form = SignUpForm(request.POST) # fill it with user details p_form = ProfileForm(request.POST, request.FILES) if u_form.is_valid() and p_form.is_valid(): user = u_form.save() email = user.email username = user.username first_name = user.first_name password = username + str(random.randint(1000, 9999)) Profile.objects.filter(user=user).delete() profile = p_form.save(commit=False) profile.user = user profile.save() messages.success(request, f'Account Created') ''' creating mantis, slack account ''' try: print("slack start", user.email) slack = requests.post( f"https://slack.com/api/users.admin.invite?token=xoxp-788210951796-790883779558-790885554118-6f267c84c9b3c9a5b90e2e74986c7be9&email={email}&channel='test'" ) print("slack end") url = "http://mantis.atg.party/api/rest/users/" header = { 'Authorization': 'mhVBa0ZRB7CCOdd2AGF2RuULv8LCKSp8', 'Content-Type': 'application/json' } payload = f"{{\n \"username\":\"{username}\",\n \"password\":\"{password}\",\n \"real_name\":\"{first_name}\",\n \"email\":\"{email}\",\n \"enabled\": true,\n \"protected\":false}}" mantis_resp = requests.post(url, headers=header, data=payload, timeout=100000) mantis = mantis_resp.json() mantis_confirm_mail = EmailMultiAlternatives( 'ATG', f"Mantis Account has been created!!\nUsername :{username}\nPassword :{password}", "*****@*****.**", [email]) mantis_confirm_mail.send() messages.success( request, "Registration Successfull\nYour Intranet and Mantis Account has been created. Please check the mail for slack and mantis credentials" ) except Exception as exp: messages.error( request, "The credentials such as username or email may already be used in Mantis" ) return render(request, 'mainapp/homepage.html', context) else: return HttpResponse("Form was Invalid") return HttpResponse("You don't have the permission to access this page")
def post(self, *args, **kwargs): if not self.request.user.is_authenticated(): return self.render({'error': 'Please log in before posting'}) form = ProfileForm(data=json.load(self.request), instance=self.request.user) if form.is_valid(): form.save() return self.get(*args, **kwargs) else: return self.render({'error': 'Data is invalid', 'errors_list': form.errors})
def post(self, request): profile = request.user.profile form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data['website'] profile.phone_number = data['phone_number'] profile.biography = data['biography'] profile.picture = data['picture'] profile.save() return redirect('users:login')
def done(self, form_list, form_dict, **kwargs): """ Gather the data from the three forms. If the user already exists, update the profile, if not create a new user. Then add a new membership. """ login_step = self.get_cleaned_data_for_step('login') address_step = self.get_cleaned_data_for_step('user_info')['address'] profile_step = self.get_cleaned_data_for_step('user_info')['profile'] membership_step = self.get_cleaned_data_for_step('membership') # Renew membership for current user if login_step is None: u = self.request.user # Update the user profile profile_form = ProfileForm(profile_step, instance=u.profile) u.profile = profile_form.save() u.save() else: # Create a new user from steps 'login' & 'profile' u = User(email=login_step['email']) u.is_active = False # Not activated yet p = Profile(**profile_step) p.save() u.profile = p u.save() # Create or update address info addresses = u.profile.address_set.all() if len(addresses) > 0: add = addresses[0] add = AddressForm(address_step, instance=addresses[0]) else: add = Address(**address_step) add.profile = u.profile add.save() # Create a new Membership object membership = Membership(**membership_step) membership.profile = u.profile membership.start_date = membership.next_start_date() membership.amount = membership.compute_amount() membership.duration = 1 # valid for one year membership.save() # Send a confirmation email if the user has to pay if membership.amount > 0: membership.email_user(status="submitted") mb_url = self.request.build_absolute_uri( reverse('membership-detail', args=[membership.uid])) return redirect("membership-detail", membership.uid)
def editProfile(request): profile = None try: profile = Profile.objects.get(user=request.user) except: profile = None form = ProfileForm(request.POST or None, instance=profile) if request.method == "POST": if form.is_valid(): form.save() return render(request, 'registration/profile.html', {'form': form})
def post(self, request, *args, **kwargs): user_form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): return self.form_valid(user_form) else: self.send_form_error_messages(request, messages, user_form, profile_form) return self.render_to_response(self.get_context_data())
def save(request, user_id): # action # saves changes to user profile user = get_object_or_404(User, pk=user_id) userProfile = Profile.objects.get(user=user) if request.method == 'POST': form = ProfileForm(request.POST,instance=userProfile) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('users:profile', args=[user_id])) else: return HttpResponseRedirect(reverse('users:edit', args=[user_id]))
def user_edit(request, pk): user = User.get(pk) form = UserForm(request.POST or None, instance=user) profile = ProfileForm(request.POST or None, instance=get_profile(user)) if form.is_valid() and profile.is_valid(): form.save() profile.save() return HttpResponseRedirect(reverse("user-list")) return direct_to_template(request, "user_edit.html", extra_context={ "form": form, "profile": profile, "nav": {"selected": "users",}, })
def edit_profile(request): profile = get_profile(request.user) if request.method == "GET": profile_form = ProfileForm(instance=profile) elif request.method == "POST": profile_form = ProfileForm(instance=profile, data=request.POST) if profile_form.is_valid(): profile_form.save() messages.add_message(request, messages.SUCCESS, "Your profile has been updated.") return render(request, "users/edit_profile.html", {"form": profile_form})
def save_settings(request): if not request.user.is_authenticated(): # XXX improve this return {'error': 'Not logged in'} from users.forms import ProfileForm profile = request.user.get_profile() form = ProfileForm(instance=profile, data=request.POST) if form.is_valid(): profile = form.save(commit=False) profile.country = form.cleaned_data['country'] profile.save() return {'ok': True} else: return {'form_errors': form.errors}
def lk(request): c = get_common_context(request) if not request.user.is_authenticated(): return HttpResponseRedirect('/') if request.method == 'GET': c['form'] = ProfileForm(instance=request.user.get_profile()) else: form = ProfileForm(request.POST, instance=request.user.get_profile()) if form.is_valid(): form.save() return HttpResponseRedirect('/lk/') c['form'] = form return render_to_response('lk.html', c, context_instance=RequestContext(request))
def handle_profile_save(request): """Edit or create a user profile.""" profile = request.user.get_profile() if request.method == 'POST': form = ProfileForm(data=request.POST, files=request.FILES, instance=profile) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() return form return ProfileForm(instance=profile)
def register(request): c = get_common_context(request) register_form = ProfileForm() c['register_form'] = register_form auth_form = AuthenticationForm() c['auth_form'] = auth_form if request.method == "POST": if request.POST['action'] == 'register': register_form = ProfileForm(request.POST, request.FILES) if register_form.is_valid(): error = False if len(User.objects.filter(username=register_form.data.get('email'))): register_form._errors["email"] = ErrorList([u'Такой емейл уже зарегистрирован.']) error = True if not error: email = register_form.data.get('email') u = User(username= email, email=email, first_name=register_form.data.get('fio')) password = password_generator() u.set_password(password) u.save() p = register_form.save(commit=False) p.user = u p.save() user = auth.authenticate(username=email, password=password) auth.login(request, user) p.send(password) return HttpResponseRedirect('/edu/') c['register_form'] = register_form elif request.POST['action'] == 'auth': auth_form = AuthenticationForm(request.POST) if auth_form.is_valid(): pass username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/edu/') else: auth_form._errors = {} auth_form._errors["username"] = ErrorList([u'Неверный логин или пароль.']) c['auth_form'] = auth_form c['title'] = u'Регистрация' return render_to_response('register.html', c, context_instance=RequestContext(request))
def post(self, *args, **kwargs): if not self.request.user.is_authenticated(): return self.render({'error': 'Please log in before posting'}) form = ProfileForm(data=json.load(self.request), instance=self.request.user) if form.is_valid(): form.save() return self.get(*args, **kwargs) else: return self.render({ 'error': 'Data is invalid', 'errors_list': form.errors })
def reg_page(request): c = get_common_context(request) if request.method == 'GET': client_form = ClientForm() profile_form = ProfileForm() user_form = UserForm() elif request.method == 'POST': client_form = ClientForm(request.POST) profile_form = ProfileForm(request.POST) user_form = UserForm(request.POST) if request.POST.get('confirm', None) is None: user_form.errors['confirm'] = ErrorList([u'Необходимо согласиться с договором.']) elif user_form.data['passwd1'] != user_form.data['passwd2']: user_form.errors['passwd1'] = ErrorList([u'Пароли не совпадают.']) elif not user_form.data['email']: user_form.errors['email'] = ErrorList([u'Обязательное поле.']) elif client_form.is_valid() and profile_form.is_valid() and user_form.is_valid(): try: u = auth.models.User(username=user_form.data['email'], email=user_form.data['email'], first_name=user_form.data['first_name'], ) u.save() u.set_password(user_form.data['passwd1']) u.save() except: u = None user_form.errors['email'] = ErrorList([u'Пользователь с таким email уже существует']) if u: # user saved, all is right p = u.get_profile() p.phone = profile_form.data['phone'] p.work_phone=profile_form.data['work_phone'] p.qiwi=profile_form.data['qiwi'] p.user = u p.type = 'c' p.save() Client.add(u, client_form.data['name']) user = auth.authenticate(username=user_form.data['email'], password=user_form.data['passwd1']) auth.login(request, user) messages.success(request, u'Вы успешно зарегистрировались в системе в качестве клиента.') return HttpResponseRedirect('/cabinet') c['client_form'] = client_form c['profile_form'] = profile_form c['user_form'] = user_form return render_to_response('client/reg.html', c, context_instance=RequestContext(request))
def post(self, *args, **kwargs): if not self.request.user.is_authenticated(): return self.render({'error': 'Please log in before posting'}) form = ProfileForm(data=self.post_data(), instance=self.request.user) if form.is_valid(): form.save() if not self.request.is_ajax(): messages.success(self.request, u'Data saved.') return redirect('.') else: return self.get(*args, **kwargs) else: return self.render({'error': 'Data is invalid', 'errors_list': form.errors})
def edit_profile(request): try: profile = Profile.objects.get(user=request.user) except Profile.DoesNotExist: raise Http404 if request.method == 'POST': form = ProfileForm(data=request.POST, files=request.FILES, instance=profile) if form.is_valid(): form.save() return HttpResponseRedirect('/user/') else: print profile form = ProfileForm(instance=profile) return render(request, 'profiles/edit_profile.html', {"profile": profile, "form": form})
def profile(request): c = get_common_context(request) user = request.user participant_form = None expert_form = None profile = user.get_profile() profile_form = None if request.method == 'GET': if Participant.exist(user): participant = Participant.objects.get(user=user) participant_form = ParticipantForm(instance=participant) elif Expert.exist(user): expert = Expert.objects.get(user=user) expert_form = ExpertForm(instance=expert) profile_form = ProfileForm(instance=profile, initial={'name': user.first_name, 'last_name': user.last_name}) if not (request.user.first_name or request.user.last_name): c['pr_msg'] = u'Необходимо заполнить поля: Имя и Фамилия.' else: if Expert.exist(user): expert = Expert.objects.get(user=user) expert_form = ExpertForm(request.POST, request.FILES) else: if Participant.exist(user): participant = Participant.objects.get(user=user) participant_form = ParticipantForm(request.POST, request.FILES) if participant_form.is_valid(): participant.about = participant_form.data['about'] participant.save() profile_form = ProfileForm(request.POST, request.FILES) if profile_form.is_valid(): user.first_name = profile_form.data['name'] user.last_name = profile_form.data['last_name'] user.save() if 'photo' in request.FILES: profile.photo = request.FILES.get('photo', '') profile.sex = profile_form.data.get('sex', '') profile.date_birth = profile_form.data['date_birth'] profile.school = profile_form.data['school'] profile.save() c['participant_form'] = participant_form c['expert_form'] = expert_form c['profile_form'] = profile_form c['user_photo'] = profile.photo return render_to_response('profile.html', c, context_instance=RequestContext(request))
def profile(request): if request.method == "POST": form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): try: form.save() messages.add_message(request, messages.SUCCESS, "Your profile has been updated successfully.") return redirect(reverse('profile')) except: pass else: form = ProfileForm(instance=request.user) data = {'form': form} return render(request, 'registration/profile.html', data)
def add_profile(request): method = request.method if method == 'POST': form = ProfileForm(request.POST, request.FILES) print(form.data) Profile.objects.create(name=form.data['name'], sex=form.data['sex'], age=form.data['age'], hobby=form.data['hobby'], image=form.data['image'], about=form.data['about']) return HttpResponse('Profile Created Successfully') else: form = ProfileForm() return render(request, 'users/add_profile.html', {'form': form})
def update_profile(request): """ User Profile linked one2one with user model. Also links user to company account Contains basic details such as web_site, about, city """ form = ProfileForm(request.POST or None, instance=request.user.get_profile()) if form.is_valid(): form.save() messages.success(request, "Profile updated successfully") return redirect("users:settings") return render(request, "users/update_profile.html", locals())
def mutate_and_get_payload(cls, input, context, info): if hasattr(context.user, 'profile'): profile = context.user.profile else: profile = Profile() profile.user = context.user # update profile form = ProfileForm(input, instance=profile) if form.is_valid(): form.save() else: raise FormError(form.errors) return UpdateProfileMutation(profile=profile)
def settings(request): profile = request.user.get_profile() if request.method == 'POST': form = ProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, _('Your settings have been updated')) return redirect(reverse('default_inbox')) else: # TODO: handle correctly the error and translate the message err = "Incorrect config..." else: err = '' form = ProfileForm(instance=profile) context = {'user': request.user, 'form': form,} return render(request, 'settings.html', context)
def save_user_view(request): form = ProfileForm(request.POST) if form.is_valid(): user = request.user user.email = form.cleaned_data['email'] user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.last_name = form.cleaned_data['last_name'] user.phone_nr = form.cleaned_data['phone_nr'] user.address = form.cleaned_data['address'] user.p_code = form.cleaned_data['p_code'] user.city = form.cleaned_data['city'] user.save() else: dictionary = {'form': form} return render(request, 'users/profile.html', dictionary) return HttpResponseRedirect(reverse('main:main'))
def edit_profile(request): """Edit user profile.""" try: user_profile = request.user.get_profile() except Profile.DoesNotExist: # TODO: Once we do user profile migrations, all users should have a # a profile. We can remove this fallback. user_profile = Profile.objects.create(user=request.user) if request.method == "POST": form = ProfileForm(request.POST, request.FILES, instance=user_profile) if form.is_valid(): user_profile = form.save() return HttpResponseRedirect(reverse("users.profile", args=[request.user.id])) else: # request.method == 'GET' form = ProfileForm(instance=user_profile) return jingo.render(request, "users/edit_profile.html", {"form": form, "profile": user_profile})
def edit(request): """Edit the currently logged in users profile.""" profile = request.user.get_profile() if request.method == 'POST': form = ProfileForm(data=request.POST, files=request.FILES, instance=profile) if form.is_valid(): success_message = ugettext(u"Thank you \u2013 your profile has " u"been updated.") profile = form.save(commit=False) profile.user = request.user profile.save() # if the link form is present we have a few more checks to do if 'link_url' in request.POST: # adding in a link non-JS links_form = ProfileLinksForm(data={ 'url': request.POST['link_url'], 'name': request.POST['link_name'] }) if links_form.is_valid(): link = links_form.save(commit=False) link.profile = profile link.save() messages.success(request, success_message) # links only valid on betafarm so feels safe to do this... return HttpResponseRedirect(reverse('users_profile', kwargs={ 'username': request.user.username })) else: messages.success(request, success_message) return HttpResponseRedirect('/') form = ProfileForm(instance=profile) links = profile.link_set.all() return jingo.render(request, 'users/edit.html', { 'form': form, 'links': links })
def post_profile_form(request): if request.method == 'POST': profile_form = ProfileForm(request.POST, request.FILES) if profile_form.is_valid(): # QUESTION: Cómo mejorar lo siguiente? # Extract the user from the hidden field user = get_object_or_404(User, id=profile_form.cleaned_data['user_id']) if request.user == user: # Recreate the form, but this time binded to the user instance profile_form = ProfileForm(request.POST, request.FILES, instance=user) profile_form.save() return HttpResponseRedirect(profile_form.cleaned_data['next']) else: raise PermissionDenied else: # Save the form in the session for the redirect request.session['profile_form_with_errors'] = request.POST.copy() # We're not saving the avatar image, though... # QUESTION: Si no viene un POST qué? return HttpResponseRedirect(request.POST['next'])
def edit_profile(request): url = '/editprofile' sub = 'Submit' u = OjUser.objects.get(username=request.user.username) if request.method=="POST": form = ProfileForm(request.POST) if form.is_valid(): if u.check_password(form.cleaned_data['oldpassword']): u.set_password(form.cleaned_data['password']) else: text = 'Sorry. The old password did not match' return render(request,'message.html',{'text': text}) u.first_name = form.cleaned_data['name'] u.gender = form.cleaned_data['gender'] u.reg_no = form.cleaned_data['reg_no'] u.save() return HttpResponseRedirect('/profile') else: return render(request,'register.html',{'form':form,'url':url,'sub':sub}) else: form = ProfileForm(initial={ 'name':u.first_name,'gender':u.gender,'reg_no':u.reg_no }) return render(request,'register.html',{'form':form,'sub':sub,'url':url})
def edit_profile(request): user=request.user users=User.objects.get(username=user) profile = Profile.objects.get(user=user) if request.method == 'POST': form1 = EditUserForm(request.POST, instance=users) # form2 = EditForm(request.POST) form2 = ProfileForm(request.POST, instance=profile) form3 = UserImageForm(request.POST, request.FILES) if form1.is_valid() and form2.is_valid() and form3.is_valid(): if not form3.cleaned_data['profile_pic'] and form3.cleaned_data['cover_pic']: UserImage.objects.filter(user=user).update(is_active_cover = False) if not form3.cleaned_data['cover_pic'] and form3.cleaned_data['profile_pic']: UserImage.objects.filter(user=user).update(is_active_profile = False) if form3.cleaned_data['cover_pic'] and form3.cleaned_data['profile_pic']: UserImage.objects.filter(user=user).update(is_active_profile = False, is_active_cover= False) image = form3.save(commit=False) image.user = user image.is_active_profile = True image.is_active_cover = True image.is_public = True image.save() form2.save() form1.save() return HttpResponseRedirect('/home') else: form1 = EditUserForm(instance=users) form2 = ProfileForm(instance=profile) form3 = UserImageForm() variables = RequestContext(request, {'form1': form1, 'form2':form2, 'form3':form3}) return render_to_response( 'users/editprofile.html', variables, )
def base_profile(request): f_password = forms.PasswordChangeForm(request.POST) f_profile = ProfileForm(instance = request.user.profile) f_user = UserEditForm(instance = request.user) commit = False if request.method == 'POST': f_profile = ProfileForm(request.POST,request.FILES,instance = request.user.profile) f_user = UserEditForm(request.POST,request.FILES,instance = request.user) if f_password.is_valid(): f_password.save(commit=True) #handle_uploaded_file(request.FILES['avatar']) f_profile.save(commit=True) commit=True if f_profile.is_valid(): f_profile.save(commit=True) #handle_uploaded_file(request.FILES['avatar']) commit=True if f_user.is_valid(): user = f_user.save(commit=True) commit=True return render_to_response('user/profile.html',{'profile':f_profile,'f_pw':f_password,'f_user':f_user,'commit':commit},context_instance=RequestContext(request))
def profile(request): c = get_client_context(request) if c['client'].legal_entity: client_form = ClientForm(initial={'name': c['client'].legal_entity.name}) profile_form = ProfileForm(instance=c['user_profile']) user_form = UserForm(instance=c['user']) robokassa_form = RobokassaForm(initial={ 'OutSum': 500, 'InvId': 13, 'Desc': u'Описание', 'Email': '*****@*****.**', # 'IncCurrLabel': '', # 'Culture': 'ru' }) if request.method == 'POST': action = request.POST.get('action') if action == 'user': user_form = UserForm(request.POST, instance=c['user']) if user_form.data['passwd1'] != user_form.data['passwd2']: user_form.errors['passwd1'] = ErrorList([u'Пароли не совпадают.']) elif not user_form.data['email']: user_form.errors['email'] = ErrorList([u'Обязательное поле.']) elif user_form.is_valid(): try: u = user_form.save() u.set_password(user_form.data['passwd1']) u.save() messages.success(request, u'Учетные данные успешно изменены.') return HttpResponseRedirect('/profile') except: u = None user_form.errors['email'] = ErrorList([u'Пользователь с таким email уже существует']) elif action == 'profile': profile_form = ProfileForm(request.POST, instance=c['user_profile']) if profile_form.is_valid(): profile_form.save() messages.success(request, u'Данные профиля успешно обновлены.') return HttpResponseRedirect('/profile') elif action == 'client': client_form = ClientForm(request.POST) #if client_form.is_valid(): # c = client_form.save() le = c['client'].legal_entity le.name = client_form.data['name'] le.save() messages.success(request, u'Данные об организации успешно обновлены.') return HttpResponseRedirect('/profile') elif action == 'to_pay': pass c['client_form'] = client_form c['profile_form'] = profile_form c['user_form'] = user_form c['robokassa_form'] = robokassa_form print c['robokassa_form'] return render_to_response('client/profile.html', c, context_instance=RequestContext(request))
def edit(request, slug, format=None): """Edit user page.""" profile = get_object_or_404(Profile, slug=slug) user = profile.user if request.user != user: return HttpResponseRedirect(reverse('users.views.edit', args=[request.user.profile.slug])) if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=profile) if profile_form.is_valid(): profile = profile_form.save() if request.POST.get('phone'): profile.phone = request.POST.get('phone')[0:10] profile.save() city_name = request.POST.get('city_name') state_name = request.POST.get('state_name') if city_name and state_name: city_name = city_name.lower() state_name = state_name.lower() try: # Check to see if state exists state = State.objects.get(name=state_name) try: # Check to see if city exists in that state city = state.city_set.get(name=city_name) except City.DoesNotExist: # If no city in that state exists, create one in that state city = City(name=city_name, state=state) city.save() except State.DoesNotExist: # If state does not exist, create one state = State(name=state_name) state.save() # Then create a city for that state city = City(name=city_name, state=state) city.save() profile.city = city profile.save() if format and format == '.json': data = { 'user': profile.to_json(), } return HttpResponse(json.dumps(data), mimetype='application/json') messages.success(request, 'Profile updated') return HttpResponseRedirect(reverse('users.views.detail', args=[profile.slug])) days = [] day_ids = [dayfree.day.pk for dayfree in user.dayfree_set.all()] hours_am = [] hours_pm = [] hour_ids = [hourfree.hour.pk for hourfree in user.hourfree_set.all()] if profile.tutor: for day in Day.objects.filter(value__gte=0, value__lte=6): button_class = '' if day.pk in day_ids: button_class = 'selected' days.append((day, button_class)) for hour in Hour.objects.filter(value__gte=0, value__lte=23): button_class = '' if hour.pk in hour_ids: button_class = 'selected' if hour.value >= 0 and hour.value <= 11: hours_am.append((hour, button_class)) elif hour.value >= 12 and hour.value <= 23: hours_pm.append((hour, button_class)) hours_am.sort(key=lambda (x, c): x.value) hours_pm.sort(key=lambda (x, c): x.value) profile_form = ProfileForm(instance=profile) skills = [skill for skill in user.skill_set.all()] # Autocomplete source for city name if profile.city and profile.city.state: state_slug = profile.city.state.name.replace(' ', '-') city_autocomplete_source = reverse('cities.views.city_list', args=[state_slug]) else: city_autocomplete_source = reverse('cities.views.city_list') d = { 'city_autocomplete_source': city_autocomplete_source, 'days': days, 'hours_am': hours_am, 'hours_pm': hours_pm, 'profile_form': profile_form, 'skills': sorted(skills, key=lambda x: x.interest.name), 'title': 'Edit', } return render(request, 'users/edit.html', add_csrf(request, d))
def edit(request, slug): """Edit user page.""" user = user_exists(slug) # Correct user if request.user.pk is not user.pk or not request.user.is_staff: return HttpResponseRedirect(reverse('readings.views.list_user', args=[request.user.profile.slug])) profile = user.profile if request.method == 'POST': form = EditUserForm(request.POST, instance=user) profile_form = ProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid() and profile_form.is_valid(): username = request.POST.get('username') password = request.POST.get('password1') # If user changed their password if password: user.set_password(password) user.save() user = form.save() # If an image is uploaded profile = profile_form.save() # If user changed their username if username: profile.slug = slugify(username) # if user has a profile image and checked clear image if profile.image and request.POST.get('clear_image'): profile.image = '' s3_delete_file(user) profile.save() if request.FILES.get('image'): file_path = settings.MEDIA_ROOT + '/' + profile.image.name try: f = open(file_path) f.close() name = str(user.pk) + '_orig.jpg' # Get absolute path of image absolute_path = absolute_image_path(profile) # Rename image rename_image(name, absolute_path) # Resize original image if too large resize_orig_image(user) # Create medium and small images create_extra_images(user) # Upload images to Amazon S3 s3_upload(user) # Remove any old images remove_images(user) # Save profile image name profile.image = name profile.save() except IOError as e: pass messages.success(request, 'User updated') return HttpResponseRedirect(reverse('readings.views.list_user', args=[user.profile.slug])) else: form = EditUserForm(instance=user) profile_form = ProfileForm(instance=profile) d = { 'title': 'Edit %s' % user.first_name, 'form': form, 'profile_form': profile_form, } return render_to_response('users/edit.html', add_csrf(request, d), context_instance=RequestContext(request))