Views.py
from django.shortcuts import render
from django.template.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from .models import studentDetails
from .forms import loginForm
# Create your views here.
def login(request):
c = {}
c.update(csrf(request))
return render(request, "login.html", c)
def auth_view(request):
username = request.POST.get("username", "")
password = request.POST.get("password", "")
q = studentDetails.objects.get(name=username)
if q.password==password:
return HttpResponseRedirect("/student/accounts/loggedin")
return HttpResponseRedirect("/studemt/accounts/invalid")
def loggedin(request):
username = request.GET.get("username")
return render(request, "loggedin.html", {"full_name": username})
def invalid(request):
return render(request, "invalid_login.html")
def logout(request):
return render(request, "logout.html")
Urls.py
from django.conf.urls import url
from django.contrib import admin
from .views import (
login,
auth_view,
loggedin,
logout
)
urlpatterns = [
url(r"^accounts/login/$", login , name="login"),
url(r"^accounts/auth/$", auth_view ,name="auth_view"),
url(r"^accounts/loggedin/$", loggedin , name="loggedin"),
url(r"^accounts/logout/$", logout, name="logout"),
]
i want to send username from auth_view to loggedin view but i don'y know how to do that.
i have used username = request.GET.get("username") but it is not working.
i want to show username in url also such that it looks like /student/username/
where username will change as different user login.
You should pass parameter in url first:
url(r'^student/(?P<username>\w+)/$', views.userpage, name='userpage)
But better use pk field or something with name + pk, as url parametr, because username can be duplicate.
Now you can pass this parameter in view and don't hardcore url, use reverse with url name instead.
def auth_view(request):
username = request.POST.get("username", "")
password = request.POST.get("password", "")
q = studentDetails.objects.get(name=username)
if q.password==password:
return HttpResponseRedirect(reverse('userpage', args=[q.username]))
return HttpResponseRedirect(reverse('invalid'))
Related
So I'm creating a web app in Django, and I encountered this error:
my urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:user_id>/', views.profile, name="profile"),
#path('signup/', views.signup, name="signup"),
path("signup/", views.signup, name="signup")
]
my views.py:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth import forms
from django.urls import reverse_lazy
from django.http import HttpResponse, Http404
from django.template import loader
from .models import User
from .forms import SignUpForm
from datetime import datetime
def index(request):
cool_people_list = User.objects.order_by("-username")[:5]
_template = loader.get_template("front_page.html")
context = {
"cool_people_list" : cool_people_list,
}
return HttpResponse(_template.render(context, request))
def profile(request, user_id):
try:
user = get_object_or_404(User, pk=user_id)
_template = loader.get_template("profile.html")
context = {
"user" : user
}
return HttpResponse(_template.render(context, request))
except:
raise Http404("The user you are looking for doesn't exist.")
def signup(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
rn = str(datetime.today().strftime("%Y-%m-%D"))
rn2 = str(datetime.today)
"""usr_list = User.objects.order_by('-join_date')
latest_usr = usr_list.first()"""
new_user = User(3, str(form.cleaned_data.get("username")), str(form.cleaned_data.get("password")), rn, rn2)
new_user.save()
return render(request, "signup.html")
my models.py:
from django.db import models
from django.core.validators import MinLengthValidator
import datetime
class User(models.Model):
user_id = models.IntegerField(unique=True)
username = models.CharField(max_length=25, validators=[MinLengthValidator(3)])
password = models.CharField(max_length=25, validators=[MinLengthValidator(7)])
join_date = models.DateField()
last_online = models.DateTimeField()
def __str__(self):
return self.username
I kept trying different methods, like manually adding the user ID (temporary fix), but Django can't see where I type in the ID! It doesn't register it when I typed it in what I believe is the correct format for my 'User' model.
You need to save an object in User Model like this...
def signup(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
rn = datetime.today().strftime("%Y-%m-%D")
rn2 = datetime.today
new_user = User(username= form.cleaned_data["username"], password=form.cleaned_data["password"], rn=rn, rn2=rn2)
new_user.save()
else:
form.errors
return render(request, "signup.html")
I'm newbie in Django
I have a trouble with this:
I've already make API for 'request-reset-email', 'password-reset' and 'password-reset-complete'
Here are the code:
file: urls.py
from django.urls import path
from .views import *
from django.contrib.auth import views as auth_view
from rest_framework_simplejwt.views import (
TokenObtainSlidingView,
TokenRefreshSlidingView,
)
urlpatterns=[
path('register/', RegisterView.as_view(), name="register"),
path('login/', LoginAPIView.as_view(), name="login"),
path('email-verify/', VerifyEmail.as_view(), name="email-verify"),
path('token/refresh/', TokenRefreshSlidingView.as_view(), name='token_refresh'),
path('request-reset-email/',RequestPasswordResetEmail.as_view(), name='request-reset-email'),
path('password-reset/<uidb64>/<token>/',PasswordTokenCheckAPIView.as_view(),name='password-reset'),
path('password-reset-complete/',SetNewPasswordAPIView.as_view(),name='password-reset-complete')
]
file Views.py:
from django.shortcuts import render
from rest_framework import exceptions, generics, serializers
from rest_framework.response import Response
from rest_framework import status
from .models import *
from .serializers import *
from rest_framework_simplejwt.tokens import RefreshToken
from .utils import *
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse
import jwt
from django.conf import settings
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils.encoding import smart_str, force_str, smart_bytes, DjangoUnicodeDecodeError
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
# Create your views here.
class RegisterView(generics.GenericAPIView):
queryset = User.objects.all()
serializer_class=RegisterSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user= User.objects.get(email=user_data['email'])
token=RefreshToken.for_user(user).access_token
current_site=get_current_site(request).domain
realtivelink = reverse('email-verify')
absurl='http://'+current_site+realtivelink+"?token="+ str(token)
email_body='Hi '+ user.email+ ' Use link below to verify your email \n' + absurl
data={'email_body':email_body,'to_email':user.email,'email_subject':'Verify your email'}
Util.send_email(data)
return Response(user_data,status= status.HTTP_201_CREATED)
class VerifyEmail(generics.GenericAPIView):
def get(self,request):
token= request.GET.get('token')
try:
payload=jwt.decode(token,settings.SECRET_KEY,algorithms='HS256')
user=User.objects.get(id=payload['user_id'])
if not user.is_verified:
user.is_verified=True
user.save()
return Response({'email':'Successfully activated'},status= status.HTTP_200_OK)
except jwt.ExpiredSignatureError as indentifier:
return Response({'email':'Activation expired'},status= status.HTTP_400_BAD_REQUEST)
except jwt.exceptions.DecodeError as indentifier:
return Response({'email':'Invalid token'},status= status.HTTP_400_BAD_REQUEST)
class LoginAPIView(generics.GenericAPIView):
queryset = User.objects.all()
serializer_class = LoginSerializers
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data,status=status.HTTP_200_OK )
class RequestPasswordResetEmail(generics.GenericAPIView):
queryset = User.objects.all()
serializer_class=ResetPasswordViaEmailSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
email = request.data['email']
if User.objects.filter(email=email).exists():
user = User.objects.get(email=email)
uidb64 = urlsafe_base64_encode(smart_bytes(user.id) )
token = PasswordResetTokenGenerator().make_token(user)
current_site=get_current_site(request=request).domain
realtivelink = reverse('password-reset',kwargs={'uidb64':uidb64,'token':token})
absurl='http://'+current_site+realtivelink
email_body='Hi, \nUse link below to reset your password \n' + absurl
data={'email_body':email_body,'to_email':user.email,'email_subject':'Reset your password'}
Util.send_email(data)
return Response({'successfully':'check your email to reset your password'},status=status.HTTP_200_OK)
class PasswordTokenCheckAPIView(generics.GenericAPIView):
def get(self, request, uidb64,token):
try:
id= smart_str(urlsafe_base64_decode(uidb64))
user= User.objects.get(id=id)
if not PasswordResetTokenGenerator().check_token(user,token):
return Response({'error':'token is not valid, please check the new one'},status=status.HTTP_401_UNAUTHORIZED)
return Response({'sucess':True, 'message':'Credential Valid','uidb64':uidb64, 'token':token},status=status.HTTP_200_OK)
except DjangoUnicodeDecodeError as indentifier:
return Response({'error':'token is not valid, please check the new one'},status=status.HTTP_401_UNAUTHORIZED)
class SetNewPasswordAPIView(generics.GenericAPIView):
queryset = User.objects.all()
serializer_class=ResetPassWordSerializer
def patch(self, request):
serializer=self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
return Response({'sucess':True, 'message':'Password is reset successfully'},status=status.HTTP_200_OK)
APIs've already worked. But I want to make the "PasswordTokenCheckAPIView" have a templete for user to enter the new password and confirm it. So, could you please to give me some way to do this? I've tried to use django.contrib.auth.PasswordResetConfirmView, it appears the template when I click the link I received in mail, but when I confirm change password, there is error
from django.urls import path
from .views import *
from django.contrib.auth import views as auth_view
from rest_framework_simplejwt.views import (
TokenObtainSlidingView,
TokenRefreshSlidingView,
)
urlpatterns=[
path('register/', RegisterView.as_view(), name="register"),
path('login/', LoginAPIView.as_view(), name="login"),
path('email-verify/', VerifyEmail.as_view(), name="email-verify"),
path('token/refresh/', TokenRefreshSlidingView.as_view(), name='token_refresh'),
path('request-reset-email/',RequestPasswordResetEmail.as_view(), name='request-reset-email'),
path('password-reset/<uidb64>/<token>/',auth_view.PasswordResetConfirmView.as_view(),name='password-reset'),
path('password_reset_complete/',auth_view.PasswordResetCompleteView.as_view(),name='password-reset-complete')
]
the error: Reverse for 'password_reset_complete' not found. 'password_reset_complete' is not a valid view function or pattern name.
Thank you very much!
Change
path('password_reset_complete/',auth_view.PasswordResetCompleteView.as_view(),name='password-reset-complete')
to
path('password_reset_complete/',auth_view.PasswordResetCompleteView.as_view(),name='password_reset_complete')
Django reverse checks for name in the path.
I am trying to build a form to be used in 2 pages (index and contact).
Once the form performs method post, it will bring a page either success or failed (simple html page with few words).
I am stuck due to the error shown above and I’m still new in using Django.
Appreciate any help. Thank you
urls.py
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^app/', include('app.urls'))
]
app/url.py
from .views import *
app_name = "app"
urlpatterns = [
url(r'^home/$', home, name='home'),
url(r'^contact/$', contact, name='contact'),
url(r'^send_message/(?P<flag>\d+)/$', send_form, name='send_form'),
url(r'^send_message/success/$', success, name='success'),
url(r'^send_message/failed/$', failed , name='failed'),
]
views.py
from django.core.mail import send_mail
from .forms import MessagesForm
from django.conf import settings
rom django.shortcuts import render, redirect
def home(request):
empty_form = send_form(request)
cover_title = PageServiceCover.objects.latest('id').title
cover_text = PageServiceCover.objects.latest('id').text
context = {'cover_title': cover_title, 'cover_text': cover_text,'form':empty_form}
return render(request, 'index.html', context)
def send_form(request):
if request.method == 'POST':
form = MessagesForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
category = form.cleaned_data['category']
text = form.cleaned_data['text']
form.save()
subject=[name, phone, category]
send_mail(subject, text, email, [settings.EMAIL_HOST_USER], fail_silently=False)
return redirect('thanks', flag='success' )
else:
return redirect('not_working', flag='failed')
def success(request):
return render(request, 'thanks.html')
def failed(request):
return render(request, 'notworking.html')
index.html
<form action="{% url 'app:send_form' %}" method="POST" target="_blank">
{%csrf_token%}
{{form.as_p}}
<button type="submit"> Send Message </button>
</form>
Your url need a flag
url(r'^send_message/(?P<flag>\d+)/$', send_form, name='send_form'),
change view and pass flag from template
def send_form(request, flag):
if request.method == 'POST':
form = MessagesForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
category = form.cleaned_data['category']
text = form.cleaned_data['text']
form.save()
subject=[name, phone, category]
send_mail(subject, text, email, [settings.EMAIL_HOST_USER], fail_silently=False)
return redirect('thanks', flag='success' )
else:
return redirect('not_working', flag='failed')
please help so solve my problem, when i open the activation link in email, then it will show init() takes 1 positional argument but 2 were given, help
this is my signup views
def signup(request):
if request.method == 'POST':
user_form = UserCreationForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
profile = profile_form.save(commit=False)
user.is_active = False
user.save()
profile.save()
uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
domain = get_current_site(request).domain
link=reverse('activate', kwargs={
'uidb64': uidb64, 'token': token_generator.make_token(user)})
activate_url = 'http://'+domain+link
email_body = 'Hallo '+user.username + 'Tolong gunakan link ini untuk verifikasi akun anda\n' +activate_url
email_subject = 'Aktivasi Akun Anda'
email = EmailMessage(
email_subject,
email_body,
'noreply#kantorkecamatanbintanutara.com',
[profile.email],
)
email.send(fail_silently=False)
return redirect('/pengurusan/signin')
else:
return render(request, 'pengurusan/register.html', {
'user_form': user_form,
'profile_form': profile_form
})
this is my verification view
class VerificationView(View):
def get(self, request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
if not token_generator.check_token(self, user, token):
return redirect('pengurusan/signup'+'?message'+'User already activated')
if user.is_active:
return redirect('pengurusan/signin')
user.is_active = True
user.save()
messages.success(request, 'Account activated successfully')
return redirect('pengurusan/signup')
except Exception as ex:
pass
return redirect('pengurusan/signin')
this is my utils.py
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from six import text_type
class AppTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (text_type(user.is_active)+text_type(user.pk)+text_type(timestamp))
token_generator = AppTokenGenerator()
this is my urls.py
from django.conf import settings
from django.conf.urls import include, url
from django.urls import path
from django.conf.urls.static import static
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.signin),
url(r'index/$', views.index),
url(r'signin/$', views.signin),
url(r'signup/$', views.signup),
url(r'signout/$', views.signout),
path('activate/<uidb64>/<token>', views.VerificationView, name="activate"),
]
Try adding .as_view() to all the views that are class based (not function based):
urlpatterns = [
url(r'^$', views.signin),
url(r'index/$', views.index),
url(r'signin/$', views.signin),
url(r'signup/$', views.signup),
url(r'signout/$', views.signout),
path('activate/<uidb64>/<token>', views.VerificationView.as_view(), name="activate"),
]
I've got following code and got two issues.
1. I couldn't get joins added up and not showing up on the page.
2. Admin interface is not loading.
I've re-created the DB checked the code thoroughly and really need help.
Views.py.
from django.conf import settings
from django.shortcuts import render, HttpResponseRedirect, Http404
from.models import Join
from .forms import EmailForm, JoinForm
def get_ip(request):
try:
x_forwarded = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded:
ip = x_forwarded.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR")
except:
ip = ""
return ip
import uuid
def get_ref_id():
ref_id = str(uuid.uuid4())[:11].replace('-', '').lower()
try:
id_exists = Join.objects.get(ref_id=ref_id)
get_ref_id()
except:
return ref_id
def home(request):
try:
join_id = request.session['join_id_ref']
obj = Join.objects.get(id=join_id)
except:
obj = None
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
email = form.cleaned_data['email']
new_join_old, created = Join.objects.get_or_create(email=email)
if created:
new_join_old.ref_id = get_ref_id()
if not obj == None:
new_join_old.friend = obj
new_join_old.ip_address = get_ip(request)
new_join_old.save()
return HttpResponseRedirect("/%s" %(new_join_old.ref_id))
context = {"form": form}
template = 'home.html'
return render(request, template, context)
def share(request, ref_id):
#try:
join_obj = Join.objects.get(ref_id=ref_id)
friends_referred = Join.objects.filter(friend=join_obj)
count = join_obj.referral.all().count()
ref_url = settings.SHARE_URL + str(join_obj.ref_id)
context = {"ref_id": join_obj.ref_id, "count": count, "ref_url": ref_url}
template = "share.html"
return render(request, template, context)
#except:
#raise Http404
Error message I am getting after commenting out exception is:
DoesNotExist at /admin
Join matching query does not exist. Lookup parameters were {'ref_id': u'admin'}
Urls.py includes following.
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'joins.views.home', name='home'),
url(r'^(?P<ref_id>.*)$', 'joins.views.share', name='share'),
)
Your regular expression in line
url(r'^(?P<ref_id>.*)$', 'joins.views.share', name='share'),
matches admin/ as well you should use something less "greedy".