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}}">
Related
I have a problem with updating an existing user object in my database. When I update and change the user object it saves and everything is looking ok but when I change the user and I want to login this user does not authenticate. Here is my code:
def profile_edit(request):
user = request.user
profile = request.user.profile
context = {
'user': user
}
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
email = request.POST.get('email')
user.profile.address = request.POST.get('address')
user.profile.phone = request.POST.get('phone')
user.set_password('password')
user.username = username
user.save()
user.profile.save()
authenticate(user)
context = {
'profile': profile
}
return render(request, 'helpdesk/profile.html', context)
return render(request, 'helpdesk/profile_edit.html', context)
and login view:
def login_view(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)
profile = request.user.profile
context = {
'profile': profile
}
return render(request, 'helpdesk/user_desk.html', context)
else:
context = {
'username': username,
'error': 'user not find!'
}
else:
context = {}
return render(request, 'helpdesk/login.html', context)
When updating the password you are actually setting the string 'password' as password and not the submitted password. Change user.set_password('password') to user.set_password(password) to correct this.
<form action="" style="font-size: 2cm" method="post">
{% csrf_token %}
<div class="row" style="margin: 7px">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="username" id="first_name" class="form-control input-sm" placeholder="username:{{ request.user.username }}">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="address" id="last_name" class="form-control input-sm" placeholder="address:{{ request.user.address }}">
</div>
</div>
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-sm" placeholder="email: {{ request.user.email }}">
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-sm" placeholder="Password">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="phone" id="password_confirmation" class="form-control input-sm" placeholder="phone:{{ request.user.phone }}">
</div>
</div>
</div>
<input type="submit" value="EDIT" class="btn btn-info btn-block" style="background-color: #0d0d0d; border-color: #0d0d0d">
</form>
After POST method signup page always redirects to same page without printing any message or redirecting to homepage or login page but I am tracing it in every steps by printing something to check how it is working. But I can signup a new user using python shell.
Terminal is giving me only this:
[28/Nov/2019 15:36:26] "GET / HTTP/1.1" 200 2574
[28/Nov/2019 15:36:46] "POST / HTTP/1.1" 200 2574
def signup(request):
if request.user.is_authenticated:
return render(request,'/',{})
form = UserForm(request.POST or None)
if request.method == 'POST':
print("step 2")
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()
authenticate(username= username, password= password)
Profile.objects.create(
user= user,
full_name=form.cleaned_data['full_name'],
codeforces_id= form.cleaned_data['codeforces_id'],
Uva_Id = form.cleaned_data['Uva_Id'],
points = 0,
department= form.cleaned_data['department']
)
if user is not None:
if user.is_active:
login(request,user)
return redirect('/')
return render(request, 'signup.html',{'msg':'Invalid'})
else:
error = form.errors
print("error step")
return render(request, 'signup.html',{'msg':error})
else:
return render(request,'signup.html',{})
forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget= forms.PasswordInput)
full_name = forms.CharField(required= True)
codeforces_id = forms.CharField(required= True)
Uva_Id = forms.CharField(required= True)
department = forms.CharField(required= True)
class Meta:
model = User
fields=('username','email','password','full_name','codeforces_id','Uva_Id','department')
signup.html:
<body>
<div class="wrapper">
<div class="inner" style="width: 500px;">
{% block content %}
<form action="" method="post" style="padding-top: 40px; padding-bottom: 50px">
{% csrf_token %}
<h3 style="margin-bottom: 20px">New Account?</h3>
<div class="form-group">
<label for="username" class="control-label">Username</label>
<input type="text" class="form-control" name="username" placeholder="username">
</div>
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="text" class="form-control" name="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password" class="control-label">password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group">
<label for="full_name" class="control-label">fullname</label>
<input type="text" class="form-control" name="full_name" placeholder="Full Name">
</div>
<div class="form-group">
<label for="codeforces_id" class="control-label">codeforces_id</label>
<input type="text" class="form-control" name="codeforces_id" placeholder="codeforces_id">
</div>
<div class="form-group">
<label for="Uva_Id" class="control-label">Uva_Id</label>
<input type="text" class="form-control" name="Uva_Id" placeholder="uva_id">
</div>
<div class="form-group">
<label for="department" class="control-label">department</label>
<input type="text" class="form-control" name="department" placeholder="department">
</div>
<button type="submit" style="margin-top:20px">
<span>Register</span>
</button>
<p style="color: red">{{ msg }}</p>
<a style="float: right" href="/login">Already have an account</a>
</form>
{% endblock %}
</div>
</div>
</body>
Updated:
url.py
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^login/$',views.Login,name= 'Login'),
url(r'^signup/$',views.signup,name='signup'),
url(r'^logout/$',views.Logout,name='logout'),
You havent included the url that the form should hit on POST
[...]
<form action="{% url 'name-of-the-url-that-leads-to-your-view' %}" method="post" style
[...]
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"
I am a self learned programmer (beginner) trying to write a Signup Class Based View. Through some tutorials I have been able to write a code which as follows:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views import generic
from django.views.generic import View
from .forms import UserForm
class UserFormView (View):
form_class = UserForm
template_name = "signup.html"
#display signup blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
#process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
#cleaned (normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
# Returns User objects if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("home")
return render(request, self.template_name, {'form': form})
Here is the forms.py:
from django.contrib.auth.models import User
from django import forms
class UserForm (forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'password' ]
Now, I have a signup.html page designed using bootstrap. I am now stuck how to integrate my views to the html page. Using {{ form }} in a plane html is working bt not in bootstrap designed page. Please help
signup.html:
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3" style="margin-top: 70px">
<form role="form" method="post" action="">{% csrf_token %}
<h2>Welcome to Artivism <small>Sign up</small></h2>
<hr class="colorgraph" style="height: 7px; border-top: 0; background: grey; border-radius: 5px;">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6">
{% for field in form %}
<div class="form-group">
<input type="text" name="first_name" id="first_name" class="form-control input-lg" placeholder="First Name" tabindex="1" value="{{User.first_name}}">
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="last_name" id="last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2" value="{{User.last_name}}">
</div>
</div>
</div>
<div class="form-group">
<input type="text" name="user name" id="user_name" class="form-control input-lg" placeholder="User Name" tabindex="3" value="{{User.username}}">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4" value="{{User.email}}">
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5" value="{{User.password}}">
</div>
</div>
<span class="help-block">By clicking Sign Up, you agree to our Terms and that you have read our Data Use Policy, including our Cookie Use.</span>
<hr class="colorgraph" style="height: 7px; border-top: 0; background: grey; border-radius: 5px;"">
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3"><input type="submit" value="Sign Up" class="btn btn-primary btn-block btn-lg"></div>
</div>
</form>
</div>
Include the following form in your signup.html page and let me know if it works for you:
<form method="post" action="{% url 'signup' %}" class="form-horizontal">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label class="col-sm-2 control-label" for="id_{{ field.name }}">{{ field.label }}</label>
<div class="col-sm-10">
<input class="form-control" type="{{ field.field.widget.input_type }}"
name="{{ field.name }}"
id="id_{{ field.name }}"
value="{{ field.value }}" >
</div>
</div>
{% endfor %}
<input type="submit" value="Sign Up" class="btn btn-primary pull-right">
</form>
In your case, the simple solution would be to replace your form inputs with the following ones (this should work if your form fields are ['first_name', 'last_name', 'username', 'email', 'password']):
<input type="text" name="first_name" id="id_first_name" class="form-control input-lg" placeholder="First Name" tabindex="1">
<input type="text" name="last_name" id="id_last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2">
<input type="text" name="username" id="id_username" class="form-control input-lg" placeholder="Username" tabindex="3">
<input type="email" name="email" id="id_email" class="form-control input-lg" placeholder="Email Address" tabindex="4">
<input type="password" name="password" id="id_password" class="form-control input-lg" placeholder="Password" tabindex="5">