Why My Django Code Is Not Going To Else Part? - django

Here Is My views.py Where I written User Login Code And The Promblem I'm Facing Is That The Code Is Working Properly For Authenticating User But When User Enter Wrong Credential then I Want User To Take Him/Her To Register Page But I'm Unable To Take It To Register Page
Please Help Me Thorugh This And Let Me Know Where I'm Doing Mistake
def user_login(request):
if request.method == "POST":
fm = AuthenticationForm(request=request,data=request.POST)
if fm.is_valid():
uname = fm.cleaned_data['username']
pword = fm.cleaned_data['password']
user = authenticate(username=uname,password=pword)
if user is not None:
login(request,user)
return HttpResponseRedirect('/profile/')
else:
return HttpResponseRedirect('/register/')
else:
fm = AuthenticationForm(request)
return render(request,'login.html',{'form':fm})
Here Are My urls.py
from . import views
urlpatterns = [
path('',views.index),
path('register/',views.user_register,name='user_register'),
path('login/',views.user_login,name='user_login'),
path('profile/',views.user_profile,name='user_profile'),
]

You did not handle when the form is invalid (no else statement for if fm.is_valid():). Try using the following:
def user_login(request):
if request.method == "POST":
fm = AuthenticationForm(request=request,data=request.POST)
if fm.is_valid():
uname = fm.cleaned_data['username']
pword = fm.cleaned_data['password']
user = authenticate(username=uname,password=pword)
if user is not None:
login(request,user)
return HttpResponseRedirect('/profile/')
return HttpResponseRedirect('/register/')
else:
fm = AuthenticationForm(request)
return render(request,'login.html',{'form':fm})

Related

How to write multiple view function for single page

I'm trying to perform multiple operation for single web page. I'm struggling to write multiple function view for single web page. How to do that. Help me in that.
def home_view(request):
if 'username' in request.session:
if request.method == 'GET':
form = ProfileForm(request.GET)
if form.is_valid:
profile_info = Profile.objects.filter(username=username).values()
for i in profile_info:
profiledict = i
return render(request, 'home/index.html', {'profile_first_name': profiledict['first_name'],
'profile_last_name': profiledict["last_name"],
'profile_phone_number': profiledict['phone_number'],
'profile_email': profiledict['email'],
'profile_address': profiledict['address'],
'profile_image': profiledict['image']})
elif request.method == 'POST':
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
phone_number = request.POST.get('phone_number')
email = request.POST.get('email')
address = request.POST.get('address')
image = request.FILES['images']
file_storage = FileSystemStorage()
obj = Profile.objects.all().filter(username=username)
if len(obj) > 0:
obj.update(first_name=first_name, last_name=last_name, phone_number=phone_number,
email=email, address=address, image=file_storage.save(image.name, image))
return redirect('/home/')
return redirect('/home/')
else:
return redirect('/login/')
def home2_view(request):
if 'username' in request.session:
business_objs = AddBusiness.objects.all().values()
return render(request, 'home/index.html', {'business_objs': business_objs})
else:
return redirect('/login/')
I tried like this, it performing only first operation. Here i'm trying to perform 3 operation, GET(extract data from database and displaying in HTML form), POST(updating the form data), and Displaying all database rows and columns in HTML page.

Django - Having two views in same url

