So I just created a form and keep getting this error, why? I correctly use the Cleaned_data after I checked if the form is valid, right?
This is my forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
username = forms.CharField(max_length=10)
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password']
This is my views.py:
class UserFormView(View):
form_class = UserForm
template_name = 'Home/index.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.Cleaned_data['username']
password = form.Cleaned_data['password']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('Home:Dashboard')
return render(request, self.template_name, {'form': form})
My urls.py:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register$', views.UserFormView.as_view(), name='register'),]
and the form location:
<form action="/register" method="post">
{% csrf_token %}
<ul class="contactList">
<li id="username1" class="contact">{{ form.username }}</li>
<li id="email1" class="contact">{{ form.email }}</li>
<li id="password1" class="contact">{{ form.password }}</li>
</ul>
<input type="submit" value="Submit">
</form>
There are other topics about this issue but I could not get any help out of them, as most people didn't include the if form.is_valid(), but in my case I do.
Use form.cleaned_data.get('username') instead of form.Cleaned_data
Edit
Use FormView
from django.views.generic.edit import FormView
class UserFormView(FormView):
form_class = UserForm
template_name = 'Home/index.html'
def form_valid(self, form):
user = form.save(commit=False)
username = form.cleaned_data.get('username')
...
get_form_class returns the class of the form i.e UserForm. You need is a object of that class. The class does not have any attribute cleaned_data.
Related
How can I show errors like email or username is already taken in this page Aaccounts/sign-up.html because when try to to put a username and this username is already taken the page only refresh without any message.
Before:
After:
Code:
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'Aaccounts/sign-up.html'
def login (request) :
if request.method=='POST':
passwordtest=request.POST ['password']
usernametest=request.POST ['username']
user=auth.authenticate(username=usernametest,password=passwordtest)
if user is not None :
auth.login(request,user)
current_user = request.user
correctUSER = get_object_or_404(CustomUser, pk=current_user.id)
need_to_cheack=correctUSER.main_affilitee
kain=False
if need_to_cheack !="":
objs=CustomUser.objects.all()
for aleratwar in objs:
if kain==False:
if aleratwar.username==need_to_cheack and aleratwar.afilliteuser==True and aleratwar.username !=correctUSER.username :
kain=True
if kain== False:
correctUSER.main_affilitee=''
correctUSER.save()
return redirect('home')
else:
return render(request,'Aaccounts/login.html',{'eroor':True})
else:
return render(request,'Aaccounts/login.html')
This is the simple example of showing the message. In your view you can In this way
from django.contrib import messages
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
return redirect('index')
else:
messages.error(request,'username or password not correct')
return redirect('login')
else:
form = AuthenticationForm()
return render(request, 'todo/login.html', {'form': form})
{{ message }}
</div>
{% endfor %}
and In your template:
{% for message in messages %}
<div class="alert alert-success">
<a class="close" href="#" data-dismiss="alert">×</a>
{{ message }}
</div>
{% endfor %}
I want to get the total number of tables own by each users on my application. using Tables.objects.all().count returns all total number of tables but I will like to get the number of tables own by each user.
models.py
class User(AbstractBaseUser, PermissionsMixin):
name = models.CharField(max_length=30, blank=True, null=True)
class Bar(models.Model):
user_id = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
class Tables(models.Model):
table_no = models.CharField(max_length=14, unique=False)
bar = models.ForeignKey(to=Bar, on_delete=models.CASCADE)
views.py
def Dashboard(request, pk):
user = User.objects.get(pk=pk)
reservations = Tables.objects.filter(bar__user_id=user)
pending = Reservation.objects.filter(status="pending")
confirmed = Reservation.objects.filter(status="confirmed")
context = {"reservations":reservations, "pending":pending, "confirmed":confirmed}
return render(request, "dashboard/super/landlord/dashboard.html", context)
class Login(View):
""" Login View."""
form_class = LoginForm
template_name = "dashboard/auth/login.html"
def get(self, request):
logout(request)
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
Email = form.cleaned_data.get('Email')
password = form.cleaned_data.get('password')
user = authenticate(username=Email, password=password)
messages.success(request, "you have logged in successfully ")
if user is not None:
if user.is_active:
login(request, user)
return redirect('/dashboard')
else:
error = "Email or password is incorrect"
return render(
request, self.template_name, {'form': form, 'error': error})
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('dashboard/<int:pk>/', Dashboard, name="dashboard"),
]
templates.html
<li {% if request.path == '/dashboard/' %} class="active" {% endif %}><i class="ion-home"></i> <span class="nav-label">Dashboard</span>
</li>
Michael Lindsay pretty much answered your question here, only query the user you need, for example if this was a view:
def all_user_tables(request, pk):
user = User.objects.get(pk=pk)
tables = Tables.objcets.filter(bar__user_id=user)
tables_count = tables.count()
return render(request, 'all_user_tables.html', {'user': user,
'tables': tables,
'tables_count': tables_count})
then in your template:
{% extends 'base.html' %}
{% block content %}
<p>Tables for user {{ user }}</p>
{% for table in tables %}
{{ table }}
{% endfor %}
<p>Total {{ table_count }} tables.</p>
{% endblock %}
Double underscores allows filter() to follow ForeignKey relations
user = User.objects.get(email="nasir#yahoo.com")
tbl_count = Tables.objects.filter(bar__user_id=user).count()
Can you please help me
Forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class Registrationform(UserCreationForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
mobile = forms.CharField(max_length=12, min_length=10)
Business_name = forms.CharField(max_length=64)
email = forms.EmailField(required=True)
password2 = None
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'mobile', 'email', 'password1', 'Business_name']
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.mobile = self.cleaned_data['mobile']
user.email = self.cleaned_data['email']
user.Business_name = self.cleaned_data['Business_name']
if commit:
user.save()
return user
views.py
#login_required
def home(request):
return render(request, 'users/home.html', {'user': request.user})
home.html
{% block content %}
<p>
{{ user.Business_name }}
{{ user.first_name}}
{{ user.last_name}}
{{ user.email }}
{{user.username}}
{{ user.mobile }}
</p>
{% end block %}
I don't understand why I am not able to fetch data even though doing the right thing.
Please help me as I am newbie in Django.
Are you trying to access the form or models? if you want to submit form, you need to change your view to
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = ContactForm()
return render(request, 'home.html', {'form': form})
and add form tag to your home.html
<form method="post" novalidate>
{% csrf_token %}
<table border="1">
{{ form }}
</table>
<button type="submit">Submit</button>
</form>
I hope this helps!!
I'm really new to Django and I want to teach myself my making a simple note. But I don't understand how django forms work. I made simple template when I can display the user's notes and now I am trying to make a view when the user can add new notes to account using a simple form.
Here is my views.py file
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from .forms import CreateUserForm, CreateNoteForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import *
# Create your views here.
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username or pasword is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for '+ user)
return redirect('home')
context = {'form': form}
return render(request, 'accounts/register.html', context)
def logoutUser(request):
logout(request)
return redirect('login')
#login_required(login_url='login')
def home(request):
if request.user.is_authenticated:
username = request.POST.get('username')
context = {'username': username}
return render(request, 'accounts/home.html', context)
def notes(request):
username = None
if request.user.is_authenticated:
username = request.user.username
user_id = request.user.pk
user_notes = Note.objects.filter(user=user_id)
context = {
'user_notes': user_notes,
'username': username,
#'user_id' : user_id,
}
return render(request, 'accounts/notes.html', context)
def createNote(request):
username = request.user.username
user_id = request.user.pk
user_notes = Note.objects.filter(user=user_id)
form = CreateNoteForm()
if request.method == 'POST':
form = CreateNoteForm(request.POST)
if form.is_valid():
form.save()
return redirect('notes')
context = {'user_notes': user_notes, 'form': form}
return render(request, 'accounts/create_note.html', context)
forms.py:
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Note
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class CreateNoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ['user', 'title', 'text']
and create_note.html:
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<br>
<br>
<div class="container">
<div class="card text-white bg-dark mb-3">
<div class="container">
<form action="{% url 'notes' %}" method="POST">
<div class="card-body">
{% csrf_token %}
{{form}}
<input type="Submit" name="Submit">
</div>
</form>
</div>
</div>
</div>
{% endblock %}
The problem is the new note isn't added when I submit the data. And also if anyone have other suggestions for structuring my views or making this app better I am happy to read them and learn new ways of improving my project. Sorry for long post. I am really noob.
When I try to login through the login page of my django project, there is the message User with this Username already exists. Here I used my own authentication view:
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is None:
return HttpResponseRedirect('/logger/bad_login/')
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/logger/bad_login/')
else:
form = LoginForm()
return render(request, 'logger/login.html', {'form': form})
Later I found django stock auth views and forms. But still want to know why my view doesnt work properly.
urls.py of my logger app, which used also for saving data of users activity
from django.conf.urls import patterns, include, url
from logger import views
urlpatterns = patterns('',
url(r'^$', views.logger_view, name='log'),
url(r'^login/$', views.login_view, name = 'login'),
url(r'^bad_login/$', views.bad_login_view, name = 'bad_login'),
)
And template
{% extends "base.html" %}
{% block title %}Login {% endblock title %}
{% block content %}
<form action="/logger/login/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock content %}
LoginForm
class LoginForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'password')
You are using a ModelForm and those will only valid if both the form and the model validation pass.
As you are using the User model, your form does not validate at the model level which is why your view fails.
If you change your login form thus, your view will work as intended:
class LoginForm(forms.Form): # A normal form, not a model form
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
You might also want to fix your view, so your form errors are displayed correctly, and you are utilizing the form correctly as well:
def login_view(request):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is None:
return HttpResponseRedirect('/logger/bad_login/')
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/logger/bad_login/')
return render(request, 'logger/login.html', {'form': form})