my model is not showing up in admin model data is getting visble in link bar in csrf middle ware token - django

{% block body %}
{% load static %}
<div class="container my-3">
<h3>Contact Us</h3>
<form action="/contact" method="post"> {% csrf_token %}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name='name' placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="email" class="form-control" id="email" name='email' placeholder="Enter Your Email">
</div>
<div class="form-group">
<label for="name">Phone</label>
<input type="tel" class="form-control" id="phone" name='phone' placeholder="Enter Your Phone Number">
</div>
<div class="form-group">
<label for="desc">Your requirements:-</label>
<textarea class="form-control" id="desc" name='desc' rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success">Contact</button>
</form>
</div>
def index(request):
return render(request, 'prop/home.html')
def contact(request):
if request.method=='POST':
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
desc = request.POST['desc']
contact=Contact(name=name,email=email,phone=phone,desc=desc)
contact.save()
return render(request, 'prop/contact.html')
result
"GET /prop/contact/?csrfmiddlewaretoken=npxCzACid026bcA0bYugZdAL1K2Ondqu2EtpzTuoDbnYivut9tsHJnh5Tq7NWOdU&name=yashi&email=hyashkzo%40gmail.com&phone=55645blbb&desc= HTTP/1.1" 200 8758

make following changes and try
<form action="{% url 'contact' %}" method="POST"> {% csrf_token %}
instead of button
<input type="submit" value="Contact" class="btn btn-success">
Provided you have a url with name contact

Related

display multiple django messages in one page?

I have a template in which user can change his details like name, email and password. I am getting wrong messages after updating info ( if I change the password then I got message "Invalid" that is part of edit_profile) though I used extra_tags for message to identify two different messages,
But still having issue. I tried searching a lot, and found some relevant questions but was not helpful.
views.py
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()
messages.success(request, "Update successful!", extra_tags='edit_profile')
return redirect("accounts:edit_profile")
else:
messages.error(request, "Invalid", extra_tags='edit_profile')
return redirect("accounts:edit_profile")
else:
form = EditProfileForm(instance=request.user)
return render(request, "accounts/edit_profile.html", {'form': form})
else:
redirect('accounts:signin')
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
messages.success(request, "Update successful!", extra_tags='change_password')
update_session_auth_hash(request, form.user)
return redirect("accounts:change_password")
else:
messages.error(request, "Password Error", extra_tags='change_password')
return redirect("accounts:change_password")
else:
form = PasswordChangeForm(user=request.user)
return render(request, "accounts/edit_profile.html", {'form': form})
template
<h2 class="font-weight-bolder">Account Details</h2>
<!-- edit_profile form -->
<form action="{% url 'accounts:edit_profile' %}" method="post" class="row g-3 needs-validation"
novalidate>
{% csrf_token %}
<!-- 1 Username -->
<div class="offset-md-2 col-md-4 ">
<label for="username" class="form-label">Username</label><br>
<input type="text" name="username" class="form-control" id="username"
value="{{ form.username.value }}" required>
<div class="invalid-feedback">
Please provide name.
</div>
</div>
<!-- 2 Email -->
<div class="offset-md-1 col-md-4">
<label for="email" class="form-label">Email</label>
<input type="email" name="email" class="form-control" id="email"
value="{{ form.email.value }}" required>
<div class="invalid-feedback">
Please provide a valid email.
</div>
</div>
{% for message in messages %}
{% if 'edit_profile' in message.tags %}
<div class="offset-md-2 col-md-6 pt-2">
<h4 class="text-success font-weight-bolder">{{ message }}</h4>
</div>
{% endif %}
{% endfor %}
<div class="offset-md-2 col-md-4 pt-2 pb-2">
<input type="submit" value="Save" class="btn btn-outline-primary btn-lg">
</div>
</form>
<!-- Password section -->
<div class="offset-md-2 pt-3 pb-2">
<h4 class="font-weight-bold">Password</h4>
</div>
<form action="{% url 'accounts:change_password' %}" method="post" class="row g-3 needs-validation"
novalidate>
{% csrf_token %}
<div class="offset-md-2 col-md-3">
<label for="old_password" class="form-label">Current password</label>
<input type="password" name="old_password" value="" class="form-control" id="old_password" required>
<div class="invalid-feedback">
Please provide a valid password.
</div>
</div>
<div class="col-md-3">
<label for="new_password1" class="form-label">New password</label>
<input type="password" name="new_password1" value="" class="form-control" id="new_password1"
required>
<div class="invalid-feedback">
Please provide a valid password.
</div>
</div>
<div class="col-md-3">
<label for="new_password2" class="form-label">Confirm password</label>
<input type="password" name="new_password2" value="" class="form-control" id="new_password2"
required>
<div class="invalid-feedback">
Please provide a valid password.
</div>
</div>
{% for message in messages %}
{% if "change_password" in message %}
<div class="offset-md-2 col-md-6 pt-2">
<h4 class="text-success font-weight-bolder">{{ message }}</h4>
</div>
{% endif %}
{% endfor %}
<div class="offset-md-2 col-md-4 pt-2">
<input type="submit" value="Change Password" class="btn btn-outline-primary btn-lg">
</div>
</form>