I am making a website in django and in my homepage I want to show the list of my recent blog post and a few blocks below I want to make a simple contact form. The blog and the contact form separately are working fine. But I want to include them in the same page(obviously in the same url).
The views.py is:
from .forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'personal/index.html', {'form': form})
If you want to look at the forms.py then :
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
The urlpattern in urls.py of my homepage is:
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:2],
template_name="personal/index.html")),
url(r'^$', views.get_name, name='contact'),
]
With this urlpatter the list of blog post shows up perfectly but the contact form doesn't show up. But with the below urlpattern contact form shows up but blog posts doesn't show up.
urlpatterns = [
url(r'^$', views.get_name, name='contact'),
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:2],
template_name="personal/index.html")),
]
I want to make both of these contents show up in the same page. Please help me. If you need any more information then do tell.
It is not possible to have multiple views for the same URL. You can only have one view for each URL.
In this case, the easiest fix is to update your get_name view so that it includes the posts in the template context.
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
post_list = Post.objects.all().order_by("-date")[:2]
return render(request, 'personal/index.html', {'form': form, 'post_list': post_list})
Then remove the url pattern that uses ListView so that get_name handles the requests.
While you cannot do that directly, you could consider your function in views.py to handle the request in a way that when it gets a post request from one model then it initialises the form for the respective model only. For this to happen you will need to assign a name to your button. See below code -
def SignUpLogin(request):
message = ""
Login_message = ""
print(request.POST)
if request.method == 'POST':
if request.POST.get('UserForgotPassword') == 'Sign Up':
form_SignUP_Login = LoginForm()
print("POST request received")
print(request.POST)
form_SignUP=SignUpForm(request.POST)
print(form_SignUP)
if form_SignUP.is_valid():
if request.POST["Password"] != request.POST["Confirm_Password"]:
message = "* Passwords do not match"
#raise forms.ValidationError(('Passwords do not match'), code="PasswordNotMatched")
else:
try:
user = User.objects.get(username=request.POST["Username"])
context= {'form': form_SignUP, 'error':'* Username already taken. Please try different username.'}
return render(request, 'User/SignUp.html', context)
except User.DoesNotExist:
user = User.objects.create_user(request.POST["Username"], request.POST["Email"], request.POST["Password"])
user.first_name = request.POST["First_Name"]
user.last_name = request.POST["Last_Name"]
user.save()
form_SignUP = SignUpModel(Username = request.POST["Username"], First_Name = request.POST["First_Name"], Last_Name = request.POST["Last_Name"], Email = request.POST["Email"], Company_Name = request.POST["Company_Name"], Address = request.POST["Address"], Password = make_password(request.POST["Password"]), Confirm_Password = make_password(request.POST["Confirm_Password"]), Phone_Number = request.POST["Phone_Number"])
form_SignUP.save()
#queryset = SignUpModel.objects.get(Username = request.POST["Username"])
#queryset.Password = "pwd_removed"
#queryset.Confirm_Password = "pwd_removed"
#queryset.save()
#send_email_to_host(request.POST["First_Name"], request.POST["Family_Name"], request.POST["Number_Of_Adults"], request.POST["Number_Of_Kids"], request.POST["Email"])
return redirect(HomePage)
elif request.POST.get('UserLogin') == 'Login':
form_SignUP = SignUpForm()
form_SignUP_Login=LoginForm(request.POST)
if form_SignUP_Login.is_valid():
user = authenticate(username=request.POST["Username"], password=request.POST["Password"])
if user is not None:
print("User authenticated")
return redirect(HomePage)
else:
print("User not authenticated")
form_SignUP_Login = LoginForm()
Login_message = "Username and password combination is not correct"
elif request.POST.get('UserForgotPassword') == 'Forgot Password':
form_SignUP = SignUpForm()
form_SignUP_Login = LoginForm()
else:
form_SignUP = SignUpForm()
form_SignUP_Login = LoginForm()
return render(request, 'User/SignUp.html', {'form' : form_SignUP, "error":message,'form_login' : form_SignUP_Login, "error_login":Login_message})

Django Redirect treating view as a URL

For some reason, Redirect thinks my call to a view 'clients.views.teacher_profile' is a URL, putting it directly in the address bar as shown:
Page Not Found Screenshot
How do I link it to the view and not treat it as a URL?
Note: I have altered some settings to accommodate django-allauth.
My code:
#views.py
def teacher_profile(request, username):
user = get_object_or_404(User, username=username)
context = {
'user':user,
'teacher':user.teacher,
}
return render(request, 'clients/teacher_profile.html', context)
def edit_profile(request):
teacher = get_object_or_404(Teacher, user=request.user)
if request.method == 'POST':
form = TeacherForm(request.POST, instance=teacher)
if form.is_valid():
teacher = form.save(commit=False)
teacher.user = request.user
teacher.save()
return redirect('clients.views.teacher_profile', username=request.user.username)
else:
form = TeacherForm(instance=teacher)
return render(request, 'clients/edit_profile.html', {'form':form})
#urls.py
urlpatterns = [
url(r'^list/$', views.teacher_list, name='teacher_list'),
url(r'^(?P<username>[\w.#+-]+)/$', views.teacher_profile, name='teacher_profile'),
url(r'^accounts/settings/$', views.edit_profile, name='edit_profile'),
]
Don't use the view's module path in the call to redirect; use the name which you explicitly defined in the url pattern.
return redirect('teacher_profile', username=request.user.username)

Error creating registration template in django . How to debug?

