__init__() takes 1 positional argument but 2 were given django email activation - python

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"),
]

Related

Django Can't See Where I Typed in User ID

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")

__init__() got an unexpected keyword argument 'user_id' in django

i have a form for update view like this:
class editpost(forms.ModelForm):
class Meta:
model = Posts
fields = ['body']
and a view like this:
#login_required
def post_edit(request, user_id, post_id):
if request.user.id == user_id:
post = get_object_or_404(Post, pk=post_id)
if request.method == 'POST':
form = editpost(request.POST, instance=post)
if form.is_valid():
ep = form.save(commit=False)
ep.slug = slugify(form.cleaned_data['body'][:30])
ep.save()
messages.success(request, 'your post edited successfully', 'success')
return redirect('account:dashboard', user_id)
else:
form = EditPostForm(instance=post)
return render(request, 'editpost.html', {'form':form})
else:
return redirect('Posts:index')
and url.py like this:
from django.urls import path
from . import views
app_name = 'Posts'
urlpatterns = [
path('', views.index.as_view(),name='index'),
path('<int:year>/<int:month>/<int:day>/<slug:slug>', views.detailPost,name='detail'),
path('addpost/<int:user_id>', views.addpost,name='addpost'),
path('delpost/<int:user_id>/<int:post_id>', views.delpost,name='delpost'),
path('editpost/<int:user_id>/<int:post_id>', views.editpost,name='editpost'),
]
when i open editpost url i got this error,what should i do to fix it?
The path for editpost should point to your view method: views.post_edit not views.editpost
path('editpost/<int:user_id>/<int:post_id>', views.post_edit, name='editpost'),

Why my django code is not sending Email to my newly register user?

I want to verify new user registration by sending confirmation token to email of user. the code is showing no error in console but also not sending the email to user email. i am using django 3.0 and python 3.8.
the code is executing this part, when i signup a new user, this message poput but i am not receiving email "Open your email to activate account."
help me to fix this:
views.py
from .forms import CreateUserForm
from django.views import View
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from .tokens import activation_token
from django.contrib.auth.models import User
from django.contrib import messages
class RegisterPageView(View):
def get(self, request, *args, **kwargs):
form = CreateUserForm()
template_name = "register/register.html"
return render(request, template_name, {"form": form})
def post(self, request, *args, **kwargs):
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
message_subject = "Activate your account"
domain_url = get_current_site(request)
user_email = form.cleaned_data["email"]
message = render_to_string(
"Backend/accounts/activation_message.html",
{
"domain": domain_url.domain,
"user": user,
"uid": urlsafe_base64_encode(force_bytes(user.id)),
"token": activation_token.make_token(user),
},
)
email = EmailMessage(message_subject, message, to=[user_email])
email.send()
activation_msg = "Open your email to activate account."
return render(
request, "Backend/accounts/activate_email.html", {"activation_msg": activation_msg}
)
template_name = 'register/register.html'
return render(request, template_name, {"form": form})
urls.py
from django.urls import path
from .views import *
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', index, name="index"),
path("activate/<uidb64>/<token>", activate, name="activate"),
path("register/", RegisterPageView.as_view(), name="register"),
]
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ("username", "email", "password1", "password2","first_name","last_name")
def clean_email(self):
data = self.cleaned_data["email"]
try:
user_email = User.objects.get(email=data)
except User.DoesNotExist:
pass
else:
raise forms.ValidationError("Email already exist")
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'mymail'
EMAIL_HOST_PASSWORD = 'mypassword'
Following could be one of the possibilities:
Make sure that SMTP congifuration of your gmail account is alright and it allows access to django:
https://support.google.com/accounts/answer/6010255?hl=en
You can if it is not the problem of smtp by sending the email to console by changing EMAIL_BACKEND 'django.core.mail.backends.smtp.EmailBackend' To "django.core.mail.backends.console.EmailBackend"
If email is displayed in console try account adapters settings: https://django-allauth.readthedocs.io/en/latest/configuration.html
Alternatively, you can try this code as it works for me:
subject = 'Thank you for registering to our site'
message = 'this is a test message'
email_from = 'xyz#gmail.com'
recipient_list = ['reciever#gmail.com', ]
connection = [
'xyz#gmail.com',
'mypassword',
False,
]
send_mail(subject, message, email_from, recipient_list, connection)
for this you will have to import send_mail: https://docs.djangoproject.com/en/3.0/topics/email/
Your email setting in setting.py should look like this:
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com" # mail service smtp
EMAIL_HOST_USER = "youremail#gmail.com" # mymial is not any email: use environment variable to hide your email in production.
EMAIL_HOST_PASSWORD = "your email password" # password
EMAIL_PORT = 587
EMAIL_USE_TLS = True
Note: You should make your gmail account less secure.
Go to this link
And do as in figure.
Alternatively, you can try this:
class RegisterPageView(View):
def get(self, request, *args, **kwargs):
form = CreateUserForm()
template_name = "register/register.html"
return render(request, template_name, {"form": form})
def post(self, request, *args, **kwargs):
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
message_subject = "Activate your account"
domain_url = get_current_site(request)
user_email = form.cleaned_data["email"]
message = render_to_string(
"Backend/accounts/activation_message.html",
{
"domain": domain_url.domain,
"user": user,
"uid": urlsafe_base64_encode(force_bytes(user.id)),
"token": activation_token.make_token(user),
},
)
user.email_user(subject, message) #try this
activation_msg = "Open your email to activate account."
return render(
request, "Backend/accounts/activate_email.html", {"activation_msg": activation_msg}
)
template_name = 'register/register.html'
return render(request, template_name, {"form": form})
I updated some part and rest are same..
from django.core.mail import send_mail
class RegisterPageView(View):
def get(self, request, *args, **kwargs):
form = CreateUserForm()
template_name = "register/register.html"
return render(request, template_name, {"form": form})
def post(self, request, *args, **kwargs):
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
subject = "Activate your account"
domain_url = get_current_site(request)
message = render_to_string(
"Backend/accounts/activation_message.html",
{
"domain": domain_url.domain,
"user": user,
"uid": urlsafe_base64_encode(force_bytes(user.pk)),
"token": activation_token.make_token(user),
},
)
to_email = form.cleaned_data.get('email')
send_mail(subject, message, 'mygmail#gmail.com', [to_email])
activation_msg = "Open your email to activate account."
return render(
request, "Backend/accounts/activate_email.html", {"activation_msg": activation_msg}
)
template_name = 'register/register.html'
return render(request, template_name, {"form": form})
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and activation_token.check_token(user, token):
user.is_active = True
user.profile.email_confirmed = True
user.save()
login(request, user)
return redirect('login')
else:
return render(request, "Backend/accounts/activation_fail.html")
i used email_confirmed to check email validtion,
also i added email_confirmed = models.BooleanField(default=False) this line in my user profile
class Profile(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True)
phone=models.CharField("Write Phone Name", max_length=100,null=True,blank=True)
image=models.ImageField("Upload Client Image",null=True,blank=True)
gender=models.CharField("Write gender", max_length=100,null=True,blank=True)
position=models.CharField("Designation", max_length=100,null=True,blank=True)
email_confirmed = models.BooleanField(default=False)
thats all.. thanks for your help