how to creater a signup register form with my own reqired field form in django?

Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
here is my example how my form feild look like
[enter link description here][1]
<form id="contact-form" method="post" action="/addyourschool/" role="form">
<input type="hidden" name="csrfmiddlewaretoken" value="vhcAZ5w1HpK2mUXMhdqHR1to9Yv2LeOB85E2kR7Z1ZsPo5fjtWZ5P7o23kj8lDsk">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">School Name</label>
<input type="text" name="schoolname" id="product" class="form-control ui-autocomplete-input" placeholder="Type few letter & select from down *" required="required" data-error="Lastname is required." autocomplete="off">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_cfschp">Can't find your School *</label>
<input id="form_cfschp" type="text" name="form_cfschpool" class="form-control" placeholder="Can't find your School *" required="required" data-error="Can't find your School">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Pessonname">Contact person Name *</label>
<input id="Pessonname" type="text" name="Pessonname" class="form-control" placeholder="Contact person Name *" required="required" data-error="Contact person Name ">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="DesignationatSchool">Designation at School(job title at this section) *</label>
<select id="DesignationatSchool" name="DesignationatSchool" class="form-control" required="required" data-error="Designation at School">
<option value=""></option>
<option value="Request principal">Principal</option>
<option value="Request quotation">Founder</option>
<option value="Request order status">Management</option>
<option value="Request copy of an invoice">Teachers</option>
<option value="Other">Others</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Enter your Password *" required="required" data-error="password">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Confirm Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Confirm Password *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email">Email *</label>
<input id="email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tel">Mobile No. *</label>
<input id="tel" type="tel" name="phone" class="form-control" placeholder="Please enter your Mobile No *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="text-center"> <input type="submit" class="btn btn-success btn-send" value="Register"></div>
<div class="text-center">Aready Register / have an account ? Login here</div>
</div>
</div>
</form>
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(max_length=50)
email = forms.EmailField(max_length=50)
subject = forms.CharField(max_length=50)
message = forms.CharField(widget=forms.Textarea)
You have to first create the forms.py file in your app as e.g(contact_us)
from django.shortcuts import render
from django.core.mail import send_mail
from .forms import RegisterForm
from django.http import HttpResponse
Create your views here.
def contact_us(request):
#request for POST
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
sender_name = form.cleaned_data['username']
sender_email = form.cleaned_data['email']
message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('New Enquiry', message, sender_email, ['example#gmail.com'])
return HttpResponse('Thanks for Contacting US')
else:
form = RegisterForm()
return render(request, 'Contactus/contact.html', {'form': form})
After created the forms you have to insert the forms class name in views.py to display the custom form on browser.
#Create Your Template
<form id="contactform" method="POST">
{% csrf_token %}
<div class="column one-second">
{{ form.username }}
</div>
<div class="column one-second">
{{form.email }}
</div>
<div class="column one">
{{ form.subject }}
</div>
<div class="column one">
{{ form.message }}
</div>
<div class="column one">
<input type="submit" value="submit">
</div>
</form>
After this you have to call the form in template. To display your own custom form.
As i did above.

How to provide validation for the users model in views itself in django(not the custom user model)?

