I am new to Django. I am just learning to use forms and modelforms. Here I used modelforms to get two charfields(username and password) and saving it. What I wanted to do is to get the model id of that username. Below is the code. But I can't get the id.
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from reg.models import registration, registrationform
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
p = registration.objects.all()
for loop in p:
if loop.username == username:
id = loop.id
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id)))
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
def thanks(request, id):
p = get_object_or_404(registration, pk=id)
return render_to_response('thanks.html', {'reg': p)
One more question. What is the model field for password?
Thanks.
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data =form.save()
#...
id = data.id
#...
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id)))
user = form.save(commit=False)
user.first_name = u'First name'
user.last_name = u'Last name'
user.save()
For password use password1 field
Please could you paste your urls.py?
I recently had a problem almost exactly the same as this - it was just a typo there, I had the wrong value in in second field of the url function:
url(r'^people/thanks/(?P<person_id>\d+)$', 'people.views.thanks'),
Should have been:
url(r'^people/thanks/(?P<person_id>\d+)$', 'people.views.new'),
How about changing your registration function to this:
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
userdetails = form.save()
user = userdetails.username
val = registration.objects.get(username = user)
return HttpResponseRedirect(reverse('reg.views.thanks', args=(val.id)))
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
I suggest you read this: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
Related
I tryed to add validation to ContactModel, by doing Forms.py but I went too far away with it and now dont know to fix it. Can someone help ?
def addContact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# form = Contact(
# full_name = request.POST ('fullname'),
# relationship = request.POST ('relationship'),
# email = request.POST ('email'),
# phone_number = request.POST ('phone-number'),
# address = request.POST ('address'),
# )
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
def contactProfile(request,pk):
contact = Contact.objects.get(id=pk)
return render(request, 'contact/contact-profile.html', {'contact': contact})
In my opinion in Views I have big mess.. When I fill up all fields data isn't sending to database.
forms.py:
from django.forms import ModelForm
from .models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
models.py:
from django.db import models
# Create your models here.
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number =models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
It seems that your form is not valid and it redirects always to contact.
You should to use redirect only if the form is valid. Otherwise you will never see which errors your form contains.
Try the following code:
def addContact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
else:
form = ContactForm()
context = {'form': form}
return render(request, 'contact/new.html', context)
im using a non-model based form django.
once i get the data,i create a model object.
but when im trying to edit my post(a blog/quote based app),im not able to create a form object using the model object for a specific post.
these are my codes:
views.py:
def quote_form(request):
if request.method=='POST':
form=Quote(request.POST)
if form.is_valid():
quote=form.cleaned_data['quote']
author=form.cleaned_data['author']
popularity=form.cleaned_data['popularity']
category=form.cleaned_data['category']
p=Quote1(quote=quote, author=author, popularity=popularity, category=category)
p.save()
return redirect("quote_list")
else:
form=Quote()
return render(request,'quote/form.html',{'form':form})
def quote_edit(request, pk):
q = get_object_or_404(Quote1, pk=pk)
if request.method == "POST":
form = Quote(request.POST,instance=q)
if form.is_valid():
q = form.save(commit=False)
q.author = request.user
q.save()
return redirect('quote_detail', pk=q.pk)
#return render(request,"blog/post_detail.html",{'post':post})
else:
form = Quote(instance=q)
return render(request, 'quote/quote_edit.html', {'form': form})
models.py:
class Quote1(models.Model):
quote=models.CharField(max_length=200)
author=models.CharField(max_length=200)
popularity=models.IntegerField()
category=models.CharField(max_length=40)
forms.py:
class Quote(forms.Form):
quote=forms.CharField()
author=forms.CharField()
popularity=forms.IntegerField()
category=forms.ChoiceField(choices=[('life','life'),('happiness','happiness'),('love','love'),('truth','truth'),
('inspiration','inspiration'),('humor','humor'),('philosophy','philosophy'),('science','science')])
Try this:
def quote_edit(request, pk):
q = get_object_or_404(Quote1, pk=pk)
if request.method == "POST":
form = Quote(request.POST)
if form.is_valid():
quote=form.cleaned_data['quote']
author=form.cleaned_data['author']
popularity=form.cleaned_data['popularity']
category=form.cleaned_data['category']
q.quote=quote
q.author=author
q.popularity=popularity
q.category=category
q.save()
else:
form = Quote(initial=reauest.POST.copy())
return render(request, 'quote/quote_edit.html', {'form': form})
P.S:
Using ModelForm would have been better approach. If you can switch to ModelForm i can help there as well.
I'm reading the documentation on how to display a message to the user with Django messages. It says that in order to add a message in your views to call:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
I'm not sure where to put the second the second line, this is my view:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
return HttpResponse('Thank you')
else:
return HttpResponse('That text is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
I want the message to appear and thank the user for signing up and display their input as well.
Bearing, in mind that it's customary to redirect to a success url on valid form submission, your code ought to look like this:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
messages.add_message(request, messages.INFO, 'Hello world.')
return HttpResponseRedirect('/thank-you-page/')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
note that this also results in the user being told why exactly his form is invalid (assuming that you have set up the template propertly). It's always good to say what the problem is rather than to say there is a problem.
You can put the second line in view with example:
def contact(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
textarea = request.POST.get('textarea')
contact = Contact(name = name,email = email,password = password,textarea = textarea,date=datetime.today())
contact.save()
messages.success(request, 'Form has submitted')
return render(request,"contact.html")
In my Django app I create a User from django.contrib.auth.models, and I am using request.user in multiple view functions without a problem. In one of my view functions I change the user password, save the user, and redirect the client to another view function. Once I try to get the user from the request in that function, the user is Anonymous. After using User.set_password() or redirecting, does it take the user out of the session ?
views.py
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from .models import Profile
from .forms import ProfileForm, PasswordForm
def sign_in(request):
form = AuthenticationForm()
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
if form.user_cache is not None:
user = form.user_cache
if user.is_active:
login(request, user)
return HttpResponseRedirect(
reverse('home') # TODO: go to profile
)
else:
messages.error(
request,
"That user account has been disabled."
)
else:
messages.error(
request,
"Username or password is incorrect."
)
return render(request, 'accounts/sign_in.html', {'form': form})
def sign_up(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(data=request.POST)
if form.is_valid():
form.save()
user = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1']
)
new_profile = Profile.objects.create(user=user)
login(request, user)
messages.success(
request,
"You're now a user! You've been signed in, too."
)
return HttpResponseRedirect(reverse('home')) # TODO: go to profile
return render(request, 'accounts/sign_up.html', {'form': form})
def sign_out(request):
logout(request)
messages.success(request, "You've been signed out. Come back soon!")
return HttpResponseRedirect(reverse('home'))
def profile(request):
user = request.user
try:
account = Profile.objects.get(user=user)
except Profile.DoesNotExist:
account = None
print(account.first_name)
context = {'account': account}
return render(request, 'accounts/profile.html', context)
def edit(request):
account = Profile.objects.get(user=request.user)
form = ProfileForm(instance=account)
if request.method == 'POST':
account = Profile.objects.get(user=request.user)
form = ProfileForm(request.POST, request.FILES)
if form.is_valid():
account.first_name = form.cleaned_data['first_name']
account.last_name = form.cleaned_data['last_name']
account.email = form.cleaned_data['email']
account.bio = form.cleaned_data['bio']
account.avatar = form.cleaned_data['avatar']
account.year_of_birth = form.cleaned_data['year_of_birth']
account.save()
context = {'account': account}
return HttpResponseRedirect('/accounts/profile')
else:
x =form.errors
context = {'form': form, 'errors': form.errors}
return render(request, 'accounts/edit.html', context)
else:
context = {'form': form}
return render(request, 'accounts/edit.html', context)
def change_password(request):
user = request.user
if request.method == 'POST':
form = PasswordForm(request.POST)
if form.is_valid():
cleaned_data = form.cleaned_data
if not user.check_password(cleaned_data['old_password']):
form.add_error('old_password', 'Old password is incorrect')
context = {'form': form}
return render(request, 'accounts/password.html', context)
try:
user.set_password(cleaned_data['new_password'])
user.save()
return HttpResponseRedirect('/accounts/profile')
except Exception as e:
form = PasswordForm()
context = {'form': form}
return render(request, 'accounts/password.html', context)
else:
form = PasswordForm()
context = {'form': form}
return render(request, 'accounts/password.html', context)
forms.py
class PasswordForm(forms.Form):
old_password = forms.CharField(max_length=200)
new_password = forms.CharField(max_length=200)
confirm_password = forms.CharField(max_length=200)
def clean(self, *args, **kwargs):
cleaned_data = super(PasswordForm, self).clean()
if 'new_password' in cleaned_data:
new_password = cleaned_data['new_password']
else:
new_password = None
if 'confirm_password' in cleaned_data:
confirm_password = cleaned_data['confirm_password']
else:
confirm_password = None
if confirm_password and new_password:
if new_password != confirm_password:
self.add_error('confirm_password', 'Passwords do not match')
Yes. See the documentation about session invalidation on password change. To fix it, see this bit in particular:
The default password change views included with Django, PasswordChangeView and the user_change_password view in the django.contrib.auth admin, update the session with the new password hash so that a user changing their own password won't log themselves out. If you have a custom password change view and wish to have similar behavior, use the update_session_auth_hash() function.
I am trying to make a search form for one of my classes. The model of the form is:
from django import forms
from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField
from books.models import Book, Author, Category
class SearchForm(forms.ModelForm):
authors = ModelMultipleChoiceField(queryset=Author.objects.all(),required=False)
category = ModelChoiceField (queryset=Category.objects.all(),required=False)
class Meta:
model = Book
fields = ["title"]
And the view I'm using is:
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from books.models import Book,Author
from books.forms import BookForm, SearchForm
from users.models import User
def search_book(request):
if request.method == "POST":
form = SearchForm(request.POST)
if form.is_valid():
form = SearchForm(request.POST)
stitle = form.cleaned_data['title']
sauthor = form.cleaned_data['author']
scategory = form.cleaned_data['category']
else:
form = SearchForm()
return render_to_response("books/create.html", {
"form": form,
}, context_instance=RequestContext(request))
The form shows up fine, but when I submit it I get an error: 'SearchForm' object has no attribute 'cleaned_data'
I'm not sure what's going on, can someone help me out? Thanks!
For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.
Just get rid of the second form = SearchForm(request.POST) and all should be well.
I would write the code like this:
def search_book(request):
form = SearchForm(request.POST or None)
if request.method == "POST" and form.is_valid():
stitle = form.cleaned_data['title']
sauthor = form.cleaned_data['author']
scategory = form.cleaned_data['category']
return HttpResponseRedirect('/thanks/')
return render_to_response("books/create.html", {
"form": form,
}, context_instance=RequestContext(request))
Pretty much like the documentation.
I was facing the same problem,
I changed the code like this
if request.method == "POST":
form = forms.RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
fname = form.cleaned_data.get('fname')
lname = form.cleaned_data.get('lname')
email = form.cleaned_data.get('email')
pass1 = form.cleaned_data.get('pass1')
pass2 = form.cleaned_data.get('pass2')
At times, if we forget the
return self.cleaned_data
in the clean function of django forms, we will not have any data though the form.is_valid() will return True.