'AnonymousUser' object has no attribute '_meta'

views.py code
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from tutorial import views
from accounts.form import Registrationform,EditProfileForm
from django.contrib.auth.forms import UserChangeForm,PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth import update_session_auth_hash
# Create your views here.
def home(request):
numbers=[1,2,3,4,5]
name="jay"
args={'myName':name}
return render(request,'accounts/home.html',args)
def register(request):
if request.method == "POST":
form = Registrationform(request.POST)
if form.is_valid():
form.save()
return redirect('/account')
else:
return HttpResponse('please fill all the fields and make sure new password must be match')
else:
form = Registrationform()
args={'form' : form}
return render(request,'accounts/reg_form.html',args)
def view_profile(request):
args = {'user' : request.user}
return render(request,'accounts/profile.html',args)
def edit_profile(request):
if request.method=="POST":
form = EditProfileForm(request.POST,instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = EditProfileForm(instance=request.user)
args = {'form' : form}
return render(request,'accounts/edit_profile.html',args)
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(data=request.POST,user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect('/account/profile')
else:
return HttpResponse("password doest not match,go back and try again")
else:
form = PasswordChangeForm(user=request.user)
args = {'form' : form}
return render(request,'accounts/change_password.html',args)
and form.py is
from django import forms
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from django.contrib.auth.models import User
#from django.forms import RegistrationForm,EditProfileForm
class Registrationform(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
)
def save(self,commit=True):
user=super(Registrationform,self).save(commit=False)
user.first_name= self.cleaned_data['first_name']
user.last_name=self.cleaned_data['last_name']
user.email=self.cleaned_data['email']
if commit:
user.save()
return user
class EditProfileForm(UserChangeForm):
#template_name = '/something/else'
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name',
'password'
)
and urls.py
#python -m smtpd -n -c DebuggingServer localhost:1025
from django.contrib import admin
from .import views
from django.conf.urls import url,include
from django.contrib.auth.views import login,logout,password_reset,password_reset_done,password_reset_confirm,password_reset_complete
#from django.urls import path
urlpatterns = [
url(r'^$',views.home),
url(r'^login/$',login,{'template_name' : 'accounts/login.html'}),
url(r'^logout/$',logout,{'template_name' : 'accounts/logout.html'}),
url(r'^register/$',views.register,name='register'),
url(r'^profile/$',views.view_profile,name='view_profile'),
url(r'^profile/edit/$',views.edit_profile,name='edit_profile'),
url(r'^change-password/$',views.change_password,name='change_password'),
url(r'^reset-password/$',password_reset,name='reset_password'),
url(r'^reset-password/done/$',password_reset_done,name='password_reset_done'),
url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
password_reset_confirm,name='password_reset_confirm' ),
url(r'^reset-password-complete/$',password_reset_complete,name='password_reset_complete'),
]
So when i enter url -" http://127.0.0.1:8000/account/profile/edit/ " its give me error
"'AnonymousUser' object has no attribute '_meta'"
What is the mistake ?what i did wrong here ? and django gives this line error
/usr/local/lib/python2.7/dist-packages/django/utils/functional.py in
inner, line 205.
what should i do to solve this error ?
You are not logged in and trying to modify profile. To prevent such kind of error, add is_authenticated validation to your view. If user is not authenticated, you can redirect him to login page with redirect shortcut function:
def edit_profile(request):
if request.user.is_authenticated:
if request.method=="POST":
form = EditProfileForm(request.POST,instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = EditProfileForm(instance=request.user)
args = {'form' : form}
return render(request,'accounts/edit_profile.html',args)
else:
return redirect('/login/')
It's better to use login_required decorator. It will check whether user logged in or not without coding it explicitly.
from django.contrib.auth.decorators import login_required
#login_required
def edit_profile(request):
if request.method=="POST":
form = EditProfileForm(request.POST,instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = EditProfileForm(instance=request.user)
args = {'form' : form}
return render(request,'accounts/edit_profile.html',args)

Django: how to send argument in HtpResponseRedirect

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'))

Categories