I am having user model in the models.py and the every user even the repeated user emails and usernames are being stored in the database but I need the validation of email and password upto 8 characters in the views.py
My models.py is
class users(models.Model):
email=models.CharField(max_length=50,default='0000000')
password=models.CharField(max_length=50,default='0000000')
room = models.ForeignKey(rooms,on_delete=models.CASCADE)
goal = models.ManyToManyField(goals)
style = models.ManyToManyField(designs)
My views.py
def user_register(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
room = request.POST['room']
g=goal=request.POST['goal']
g = g.split(',')
s=style=request.POST['style']
s=s.split(',')
user = users(password=password,email=email)
user.room=rooms.objects.get(pk=room)
goal = goals.objects.filter(pk__in=g)
style = designs.objects.filter(pk__in=s)
user.save()
user.goal.add(*goal)
user.style.add(*style)
return render(request,'home.html')
My template is:
<div class="card-body">
<form action="{% url 'car:user_register' %}" method="POST" >
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" required>
</div>
<div class="form-group">
<input type="hidden" name="room" id="name" value=" ">
</div>
<div class="form-group" >
<input type="hidden" name="goal" id="goal" value=" ">
</div>
<div class="form-group" >
<input type="hidden" name="style" id="style" value=" ">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<input type="submit" value="Register" class="btn btn-secondary btn-block">
</form>
</div>
</div>
</div>

Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['employees\\/edit\\/(?P<pk>[0-9]+)\\/$']

Building an Employee application, After updating an Employee using a form, it just shows this error and the Url seems correct so I can really say where the error is coming from
I've crosschecked all my url patterns my views and my url in the form and also tried using the solution in this question, this gives me a bigger error
urls.py
urlpatterns = [
path('edit/<int:pk>/', views.edit, name = 'edit'),
]
views.py
#login_required(login_url='/accounts/login')
def edit(request, pk):
employ = get_object_or_404(Employee, id=pk)
logging.info(type(employ))
departments = Department.objects.all()
context = {
'employ': employ,
'departments':departments
}
if request.method == "POST":
first_name = request.POST['first_name']
last_name = request.POST['last_name']
name = last_name +' '+first_name
employee_id = request.POST['employee_id']
email = request.POST['email']
department = Department.objects.get(dept_name = request.POST['department'])
address = request.POST['address']
employment_type = request.POST['employment_type']
employment_status = request.POST['employment_status']
role = request.POST['role']
marital_status = request.POST['marital_status']
gender = request.POST['gender']
join_date = request.POST['join_date']
end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date']
location = request.POST['location']
credentials = request.POST['credentials']
passport = request.POST['passport']
hod = request.POST['hod']
phone_number = request.POST['phone_number']
date_of_birth = request.POST['date_of_birth']
date_added = datetime.now()
if Employee.objects.filter(employee_id = employee_id).exists() or Employee.objects.filter(email = email).exists():
messages.error(request, 'That ID/Email is Taken')
return redirect('edit')
else:
employee = Employee(first_name='first_name',last_name='last_name',email='email',
employee_id='employee_id',department='department',address='address',employment_type='employment_type',
employment_status='employment_status',role='role',marital_status='marital_status',gender='gender',join_date='join_date',
end_date='end_date',location='location',credentials='credentials',passport='passport',hod='hod',
phone_number='phone_number',date_added='date_added',date_of_birth='date_of_birth')
employee.save()
messages.success(request, 'Employee Created')
return redirect('all')
return render(request, 'employees/edit.html', context, employ)
edit.html
<form method = 'POST' action="{% url 'edit' pk=employ.pk %}" class="m-b-30" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for='first_name' class="control-label">First Name <span class="text-danger">*</span></label>
<input name='first_name' class="form-control" type="text" required value="{{employ.first_name}}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='last_name' class="control-label">Last Name</label>
<input name='last_name' class="form-control" type="text" required value="{{employ.last_name }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employee_id' class="control-label">Employee ID <span class="text-danger">*</span></label>
<input name='employee_id' class="form-control" type="number" required value="{{employ.employee_id }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='email' class="control-label">Email <span class="text-danger">*</span></label>
<input name='email' class="form-control" type="email" required value="{{employ.email }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='phone_number' class="control-label">Phone Number</label>
<input name='phone_number' class="form-control" type="text" required value="{{employ.phone_number }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='gender' class="control-label">Gender</label>
<select name = 'gender' class="form-control" value = "{{employ.gender}} " type="text" >
<option>select gender</option>
{% if employ.gender == 'Male' %}
<option selected ='selected'>Male</option>
{% else %}
<option selected ='selected'>Female</option>
{% endif %}
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='marital_status' class="control-label">Marital Status</label>
<select name='marital_status' class="form-control" value = "{{employ.marital_status}} " type="text" >
{% if employ.marital_status == 'Married' %}
<option selected ='selected'>Married</option>
{% else %}
<option selected ='selected'>Single</option>
{% endif %}
<option>select martial status</option>
<option>Married</option>
<option>Single</option>
<option>Single</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='date_of_birth' class="control-label">Date of Birth <span class="text-danger">*</span></label>
<input name='date_of_birth' class="form-control" type="date" required value="{{employ.date_of_birth|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='address' class="control-label">Address </label>
<input name='address' class="form-control" type="text" required value="{{employ.address }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='department' class="control-label">Department <span class="text-danger">*</span></label>
<select name = 'department' type="text" class="form-control" value = "{{employ.department}} " >
<option>select department</option>
{% for department in departments %}
{% if employ.department == department %}
<option selected ='selected'>{{employ.department}}</option>
{% endif %}
<option>{{department.dept_name}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employment_type' class="control-label">Employment Type </label>
<select id= "employment_type" name='employment_type' type="text" class="form-control" value = "{{employ.employment_type}} " >
{% if employ.employment_type == 'Contract' %}
<option selected ='selected'>Contract</option>
{% elif employ.employment_type == 'Fulltime' %}
<option selected ='selected'>Fulltime</option>
{% else %}
<option selected ='selected'>Intern</option>
{% endif %}
<option>select employment type</option>
<option>Contract</option>
<option>Fulltime</option>
<option>Intern</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='join_date' class="control-label">Join Date <span class="text-danger">*</span></label>
<input name='join_date' class="form-control " type="date" required value="{{employ.join_date|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6" id="end_date">
<div class="form-group">
<label for='end_date' class="control-label">End Date <span class="text-danger">*</span></label>
<input name='end_date' class="form-control " type="date" value="{{employ.end_date|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employment_status' class="control-label">Employment Status </label>
<select name='employment_status' type="text" class="form-control" value="{{employ.employment_status}}" >
{% if employ.employment_status == 'Active' %}
<option selected ='selected'>Active</option>
{% else %}
<option selected ='selected'>Inactive</option>
{% endif %}
<option>select employment status</option>
<option>Active</option>
<option>Inactive</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='role' class="control-label">Role </label>
<input name='role' class="form-control" type="text" required value="{{employ.role }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='location' class="control-label">Work Location </label>
<input name='location' class="form-control" type="text" required value="{{employ.location }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='hod' class="control-label">HOD </label>
<select name='hod' class="form-control" type="text" >
<option>Select HOD</option>
{% for department in departments %}
{% if employ.department.lead == department.lead %}
<option selected ='selected'>{{employ.department.lead}}</option>
{% endif %}
<option>{{department.lead}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='passport' class="control-label">Upload passport </label>
<input name='passport' type="file" accept="image/*" value="{{employ.passport }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='credentials' class="control-label">Add Credentials </label>
<input name='credentials' type="file" accept="image/*" value="{{employ.credentials }}">
</div>
</div>
</div>
<div class="m-t-20 text-center">
<button class="btn btn-primary">Update Employee</button>
</div>
</form>
it's meant to be submitted and routed to edit.hmtl in case there's any error while submitting
When you redirect to the edit view, you need to pass the primary key.
return redirect('edit', pk=employ.pk)
As an aside, it's not recommended to access values from request.POST directly. Have a look at Django forms.

How to show error messages in a custom signup template in Django

I'm trying to show error message in my custom signup template. Just to verify my below codes work, I used the {{ form.as_table }} and it shows error message properly. However, when I use my custom signup template, it doesn't show any error message when I cause an error on purpose on the signup form.
HTML
<form class="form-signin" method="POST">
{% csrf_token %}
<div class="container">
<div class="jumbotron">
<a class="navbar-brand js-scroll-trigger" href="{% url 'boutique:index' %}"><img width="165" height="30" src="{% static 'boutique/img/modvisor_logo_black.png' %}"></a>
<br><br>
<div class="text-center mb-4">
<h1 class="h3 mb-3 font-weight-normal">Join Modvisor</h1>
<p class="error-message">
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
{% endif %}
</p>
</div>
<div class="form-label-group">
<input type="text" id="inputEmail" class="form-control" name="username" placeholder="Email address" required autofocus>
<label for="inputEmail">Email</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword1" class="form-control" name="password1" placeholder="Password" required>
<label for="inputPassword">Password</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword2" class="form-control" name="password2" placeholder="Password" required>
<label for="inputPassword">Confirm Password</label>
</div>
<!--
<div class="form-label-group">
<input type="password" id="inputPassword" class="form-control" name="password2" placeholder="Password" required>
<label for="inputPassword">Confirm Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
-->
<button class="btn btn-success btn-block" type="submit">Sign Up</button>
<br>
<button class="btn btn-secondary btn-block" type="button">Back</button>
<p class="mt-5 mb-3 text-muted text-center">© 2018 Modvisor All Rights Reserved.</p></p>
</div>
</div>
</form>
forms.py
class SignupForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
fields = UserCreationForm.Meta.fields
views.py
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.save()
return redirect(settings.LOGIN_URL)
else:
form = SignupForm()
return render(request, 'accounts/register.html', {'form': form})
You should use form.errors.field_name for errors related to specific field. Like for error on username field, it will be form.errors.username
You HTML will look like
<div class='error'>{{form.errors.username}}</div>
<div class="form-label-group">
<input type="text" id="inputEmail" class="form-control" name="username" placeholder="Email address" required autofocus>
<label for="inputEmail">Email</label>
</div>