Wrong form is being displayed in a Django project - django

I have a django project I created. This django project is split into two apps, the user and common. I have a method in the user app that allows the user to submit a form which will create a new Django user. Once the form is submitted and process I want to redirect the user to the testing page in the common app and display a html template that says testing page. Everything is working, the form is being processed and the redirect is occuring. I know this because the url changed to the expected url which will display the html testing page. For some reason, even though the url is transfering to the correct one, the html template being displayed is actually the signup form html template not the correct template.
Here is the code from the common app:
views.py
# testing method
def test(request):
return render(request, 'common/test.html')
urls.py:
urlpatterns = [
url(r'^test/$', views.test, name='test'),
]
test.html:
{% extends "base.html" %}
{% block standard %}
<p>testing page</p>
{% endblock %}
here is the redirect from the users app:
this is in the signup def after the user has been created
return redirect('test')
here is the entire signup method:
# have a user signup and create his account
def Signup(request):
# check to see if form is submitted
if request.method == "POST":
# grab the form and information
form = SignupForm(request.POST)
# validating form
if form.is_valid():
# grab the form content
cd = form.cleaned_data
username = cd['username']
password = cd['password']
verify = cd['verify']
email = cd['email']
# check if passwords match
if password == verify:
# create safe passwords
secure_password = make_password(password)
# save username in sessions
# request.session['username'] = username
return redirect('test')
else:
# redirec to original forms
message = "Passwords did not match"
# users form
form = SignupForm()
# everything required for the template
parameters = {
'message':message,
'form':form,
}
# display html template
return render(request, 'user/Signup.html', parameters)
else:
# the signing up form
form = SignupForm()
message = "Please fill out the entire form"
# everything that needs to be passed to html template
parameters = {
'form':form,
'message':message,
}
# render the template
return render(request, 'user/Signup.html', parameters)

Related

Django How to Add Base Form Template Context Processer

In my navbar I have a newsletter button that pops up a modal. In the modal there is a form that I can use to get the email and do some form manipulation. Since this modal is in the base template, the form must be available for all urls. I have added 'blog.context_processors.email_form' in the settings, and a context_processer.py file with the below info:
from .forms import EmailForm
def email_form(request):
return {
'email_form': EmailForm()
}
In my forms.py I have:
from django import forms
from .models import Email
class EmailForm(forms.ModelForm):
email = forms.EmailField(label='',
widget=forms.EmailInput
(attrs={'id': 'emailInput', 'class': 'article-search',
'placeholder': 'Enter yorffreur email here...', 'type': 'text'}))
class Meta:
model = Email
fields = ['email']
def clean_email(self, *args, **kwargs):
email = self.cleaned_data.get('email')
qs = Email.objects.filter(email__iexact=email)
if qs.exists():
raise forms.ValidationError('This email already exists.')
return email
In the base templates I have included the form as {{ email_form }}. But I do not know where to add the form manipulation. Usually I add it in the views but I'm new so I am an unsure how to do this.
You can write a view wherever you want that will receive the form and validate it then redirect to a page that will confirm the success of the subscription.
You just have to use the action property of the <form> tag to specify which view will handle the form :
<form method="post" action="{% url 'handle_newsletter' %}">
Then in your view, something like this :
def handle_newsletter(request):
form = EmailForm(request.POST)
if form.is_valid():
form.save()
return redirect('subscription_confirmation') # you would need to create this view
# An error occurred
print(form.errors)
return redirect('home')
Don't forget to update your urls.py with the appropriate view names.

Reset Password Form Page not found

