i wanted to check whether the name is exists in owner table or not.
this is my models.py
class owner(models.Model):
id = models.AutoField
name = models.CharField(max_length=255, blank=True, null=True)
password = models.CharField(max_length=255)
def __str__(self):
return self.name
this is my index.html
`
<form style="color:black" method="POST" action="check" class=" mt-3">
{% csrf_token %}
<div class="row mb-3">
<label for="inputText" class="col-sm-3 col-form-label">Username</label>
<div class="col-sm-8">
<input type="text" name="name" placeholder="Username" class="form-control">
</div>
</div>
<div class="row mb-3">
<label for="inputText" class="col-sm-3 col-form-label">Password</label>
<div class="col-sm-8">
<input type="text" name="password" placeholder="password" class="form-control">
</div>
</div>
<button class="btn btn-success mb-3" type="submit">Login</button>
<a class="btn btn-danger mb-3" href="index">Go Back</a>
</form>
this is my urls.py
path('index', views.index),
path('check', views.check),
this is my views.py
def check(request):
owners = owner.objects.all()
if request.method == "POST":
name = request.POST.get('name')
password = request.POST.get('password')
if owners.name == name and owners.password == password :
return render(request, "card/check.html")
it gives error on this line
if owners.name == name and owners.password == password :
`
how to check whether the name exist or not in table
owners = owner.objects.all() # This line fetches all the record in the owner table and returns queryset object
if owners.name == name and owners.password == password # The queryset can not have a name attribute. Use an instance.
Solution:
name = request.POST.get('name')
password = request.POST.get('password')
owner = Owner.objects.filter(name=name, password=password).first()
if owner:
return render(request, "card/check.html")
Related
I have a field named 'amount' of type Floatfield.
I changed it to DecimalField and ran makemigrations and migrate commands and it successfully generated 0002_alter_expense_amount.py file.
This change is reflected in the database.
But in the html form when I try to add new amount It's showing this message.
When I tried the same from the admin panel it was successful
What should I do to make the html form accept the decimal value? Is there anything I'm missing?
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
class Expense(models.Model):
amount = models.DecimalField(decimal_places=2, max_digits=10)
date = models.DateField(default=now)
description = models.TextField()
owner = models.ForeignKey(to=User, on_delete=models.CASCADE)
category = models.CharField(max_length=255)
def __str__(self):
return self.category
class Meta:
ordering = ['-date']
class Category(models.Model):
name = models.CharField(max_length=255)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
views.py
#login_required(login_url="/authentication/login")
def add_expenses(request):
categories = Category.objects.all()
context = {
'categories': categories,
'values': request.POST
}
if request.method == 'POST':
amount = request.POST['amount']
description = request.POST['description']
date = request.POST['expense_date']
category = request.POST['category']
Expense.objects.create(owner=request.user, amount=amount, date=date, category=category, description=description)
messages.success(request, 'Expense saved successfully')
return redirect('expenses')
else:
return render(request, 'expenses/add-expenses.html', context)
html form
<form action="{% url 'add-expenses' %}" method="post">
{% include 'partials/messages.html' %}
{% csrf_token %}
<div class="form-group mb-3">
<label for="">Categories</label>
<select class="form-control form-control" name="category" required>
{% for category in categories%}
<option name="category" value="{{category.name}}">
{{category.name}}
</option>
{% endfor %}
</select>
</div>
<div class="form-group mb-3">
<label for="">Amount</label>
<input type="number" class="form-control form-control-sm" name="amount" required />
</div>
<div class="form-group mb-3">
<label for="">Description</label>
<input type="text" class="form-control form-control-sm" name="description" value="{{values.description}}">
</div>
<div class="form-group mb-3">
<label for="">Date</label>
<div class="d-grid gap-2 col-3">
<input type="date" class="form-control form-control-sm" name="expense_date" required>
</div>
</div>
<div class="d-grid gap-2 col-3">
<input type="submit" value="Add" class="btn btn-outline-dark" />
</div>
</form>
I am trying to make a page in django where users can look at their profiles and edit and save the changes, but everytime i click on the save button, nothing happens and when I refresh the page, the information doesn't get updated. What am I doing wrong?
This is my models.py:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User,null= True ,on_delete= models.CASCADE)
profile_pic = models.ImageField(null = True, blank= True)
first = models.CharField(max_length=500, null=True)
last = models.CharField(max_length=500, null=True)
email = models.CharField(max_length=500, null=True)
mobile_number = models.IntegerField(null=True)
location = models.CharField(max_length= 500, null= True)
postal = models.IntegerField(null=True)
def __str__(self):
return self.first
This is my forms.py:
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = '__all__'
exclude = ['user']
widgets = {
'profile_pic': forms.FileInput()
}
This is my views.py:
#login_required(login_url='Login')
def Profile(request):
profile = request.user.profile
form = ProfileForm(instance=profile)
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILE, instance=profile)
if form.is_valid():
form.save()
return HttpResponseRedirect(reversed('Profile'))
context = {'form': form}
return render(request, 'profile.html', context)
This is my template:
<div class="col-lg middle middle-profile-con">
<div class="img-cir profile-img">
<img src="{{request.user.profile.profile_pic.url}}" alt="" width="100px" height="100px" class="pro-img">
</div>
<form method='POST' action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="">
<p class="my-name-pro">{{request.user.profile.first}}
<p>
<p class="my-email-id-pro">{{request.user.profile.email}} <br> {{form.profile_pic}}</p>
</div>
<div class="">
<div class="pro-fn-div">
<label class="pro-fn-label">First name</label>
<div class="pro-fn-input"> {{form.first}} </div>
</div>
<div class="pro-ln-div">
<label class="pro-fn-label">Last name</label>
<div class="pro-fn-input"> {{form.last}} </div>
</div>
<div class="pro-email-div">
<label class="pro-fn-label">Email ID</label>
<div class="pro-fn-input"> {{form.email}} </div>
</div>
<div class="pro-pn-div">
<label class="pro-fn-label">Phone Number</label>
<div class="pro-fn-input"> {{form.mobile_number}} </div>
</div>
<div class="pro-lo-div">
<label class="pro-fn-label">Location</label>
<div class="pro-fn-input"> {{form.location}} </div>
</div>
<div class="pro-pc-div">
<label class="pro-fn-label">Postal Code</label>
<div class="pro-fn-input"> {{form.postal}} </div>
</div>
<button type="button" name="Update Information" class="btn btn-dark btn-sm pro-btn-save">Save Changes</button>
</form>
</div>
I don't understand where I'm going wrong. Do I need to add something in the template? Maybe in the save button or something?
You forgot to register your url so for example :
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('profile/', views.profile, name="profile"),
]
In your template, edit your form
<form method='POST' action="{% url 'profile' %}" enctype="multipart/form-data">
Note that variable in Python are lowercase, following the convention is best
I have a form that returns the following fields:
fields = ['username', 'first_name', 'last_name', 'email']
So in my profile/edit view(I mean an HTML page) I have this code:
<div class="col-xl-9">
<div class="widget has-shadow" style="height:100%">
<div class="widget-header bordered no-actions d-flex align-items-center">
<h4>edit profile</h4>
</div>
<div class="widget-body">
<form method="POST">
{% csrf_token %}
<div class="form-group row d-flex align-items-center mb-5">
<label class="col-lg-2 form-control-label d-flex justify-content-lg-end">username</label>
<div class="col-lg-6">
<input type="text" name="username" class="form-control" placeholder="{{update_profile_form.username}}">
</div>
</div>
<div class="em-separator separator-dashed"></div>
<div class="text-right">
<button class="btn btn-gradient-01" type="submit">Save</button>
<button class="btn btn-shadow" type="reset">Cancel</button>
</div>
</form>
</div>
</div>
</div>
And you see I want to show username field from update_profile_form form. But when I reload the page I have an extra "> below of my username field.
I don't know how to get rid of these characters in my page.
Update
my forms.py looks like:
class AccountUpdateForm(forms.ModelForm):
class Meta:
model = Account
fields = ['username', 'first_name', 'last_name', 'email']
def clean_username(self):
if self.is_valid():
username = self.cleaned_data['username']
try:
account = Account.objects.exclude(pk=self.instance.pk).get(username=username)
except Account.DoesNotExist:
return username
raise forms.ValidationError('The username "%s" is now allowed to be used!', username)
and my views.py is:
def edit_profile_view(request):
context = {}
if not request.user.is_authenticated:
return redirect('login')
if request.POST:
upd_form = AccountUpdateForm(request.POST, instance=request.user)
if upd_form.is_valid():
upd_form.save()
else: # Get request
upd_form = AccountUpdateForm(
initial = {
"username": request.user.username,
}
)
context = {'update_profile_form': upd_form}
return render(request, 'account/user/edit-profile.html', context)
you have to replace this line
<input type="text" name="username" class="form-control" placeholder="{{update_profile_form.username}}">
with
<input type="text" name="username" class="form-control" placeholder="{{request.user.username}}">
you do not have to provide initial values to your form in your views.
Because of initials I need to do:
<input type="text" name="username" class="form-control" value="{{update_profile_form.initial.username}}">
I am trying to save students from addstudent form but it is not saving students and it is displaying error message 'error in form'.Is there any solutions for this code.I think the error is in html template.
Error is like this:
AttributeError at /students/add/student/
'ErrorDict' object has no attribute 'status_code'
Request Method: POST
Request URL: http://127.0.0.1:8000/students/add/student/
Django Version: 2.1.5
Exception Type: AttributeError
Exception Value:
'ErrorDict' object has no attribute 'status_code'
models.py
class Course(models.Model):
title = models.CharField(max_length=250)
basic_price = models.CharField(max_length=100)
advanced_price = models.CharField(max_length=100)
basic_duration = models.CharField(max_length=50)
advanced_duration = models.CharField(max_length=50)
class Student(models.Model):
name = models.CharField(max_length=100)
course = models.ManyToManyField(Course)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateField()
forms.py
class AddStudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
views.py
def addstudent(request):
courses = Course.objects.all()
if request.method == 'POST':
form = AddStudentForm(request.POST,request.FILES)
if form.is_valid():
student = form.save()
student.save()
messages.success(request,'student saved.')
return redirect('students:add_student')
# else:
# return HttpResponse(form.errors) --> it returns course
else:
form = AddStudentForm()
return render(request,'students/add_student.html',{'form':form,'courses':courses})
add_student.html
<form action="{% url 'students:add_student' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Course <span class="text-danger">*</span></h5>
<div class="controls">
<select name="course" id="select" required class="form-control">
<option value="">Select Your Course</option>
{% for course in courses %}
<option value="{{course.title}}">{{course.title}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<h5>Address<span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="address" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Phone Number <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="phone" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Email <span class="text-danger">*</span></h5>
<div class="controls">
<input type="email" name="email" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Date <span class="text-danger">*</span></h5>
<div class="controls">
<input type="date" name="joined_date" data-validation-match-match="password" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Image <span class="text-danger">*</span></h5>
<div class="controls">
<input type="file" name="image" class="form-control" > </div>
</div>
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
You should output the value of form.errors as suggested in the comments to discover the exact error. However, I can see two immediate issues that are likely causing form validation to fail.
Firstly, because your form contains an image upload you must set the enctype to multipart/form-data in the template:
<form action="{% url 'students:add_student' %}" method="post" enctype="multipart/form-data">
Second, the uploaded image exists in request.FILES so you need to pass that to the form:
form = AddStudentForm(request.POST, request.FILES)
You have to save many to many field after save method.
if form.is_valid():
student = form.save(commit=False)
student.save()
form.save_m2m()
With this code i want to store multiple courses to the student table.But this code is not working.Neither it throws any error neither saves any data.The main problem is while clicking submit button the submit button does not perform any action at all.It does not load the submit button.How can i solve this??
I think the problem is in add_student.html template.When i return form.error it throws course.Is there anything i have to change??but i want to keep my design like this
models.py
class Course(models.Model):
title = models.CharField(max_length=250)
basic_price = models.CharField(max_length=100)
advanced_price = models.CharField(max_length=100)
basic_duration = models.CharField(max_length=50)
advanced_duration = models.CharField(max_length=50)
def __str__(self):
return self.title
class Student(models.Model):
name = models.CharField(max_length=100)
course = models.ManyToManyField(Course)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateField()
def __str__(self):
return self.name
views.py
def addstudent(request):
courses = Course.objects.all()
if request.method == 'POST':
form = AddStudentForm(request.POST,request.FILES)
if form.is_valid():
student = form.save()
student.save()
# student.course.set(courses)
messages.success(request, 'student saved.')
return redirect('students:add_student')
else:
return HttpResponse(form.errors) # it returns course.i think the problem is while saving the course
else:
form = AddStudentForm()
return render(request,'students/add_student.html',{'form':form,'courses':courses})
forms.py
class AddStudentForm(forms.ModelForm):
course = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple)
class Meta:
model = Student
fields = ['name','course','email','address','phone','image','joined_date']
add_student.html
<form action="{% url 'students:add_student' %}"
method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Courses <span class="text-danger">*</span></h5>
<div class="controls">
{% for course in courses %}
<input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.id}}">
<label for="{{course.title}}">{{course.title}}</label>
{% endfor %}
</div>
</div>
<div class="form-group">
<h5>Address<span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="address" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Phone Number <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="phone" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Email <span class="text-danger">*</span></h5>
<div class="controls">
<input type="email" name="email" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Joined Date <span class="text-danger">*</span></h5>
<div class="controls">
<input type="date" name="joined_date" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Image <span class="text-danger">*</span></h5>
<div class="controls">
<input type="file" name="image" class="form-control" > </div>
</div>
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
I'd recommend this solution:
courses = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset= Course.objects.all())
in views.py
if form.is_valid():
student = form.save(commit=False)
courses = form.cleaned_data['courses']
student.course = courses
student.save()
ps. it's a good practice to name m2m fields in plural:
courses = models.ManyToManyField(Course)
here's what I meant with templates:
in add_student.html
Comment out whole <form> block and replace it with Django's {{ form }} and see how it'd render
You have a queryset of courses passed in context to template. Try to change it from:
{% for course in courses %}
<input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.title}}">
<label for="{{course.title}}">{{course.title}}</label>
{% endfor %}
to just:
{{ form.cource }}
Try a Class Based View
class CreateStudent(CreateView):
model = Student
form_class = AddStudentForm
template_name = "add_student.html"