This is my forms.py
from django import forms
from django.core import validators
from django.contrib.auth.models import User
class RegistrationForm(forms.Manipulator):
def __init__(self):
self.fields = (
forms.TextField(field_name='username',
length=30, maxlength=30,
is_required=True, validator_list=[validators.isAlphaNumeric,
self.isValidUsername]),
forms.EmailField(field_name='email',
length=30,
maxlength=30,
is_required=True),
forms.PasswordField(field_name='password1',
length=30,
maxlength=60,
is_required=True),
forms.PasswordField(field_name='password2',
length=30, maxlength=60,
is_required=True,
validator_list=[validators.AlwaysMatchesOtherField('password1',
'Passwords must match.')]),
)
def isValidUsername(self, field_data, all_data):
try:
User.objects.get(username=field_data)
except User.DoesNotExist:
return
raise validators.ValidationError('The username "%s" is already taken.' % field_data)
def save(self, new_data):
u = User.objects.create_user(new_data['username'],
new_data['email'],
new_data['password1'])
u.is_active = False
u.save()
return u
This is my views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
import datetime, random, sha
from django.shortcuts import render_to_response, get_object_or_404
from django.core.mail import send_mail
def login(request):
def errorHandle(error):
form = LoginForm()
return render_to_response('login.html', {
'error' : error,
'form' : form,
})
if request.method == 'POST': # If the form has been submitted...
form = LoginForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# Redirect to a success page.
login(request, user)
return render_to_response('userprof/why.html', {
'username': username,
})
else:
# Return a 'disabled account' error message
error = u'account disabled'
return errorHandle(error)
else:
# Return an 'invalid login' error message.
error = u'invalid login'
return errorHandle(error)
else:
error = u'form is invalid'
return errorHandle(error)
else:
form = LoginForm() # An unbound form
return render_to_response('login.html', {
'form': form,
})
def loggedin(request):
return render_to_response('loggedin.html', {})
def register(request):
if request.user.is_authenticated():
# They already have an account; don't let them register again
return render_to_response('userprof/register.html', {'has_account': True})
manipulator = RegistrationForm()
if request.POST:
new_data = request.POST.copy()
errors = manipulator.get_validation_errors(new_data)
if not errors:
# Save the user
manipulator.do_html2python(new_data)
new_user = manipulator.save(new_data)
# Build the activation key for their account
salt = sha.new(str(random.random())).hexdigest()[:5]
activation_key = sha.new(salt+new_user.username).hexdigest()
key_expires = datetime.datetime.today() + datetime.timedelta(2)
# Create and save their profile
new_profile = UserProfile(user=new_user,
activation_key=activation_key,
key_expires=key_expires)
new_profile.save()
# Send an email with the confirmation link
email_subject = 'Your new example.com account confirmation'
return render_to_response('userprof/register.html', {'created': True})
else:
errors = new_data = {}
form = forms.FormWrapper(manipulator, new_data, errors)
return render_to_response('userprof/register.html', {'form': form})
def confirm(request, activation_key):
if request.user.is_authenticated():
return render_to_response('userprof/confirm.html', {'has_account': True})
user_profile = get_object_or_404(UserProfile,
activation_key=activation_key)
if user_profile.key_expires < datetime.datetime.today():
return render_to_response('confirm.html', {'expired': True})
user_account = user_profile.user
user_account.is_active = True
user_account.save()
return render_to_response('confirm.html', {'success': True})
This is the template I am planning to use
https://github.com/yourcelf/django-registration-defaults/tree/master/registration_defaults/templates .
According to it , I did changes in the settings.py , but it gave me an error
Error: Can't find the file 'settings.py' in the directory containing 'manage.py'. It appears you've customized things.
You'll have to run django-admin.py, passing it your settings module.
(If the file settings.py does indeed exist, it's causing an ImportError somehow.)
Is it a good idea to use those templates or should I go for my own custom templates ?
Wow, what version of Django are you using? forms.Manipulator was removed in version 1.0 - three years ago - and was deprecated for a year before that.
I'm guessing that your project has an import problem - but Django catches this and doesn't show you the real error. Note that this does not need to be an import from settings.py - it can be an import anywhere in the project.
Try running:
python settings.py
And python should tell you what the import problem is. If there is no output, your problem is elsewhere - but this is a very likely candidate.

Django | how to append form field to the urlconf

I want to pass a form's field value to the next page (template) after user submit the page, the field could be user name, consider the following setup
def form_submit(request):
if request.method == 'POST':
form = UsersForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
try:
newUser = form.save()
return HttpResponseRedirect('/mysite/nextpage/')
except Exception, ex:
return HttpResponse("Error %s" % str(ex))
else:
return HttpResponse('Error')
"nextpage" is the template that renders after user submit the form, so I want to know how to append the form's field (user name) to the url and get that value from the view in order to pass it to the next page..
thanks.
Change redirect in your controller to include the user name (I guessed at the field name):
def form_submit(request):
if request.method == 'POST':
form = UsersForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
try:
newUser = form.save()
return HttpResponseRedirect('/mysite/nextpage/{0}/'.format(newUser.UserName)
except Exception, ex:
return HttpResponse("Ane apoi %s" % str(ex))
else:
return HttpResponse('Error')
Then you will need a new controller:
def user_redirected_here(request, username):
#do something
And finally add something like this to your urls.py to route to the new view:
urlpatterns = patterns('',
(r"^nextpage/.+$", user_redirected_here),
)