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)
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")
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 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'),
I have a Django Form (ModelForm) which has a number of fields. When the user presses submit these are then saved to a database. What I am struggling to work out is, how do I then output/render these results in some other HTML page.
Models.py
from django.db import models
# Create your models here.
class Contract(models.Model):
name = models.CharField(max_length=200)
doorNo = models.SlugField(max_length=200)
Address = models.TextField(blank=True)
Forms.py
from django import forms
from contracts.models import Contract
class GenerateContract(forms.ModelForm):
class Meta():
model = Contract
fields = '__all__'
Views.py
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})
At the moment, I am returning the 'Index' Home page of the app as a placeholder.
After validation, the form data is found in form.cleaned_data dictionary. So you can pass that back to the template and display it as you see fit.
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
form.save(commit=True)
return render(request,'contracts/contracts.html',{'form_data': form.cleaned_data})
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})
If you want to show the form with the saved values, you can render the template with form and fill the instance input . like this:
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
saved_instance = form.save(commit=True)
return render(request,'contracts/contracts.html',{'form':GenerateContract(instance=saved_instance)})
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})
processors.py file:
from django import forms
from django.http import HttpResponseRedirect
from mezzanine.pages.page_processors import processor_for
from .models import Author
class AuthorForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
#processor_for(Author)
def author_form(request, page):
form = AuthorForm()
if request.method == "POST":
form = AuthorForm(request.POST)
if form.is_valid():
# Form processing goes here.
redirect = request.path + "?submitted=true"
return HttpResponseRedirect(redirect)
return {"form": form}
here define urls.py file where i define processor like:
url("^xyz/$", "mezzanine.pages.views.page", {"slug": "Author"}, name="Author"),
The form still doesn't display. How do I solve this error?
Mistake: Always define processor name in " " like #processor_for("Author")
**#processor_for("Author")**
def author_form(request, page):
form = AuthorForm()
if request.method == "POST":
form = AuthorForm(request.POST)
if form.is_valid():
# Form processing goes here.
redirect = request.path + "?submitted=true"
return HttpResponseRedirect(redirect)
return {"form": form}