Hi i know there is many of these asking about routing from a veiw to a new app in django. I have looked at a lot of them. And figured out to use app_name = 'name' and to use named routes for my html templates makes everything easier for sure. When i try to use a app_name:named-route i get this :
ValueError at /recipedashboard
The view recipeApp.views.dashboard didn't return an HttpResponse object. It returned None instead.
I have gotten the name_app:named-route to send me to the second app, but how do i pass the session to the new app?
userApp veiws:
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import User as LoggedUser
# Create your views here.
def index(request):
return render(request, 'index.html')
def register(request):
if request.method == "GET":
return redirect('/')
errors = LoggedUser.objects.validate(request.POST)
if len(errors) > 0:
for er in errors.values():
messages.error(request, er)
return redirect('/')
else:
new_user = LoggedUser.objects.register(request.POST)
request.session['user_id'] = new_user.id
messages.success(request, "You have successfully registered")
return redirect('/success')
def login(request):
if request.method == "GET":
return redirect('/')
if not LoggedUser.objects.authenticate(request.POST['email'],
request.POST['password']):
messages.error(request, "Invalid Email/Password")
return redirect('/')
user = LoggedUser.objects.get(email=request.POST['email'])
request.session['user_id'] = user.id
messages.success(request, "You have successfully logged in!")
return redirect('/success')
def logout(request):
request.session.clear()
return redirect('/')
def success(request):
if 'user_id' not in request.session:
return redirect('/')
context = {
'user' : LoggedUser.objects.get(id=request.session['user_id'])
}
return redirect("recipe:recipe-dashboard")
recipeApp urls.py:
from django.urls import path
from . import views as recipeViews
app_name ='recipe'
urlpatterns = [
path('dashboard', recipeViews.dashboard, name= "recipe-dashboard" )
]
recipeApp.Views :
from django.shortcuts import render, redirect
from userApp.models import User as LoggedUser
# Create your views here.
def dashboard(request):
if 'user_id' not in request.session:
return redirect('/')
user = LoggedUser.objects.get(id=request.session['user_id'])
context = {
'user' : user
}
render (request, 'dashboard.html', context)
Your dashboard view is not returning anything.
You need to return the results of render. Like
from django.shortcuts import render, redirect
from userApp.models import User as LoggedUser
# Create your views here.
def dashboard(request):
if 'user_id' not in request.session:
return redirect('/')
user = LoggedUser.objects.get(id=request.session['user_id'])
context = {
'user' : user
}
return render (request, 'dashboard.html', context)
There is no need to deal with passing a session. The framework will handle that for you if the apps are all under the same project.
Related
I am trying to create a login and logout page for my sample project and have coded all logic up. The tutorial I was following used the following code
from django.shortcuts import render
from basic_app.forms import UserForm
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect,HttpResponse
from django.urls import reverse
from django.contrib.auth.decoraters import login_required
# Create your views here.
def index(request):
return render(request,'basic_app/index.html')
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'basic_app/registration.html',
{'user_form':user_form,
'registered':registered })
#login_required
def special(request):
return HttpResponse("You are logged in!")
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
def user_login(request):
if request.method == 'POST':
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 HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account Not Active")
else:
print("Someone tried to login and failed")
print("Username:{} and password: {}".format(username,password))
return HttpResponse("Invalid login details supplied")
else:
return render(request,'basic_app/login.html',{})
The error I am getting is this
from django.contrib.auth.decoraters import login_required
ModuleNotFoundError: No module named 'django.contrib.auth.decoraters'
You make spelling mistakes while importing the decorators:
Change:
from django.contrib.auth.decoraters import login_required
To:
from django.contrib.auth.decorators import login_required
I'm making a registration system for students in Django
When the user enters the student number, the system retrieves all the student data.
How can I work in this
def search(request):
if request.method== 'POST':
srch = request.POST['srh']
if srch:
match = Regiest_Form.objects.filter(Q(std_name__iexact=srch))
if match:
return render(request, 'Regiest_app/search.html', {'sr':match})
else:
messages.error(request,'no result')
else:
return HttpResponseRedirect('/search/')
else:
return render(request, 'Regiest_app/search.html')
Wow, you're missing a whole part of django's purpose.
Using django's form, you can delegate all your validation to your form.
If no results are found, your access errors using 'form.errors' and 'form.non_field_errors` within your template.
In forms.py
from django import forms
from .models import Regiest_Form
class RegisterSearchForm(forms.Form):
search=forms.Charfield(required=True)
def clean(self):
qs=Regiest_Form.objects.filter(Q(std_name__iexact=self.cleaned_data.get('search'))
if qs.exists():
self.add_error(field=None,error=forms.ValidationError("No results found"))
else:
return self.cleaned_data
#property
def results(self):
return Regiest_Form.objects.filter(Q(std_name__iexact=self.cleaned_data.get('search'))
In your views.py
from .forms import RegisterSearchForm
def search(request):
form = RegisterSearchForm(request.POST) if request.method== 'POST' else RegisterSearchForm()
if request.method== 'POST' and form.is_valid():
return render(request, 'Regiest_app/search.html',{'sr':forms.results, 'form':form})
return render(request, 'Regiest_app/search.html',{'form':form})
I am trying to enter the details in login form.But it is not authenticating the username and password with the existing usernames and passwords present in form data.
Here is my code
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from . forms import signup_form,loginform,profileform
from . models import registration_form
def index(request):
return render(request,'loginapp/index.html')
def display_form(request):
rform = signup_form(request.POST)
if rform.is_valid():
rform.save()
return HttpResponseRedirect('/profile/')
else:
return render(request,'loginapp/first.html',{'rform': rform})
def login_form(request):
if request.method == 'POST':
Username = request.POST.get('Username')
Password = request.POST.get('Password')
registration_form=
authenticate(Username=Username,Password=Password)
print("Username")
if registration_form is None:
if registration_form.is_active:
login(request,registration_form)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Your account was inactive.")
else:
print("Someone tried to login and failed.")
print("They used Username: {} and Password:
{}".format(Username,Password))
return HttpResponse("Invalid login details given")
return HttpResponseRedirect('/profile/')
else:
return render(request, 'loginapp/login.html', {})
def profile_form(request):
return render(request,'loginapp/profile.html')
I am running: Django==2.0.6 / python==3.6.5 / django-allauth==0.36.0
I have not touched this project in several weeks. I upgraded a number of packages before starting this round of development.
I can currently create a new user account and verify the email address used as the username. The user model is "extended" in that I use the email address for the username and have a "Profile" class to hold additional interesting fields.
I was once able to create a new account, verify the email address and be taken to a form to fill out that additional interesting info. Now, after email verification there is a noticable pause and then I am told that I have ben redirected too many times.
My urls.py looks like:
from django.urls import path, re_path
from .views import index
from .views import profile
urlpatterns = [
re_path(r'^', index, name='index'),
path('Profile/<uuid:account_number>/edit', profile.Update.as_view(), name="profile-update"),
path('Profile/<uuid:account_number>/delete', profile.Delete.as_view(), name="profile-delete"),
path('Profile/create', profile.Create.as_view(), name="profile-create"),
]
The Profile CBV is:
import django.contrib.messages as messages
from allauth.account.decorators import verified_email_required
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, UpdateView, DeleteView
from Members.forms.profile import ProfileForm
from Members.models.profile import Profile
import datetime
#method_decorator(verified_email_required, name='dispatch')
class Create(CreateView):
model = Profile
template_name = 'Members/profile.html'
form_class = ProfileForm
success_url = 'Members/index.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name, {
'profileForm': self.form_class(),
'profileState': "create"
})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.user = self.request.user
profile.save()
my_render = render(request, self.success_url, {
'profile': profile,
'profileState': "display"
})
else:
#
# form has issues. send it back to the create form to fix.
my_render = render(request, self.template_name, {
'profileForm': form,
'profileState': "editForCreate"
})
return my_render
#method_decorator(verified_email_required, name='dispatch')
class Update(UpdateView):
pk_url_kwarg = "account_number"
model = Profile
template_name = 'Members/profile.html'
form_class = ProfileForm
success_url = 'Members/index.html'
def get(self, request, *args, **kwargs):
profile = Profile.objects.get(account_number=self.kwargs[self.pk_url_kwarg])
form = ProfileForm(instance=profile)
return render(request, self.template_name, {
'profileForm': form,
'profileState': "edit"
})
def post(self, request, *args, **kwargs):
profile = Profile.objects.get(account_number=self.kwargs[self.pk_url_kwarg])
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.dateModified = datetime.datetime.now()
profile.save()
my_render = render(request, 'Members/index.html', {
'profile': profile
})
else:
#
# form has issues. send it back to the create form to fix.
my_render = render(request, self.template_name, {
'profileForm': form,
'profileState': "editForUpdate"
})
return my_render
#method_decorator(verified_email_required, name='dispatch')
class Delete(DeleteView):
pk_url_kwarg = "account_number"
model = Profile
# form_class = ProfileForm
success_url = "account/login.html"
def get(self, request, *args, **kwargs):
try:
#
# I can't believe django does not honor on_delete cascade.
# Have to roll your own. Tsk
owner = self.request.user
profile = get_object_or_404(Profile, account_number=self.kwargs[self.pk_url_kwarg])
user_pk = profile.user.pk
profile.delete()
get_object_or_404(User, pk=user_pk).delete()
messages.success(request, "The user is deleted")
except User.DoesNotExist:
messages.error(request, "User does not exist")
# except IntegrityError:
# messages.error(request, "DB IntegrityError")
return redirect("accounts/login/")
How do you go about debugging this? Ive tried setting breakpoints in PyCharm but they are ignored or ar in the wrong places.
in your urls.py you need to add $ in order to close your regular expression
urlpatterns = [
re_path(r'^$', index, name='index'),
]
my views.py:
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import render
from django.views.generic import View
from .forms import LoginForm, RegistrationForm
class Login(View):
form_class = LoginForm
initial = {'key': 'value'}
template_name = 'web/login.html'
def get(self, request):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request):
if request.method == 'POST':
form = self.form_class(initial=self.initial)
if form.is_valid():
email=form.cleaned_data['email']
password=form.cleaned_data['password']
auser = User.objects.get(email=email)
username = auser.username
buser = authenticate(username, password)
if buser:
if buser.is_active:
login(request, buser)
return HttpResponse('Good to Go...')
else:
return HttpResponse('your account is disabled...')
else:
print "Invalid login details: {0}, {1}".format(email, password)
HttpResponse('invalid login details...')
else:
return HttpResponse('Form is not valid!')
else:
form = self.form_class()
Here above I'm trying to login a user using email as unique field in class based views. But It raises 'Form is not valid!' as I specified in my views. I don't know what's going wrong with it exactly. Please Help me how to fix it?
Thanks in Advance
You need to change the post method of this class:
def post(self, request):
if request.method == 'POST':
form = self.form_class(data=self.request.POST)
if form.is_valid():
.....