sorry I just learned programming
I have registration template and registration success template.
after user fill the form registration, it will be redirect to registration success template
How to get input value['email'] from registration template and display it in registration success template ?
views.py
class RegisterFormView(TemplateView):
template_name = 'home/register.html'
def get(self, request):
user_form = UserForm()
return self.render_to_response({
'base_url' : settings.BASE_URL,
'user_form': user_form,
})
def post(self, request, *args, **kwargs):
if request.method == 'POST':
user_form = UserForm(request.POST)
if user_form.is_valid():
user = user_form.save()
user.full_name = user_form.cleaned_data.get("full_name")
user.email = user_form.cleaned_data.get("email")
user.phone_number = user_form.cleaned_data.get("phone_number")
user.set_password(user_form.cleaned_data.get("password"))
password = user_form.cleaned_data.get("password")
profile = Profile.objects.create(created_by=user)
user.save()
return redirect(reverse("home:register-success"))
else:
user_form = UserForm(request.POST)
return self.render_to_response({
'base_url' : settings.BASE_URL,
'user_form': user_form,
})
register.html
{{user_form|crispy}}
register-success.html
we have send email activation to {{user.email}}
EDIT
register views.py
class RegisterSuccessView(TemplateView):
template_name = 'home/register-success.html'
def get(self, request):
return self.render_to_response({
'base_url' : settings.BASE_URL,
})
Please try replace
return redirect(reverse("home:register-success"))
to
return render(self.request, template_name='home/register-success.html', context={'user': user})
If you want to have another URL for register-success.html you can create an additional view with page and context return
Related
I have this view:
#login_required
def newAnswer(request, id):
post = Post.objects.get(id=id)
form = AnswerForm(request.POST)
if request.method == 'POST':
if form.is_valid():
obj = form.save(commit=False)
obj.author = request.user
obj.post = post
obj.save()
form.save_m2m()
return redirect('main:post', id=post.id)
else:
return render(request, 'main/newAnswer.html', { 'form': form, 'formErrors': form.errors, 'userAvatar': getAvatar(request.user)})
else:
return render(request, 'main/newAnswer.html', {'form': form, 'post': post, 'userAvatar': getAvatar(request.user)})
When i try to post without loging in, it redirects me to "/accounts/login?next=/post/answer/new/81".
My question is how can i get the "next" param in my login view
thanks!
Everything arguments (params) you can see in url mean that request is done with GET method. Use request.GET.get('next', None).
i was following a tutorial and after finishing it i came across and error which should only be shown if the form i have submitted is invalid. I am using recaptcha and several other apis
these are few of my functions
result = "Error"
message = "There was an error, please try again"
class AccountView(TemplateView):
'''
Generic FormView with our mixin to display user account page
'''
template_name = "users/account.html"
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def profile_view(request):
'''
function view to allow users to update their profile
'''
user = request.user
up = user.userprofile
form = UserProfileForm(instance = up)
if request.is_ajax():
form = UserProfileForm(data = request.POST, instance = up)
if form.is_valid():
obj = form.save()
obj.has_profile = True
obj.save()
result = "Success"
message = "Your profile has been updated"
else:
message = FormErrors(form)
data = {'result': result, 'message': message}
return JsonResponse(data)
else:
context = {'form': form}
context['google_api_key'] = settings.GOOGLE_API_KEY
context['base_country'] = settings.BASE_COUNTRY
return render(request, 'users/profile.html', context)
class SignUpView(AjaxFormMixin, FormView):
'''
Generic FormView with our mixin for user sign-up with reCAPTURE security
'''
template_name = "C:/Users/adity\OneDrive/Documents/Coding/python/py_tutorial/djangotutorial/googleapi project/googapiproj/templates/users/sign_up.html"
form_class = UserForm
success_url = "/"
#reCAPTURE key required in context
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["recaptcha_site_key"] = settings.RECAPTCHA_PUBLIC_KEY
return context
#over write the mixin logic to get, check and save reCAPTURE score
def form_valid(self, form):
response = super(AjaxFormMixin, self).form_valid(form)
if request.is_ajax():
token = form.cleaned_data.get('token')
captcha = reCAPTCHAValidation(token)
if captcha["success"]:
obj = form.save()
obj.email = obj.username
obj.save()
up = obj.userprofile
up.captcha_score = float(captcha["score"])
up.save()
login(request, obj, backend='django.contrib.auth.backends.ModelBackend')
#change result & message on success
result = "Success"
message = "Thank you for signing up"
data = {'result': result, 'message': message}
return JsonResponse(data)
return response
class SignInView(AjaxFormMixin, FormView):
'''
Generic FormView with our mixin for user sign-in
'''
template_name = "C:/Users/adity\OneDrive/Documents/Coding/python/py_tutorial/djangotutorial/googleapi project/googapiproj/templates/users/sign_in.html"
form_class = AuthForm
success_url = "/"
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def form_valid(self, form):
response = super(AjaxFormMixin, self).form_valid(form)
if request.is_ajax():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
#attempt to authenticate user
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
result = "Success"
message = 'You are now logged in'
else:
message = FormErrors(form)
data = {'result': result, 'message': message}
return JsonResponse(data)
return response
def sign_out(request):
'''
Basic view for user sign out
'''
logout(request)
return redirect(reverse('users:sign-in'))
I have default Django registration form. It is sent to render to the page based on type of request and user login status. This logic is implemented in views.py file. Somehow, if user is not logged in and GET request is sent to the page, my view returns UnboundLocalError: local variable 'form' is referenced before assignment. How could this happen?
P.S. Here's my view.
def EmplRegisterView(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
group = Group.objects.get(name = 'Employers')
user.groups.add(group)
login(request, user)
return redirect('ProfileSetup')
else:
if request.user.is_authenticated:
logout(request)
form = UserCreationForm()
else:
form = UserCreationForm()
context = {
'form':form,
}
return render(request, "registerPage.html", context)
Try this way
def EmplRegisterView(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
group = Group.objects.get(name = 'Employers')
user.groups.add(group)
login(request, user)
return redirect('ProfileSetup')
if request.user.is_authenticated:
logout(request)
context = {
'form':form,
}
return render(request, "registerPage.html", context)
I'm trying to make register possible on the homepage, so I don't have a seperate URL to handle registration. I'm trying to send the form through get_context_data, however it's not working. Here's my code:
forms.py
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'password',
]
views.py
class BoxesView(ListView):
template_name = 'polls.html'
def get_context_data(self):
context = super(BoxesView, self).get_context_data()
# login
if self.request.method == 'POST':
form = UserRegistrationForm(self.request.POST or None)
context['form'] = form
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(username=username, password=password)
user.save()
return redirect('/')
else:
print(form.errors) #doesn't print anything
print(form.non_field_errors()) #doesn't print anything
print('Errors') #doesn't print anything
else:
form = UserRegistrationForm()
context['form'] = form
return context
def get_queryset(self):
pass
base.html
<form action="" enctype="multipart/form-data" method="post">{% csrf_token %}
<div class="registerBox">
{{ form.username }}
{{ form.password }}
<input type="submit" value="register"/>
</div>
</form>
So when I submit the form it gives this error: Method Not Allowed (POST): "POST / HTTP/1.1" 405 0
And it isn't creating a new User. Any idea what the problem is?
EDIT: Tried FormMixin, got this error: The view app.views.BoxesView didn't return an HttpResponse object. It returned None instead.
class BoxesView(ListView):
template_name = 'polls.html'
form_class = UserRegistrationForm
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(username=username, password=password)
user.save()
return redirect('/')
def get_context_data(self):
context = super(BoxesView, self).get_context_data()
context['form'] = self.get_form()
return context
def get_queryset(self):
pass
Ok I see the issue fix the indentation, your if statement should be inside the get_context_data function not outside ;)
You need to add post() method and FormMixin to your CBV like this:
class BoxesView(FormMixin, ListView):
template_name = 'polls.html'
form_class = UserRegistrationForm
# ...
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
# ...
else:
# ...
return render(request, self.template_name, {'data': some_data})
I have a page for updating a user profile in my django project. The view code looks like this:
#login_required
def updateProfile(request, user_id):
if request.method == 'POST':
form = UserProfileForm(request.POST)
if form.is_valid():
form.user_id = user_id
form.save(commit=True)
return index(request)
else:
profile, created = UserProfile.objects.get_or_create(user_id = self.user_id) # don't know if this will actually work.
profile_form = UserProfileForm(profile)
context = {
'user' : request.user,
'form' : profile_form
}
return render(request, 'myapp/profile.html', context)
My form looks like this:
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['age', 'skill_level']
My user profile looks like this:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
age = models.IntegerField(default=18)
skill_level = models.ForeignKey(SkillLevel)
When this gets posted to, we receive what appears to be a valid user_id along with a valid form. In the UserProfileForm form we do not include user_id so that when it renders the user cannot decide to swap that out. Instead, the user_id gets posted back as a separate parameter (as I type this out, I realize it's kind of weird..). I want to save the UserProfile encapsulated by UserProfileForm to the database on post, so I give it a user_id and try to call .save(commit=True) on it, which returns "Column 'user_id' cannot be null".
My question is simple, how can I get that underlying UserProfile object saved from the form data with the information at hand?
Standard Django form handling idiom in case like that is
#login_required
def updateProfile(request, user_id):
if request.method == 'POST':
form = UserProfileForm(request.POST)
if form.is_valid():
obj = form.save(commit=False) # Get just object, but don't save yet
obj.user = request.user # set user (or user_id)
obj.save() # Save object
return index(request)
else:
profile, created = UserProfile.objects.get_or_create(user_id = self.user_id) # don't know if this will actually work.
profile_form = UserProfileForm(profile)
context = {
'user' : request.user,
'form' : profile_form
}
return render(request, 'myapp/profile.html', context)
Note that form data is not in fields, so form.my_field = 123 won't work - form data is parsed to form.cleaned_data dictionary where form.save() reads it.
use the request.user for userProfile user, do this way
#login_required
def updateProfile(request, user_id):
if request.method == 'POST':
form = UserProfileForm(request.POST)
form.user = request.user
if form.is_valid():
form.save(commit=True)
return index(request)
else:
profile, created = UserProfile.objects.get_or_create(user = request.user) # don't know if this will actually work.
profile_form = UserProfileForm(instance=profile)
context = {
'user' : request.user,
'form' : profile_form
}
return render(request, 'myapp/profile.html', context)