I have built a custom password reset in Django, however, after putting the information in 'PasswordResetForm' I get a 404 page not found error.
This is my code for reset_password:
def reset_password(request,username):
if request.method == 'POST':
form = PasswordResetForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
#added this to redirect user to custom url
username = request.user.username
return redirect(reverse('main:home', kwargs={'username': username}))
#return redirect(reverse('main:home'))
else:
return redirect(reverse('main:reset_password'))
else:
form = PasswordResetForm(user=request.user)
args = {'form': form}
return render(request, 'reset_password.html', args)
My urls at myapp/urls.py
urlpatterns=[
path('signup/',views.signup,name='signup'),
path('login',views.user_login,name='user_login'),
path('',views.main_page,name='main_page'),
path('<str:username>', views.home, name='home'),
#replace home/edit with below
path('<str:username>/edit', views.edit_profile, name='edit_profile'),
path('<str:username>/password-reset', views.reset_password, name='reset_password'),
]
and my form for password reset:
class PasswordResetForm(PasswordChangeForm):
class Meta:
model = Profile
fields = ('old_password','new_password1','new_password2')
What seems to be the problem here? I do not know why I am getting this error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/main/test3-b/login.html?next=/main/test3-b/password-reset
This is my AbstractUser model in models.py (I do not have any other code in my models.py
class Profile(AbstractUser):
bio = models.TextField()
university = models.CharField(max_length=30)
def __str__(self):
return self.username
Your urls.py is not using the same path as the URL you are accessing. The URL example you have given is http://127.0.0.1:8000/main/test3-b/login.html but your password reset url is something like http://127.0.0.1:8000/example-user/password-reset where example-user is the username that you are trying to match inside your path.
Out of interest do you have the URL structure include a username? This is normally not wanted as you would be using request.user to access the current user. You also have the risk a users username could break your patterns as you are using str rather than slug which is safer in URL patterns as otherwise id a user was created with the username of "example/edit" then they would never be able to get to your homepage as it would match the edit_profile entry instead.
I saw that by the form rendered in HTML it does not reset the admin user password, however the others works. In my case, I just extended the user class and inserted the email field.

How To Make User Profile In Django?

How To Make User Profile in Django?
Hi I Want to Know How To Make User Profile when user signup in our django app i want create a profile page for the person
Here is my Views.py
def user_reg(request):
register = False
if request.method == 'POST':
form = user_register_form(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(user.password)
user.save()
register = True
if register == True:
return HttpResponseRedirect("/accounts/login")
else:
print(form.errors)
else:
form = user_register_form()
context = {'reg':form,}
return render(request,'signup.html',context)
Models.py
class user_register_model(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
join_date = models.DateTimeField(default=timezone.now)
I Want To Know How To Create Profile Page If User sign Up in our website Problem is How To Create His Profile Page
For Example:
If You Register on Stack overflow You Click on profile icon and you can go to your page
Stack overflow Make Your Page
I Need Some Thing Like That
When User Signup i need user page but how to make that?
i research on google and youtube i can't find any prefect answer
can you please help me?
Create a URL in urls.py like this:
path('profile/<username>', views.user_profile, name='user_profile'),
views.py (If you are using User model to save user data.)
def user_profile(request, username):
user = User.objects.get(username=username)
context = {
"user": user
}
return render(request, 'user_profile.html', context)
user_profile.html (use profile data as per requirement)
{{ user.username }}
{{ user.first_name }}
You can check this on link http://127.0.0.1:8000/profile/<username>/. replace username with user's username and page will show data of only that user.
-----------Edit-----------
If you want to create link, use this:
<a class="nav-link navaour" href="{% url 'profile' username=<username> %}">
replace user's username.
You can just create a view with a template see this. You can have editable forms or anything you like. This view will be shown only if the user is logged in and for unauthorized users redirect them to your login page.

Forbidden (403) CSRF verification failed Request aborted

I am getting a 403 error while I tried most of the responses in the forum to the same problem, but no luck! This registration code is originally from tango with django site, but it is not working on django 1.10.
Any help would be appreciated, here are the files I use:
views.py:
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)
profile.user = user
# 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 'picture' in request.FILES:
profile.picture = request.FILES['picture']
# Now we save the UserProfile model instance.
profile.save()
# Update our variable to tell the template registration was successful.
registered = True
# 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(
'heaven/register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home,name='home'),
url(r'^home/', views.home, name='home'),
url(r'^register/', views.register, name='register'), # ADD NEW PATTERN!
]
html template:
<!DOCTYPE html>
<html>
<head>
<title>Heavenly</title>
<style>
*{font-family:Arial}
h1 {color:red;}
</style>
</head>
<body>
<h1>Register with Heavenly</h1>
{% if registered %}
<strong>thank you for registering!</strong>
Return to the homepage.<br />
{% else %}
<strong>register here!</strong><br />
<form id="user_form" method="post" action="/register/"
enctype="multipart/form-data">
{% csrf_token %}
<!-- Display each form. The as_p method wraps each element in a paragraph
(<p>) element. This ensures each element appears on a new line,
making everything look neater. -->
{{ user_form.as_p }}
{{ profile_form.as_p }}
<!-- Provide a button to click to submit the form. -->
<input type="submit" name="submit" value="Register" />
</form>
{% endif %}
</body>
</html>
https://docs.djangoproject.com/en/1.10/releases/1.10/#features-removed-in-1-10
The dictionary and context_instance parameters for the following functions are removed:
django.shortcuts.render()
django.shortcuts.render_to_response()
django.template.loader.render_to_string()
Use render instead.
https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render

Django not authenticated redirect

What would be the best implementation to redirect a user who is not signed in? Is there a better way then to use a #is_autenticated type decerator in every single view?
The alternative I have thought of is to have a base.html which checks for is_authenticated and every html will extend base. Ex:
base.html
{% if request.user.is_authenticated %}
{% block content %}
content here
{% endblock content %}
{% else %}
redirect
I feel though this way puts view logic into the template which really doesn't sit well but it would avoid a decorator on every function.
You could use some middleware. Personally, I think having the redirect in the template (I'm assuming in javascript code) is very ugly. Django-stronghold (https://github.com/mgrouchy/django-stronghold) is nice if most views require authentication.
Django has an in-built authentication model.Authentication logic should always be in the views and including view logic in the template is a bad practice.Once the user is authenticated, you can render a homepage from the views along with a welcome message.You can do the following:
from django.contrib.auth import authenticate
# login to home page -
def home(request):
try:
username = password = ''
if request.POST:
username = request.POST['username']
password = request.POST['password']
print username
print password
user = authenticate(username=username, password=password)
print "User value is",user
if user is not None:
if user.is_active:
login(request, user)
request.session['username'] = username
return render_to_response('home.html',{"message": "Welcome"})
# Redirect to a success page.
else:
return render_to_response('login.html',{"message": "User is Inactive"})
# Return a 'disabled account' error message
else:
return render_to_response('login.html',{"message": "Invalid Credential"})
else:
return render_to_response('home.html',{"user" : request.session['username']})
except:
return render_to_response('error.html',{"message": sys.exc_info()[0]})