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

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>

Related

RuntimeError at /signup: Change your form to point to 127.0.0.1:8000/signup/ , or set APPEND_SLASH=False in your Django settings

RuntimeError at /signup
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/signup/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
I got this problem while using forms. Please help
I have used bootstrap for styling
<form action="/signup/" method = "post" >
{% csrf_token %}
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">#</span>
<input type="text" class="form-control" placeholder="Username" name = "username" aria-label="Username" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Firstname" name="fname" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Lastname" name="lname" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Recipient's email" name="email" aria-describedby="basic-addon2">
<span class="input-group-text" id="basic-addon2">#gmail.com</span>
</div>
<div class="input-group mb-3">
<input type="password" placeholder="password" name = "password" class="form-control">
</div>
<div class="input-group mb-3">
<input type="password" placeholder="confirm password" name = "con_password" class="form-control">
</div>
<div class="input-group mb-3">
<button type="submit" class="btn btn-primary">Signup</buttpn>
</div>
</form>
</div>
Views.py
def signup(request):
if (request.method == "POST"):
username = request.POST.get("username")
fname = request.POST.get("fname")
lname = request.POST.get("lname")
email = request.POST.get("email")
password = request.POST.get("password")
con_password = request.POST.get("con_password")
User.objects.create_user(username=username, first_name=fname, last_name=lname, email=email, password=password)
User.save()
messages.success(request, "Account created successfully")
return redirect("login")
Should Redirect to login Page
Either add APPEND_SLASH=False in settings.py. Or change form action="/signup/" to form action="/signup"

How to save image to model in wagtail?

When I try to do this I get the following error "'BoundField' object has no attribute 'width'".
My model
class Reviews(models.Model):
...
image = models.ForeignKey('wagtailimages.Image',
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name='+')
def __str__(self):
return(self.author)
Save method, error on Image.objects.create
class FeedbackPage(Page):
...
def serve(self, request):
post_data = request.POST or None
review_form_class = ReviewForm
if "review" in request.POST:
review_form = review_form_class(post_data, prefix='review')
new_review = Reviews()
new_review.author = review_form['author']
new_review.is_pub = False
new_review.text = review_form['text']
new_image = Image.objects.create(
file=review_form['file'],
title="Image title"
)
new_review.image = new_image
if new_review.is_valid():
new_review.save()
My form
class ReviewForm(TemplateForm):
file = forms.ImageField()
I used part of code of this answer https://stackoverflow.com/a/42551931/9842214
from wagtail.images.models import Image
def save(self, commit=False):
if not commit:
raise Exception("This form doesn't support save(commit=False)")
# build the instance for this form, but don't save it to the db yet
instance = super(MyForm, self).save(commit=False)
# create the Image object
avatar = Image.objects.create(
file=self.cleaned_data['avatar_image'],
title="Image title"
# you may need to add more fields such as collection to make it a valid image...
)
# attach the image to your final model, and save
instance.avatar = avatar
instance.save()
return instance
def chef_register(request):
if request.method == "POST" and "image" in request.FILES:
fullname= request.POST.get('fullname')
contact = request.POST.get('contact')
license_no = request.POST.get('license_no')
email = request.POST.get('email')
city = request.POST.get('city')
password = request.POST.get('password')
address = request.POST.get('address')
image= request.FILES['image']
restaurent_name = request.POST.get('restaurent_name')
ChefDetailsModel.objects.create(fullname=fullname,contact=contact,license_no=license_no,email=email,city=city,password=password,address=address,logo=image,restaurent_name=restaurent_name)
<section class="py-5 overflow-hidden bg-primary" id="">
<div class="container">
<div class="row flex-center">
<div class="row">
<div class="row" >
<center><h1 style="color:white">Register Now</h1></center><br><br><br>
<form style="border: radius 10px;border-color:white" method="post" enctype="multipart/form-data" name="myform" onsubmit = "return validate()">
{% csrf_token %}
<div>
<center> <div class="row" >
<div class="col-4">
<label class="" for="inputDelivery" style="color:white">FULL NAME</label>
<input class="form-control input-box form-foodwagon-control" name="fullname" id="inputDelivery" type="text" placeholder="Enter Your Name" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">MOBILE NUMBER</label>
<input class="form-control input-box form-foodwagon-control"name="contact" id="inputDelivery" type="text" placeholder="Enter Your Mobile Number" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">License Id</label>
<input class="form-control input-box form-foodwagon-control"name="license_no" id="inputDelivery" type="text" placeholder="Enter Your FSSAI License" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">Email Id</label>
<input class="form-control input-box form-foodwagon-control" name="email" id="inputDelivery" type="text" placeholder="Enter Your Email Address" />
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">CITY</label>
<input class="form-control input-box form-foodwagon-control" name="city" id="inputDelivery" type="text" placeholder="Enter Your City Name" />
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">PASSWORD</label>
<input class="form-control input-box form-foodwagon-control" name="password" id="inputDelivery" type="password" placeholder="Enter Your Password" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">ADDRESS</label>
<input class="form-control input-box form-foodwagon-control" name="address" id="inputDelivery" type="text" placeholder="Enter Your Full Adress" /><br>
</div>
<div class="col-4">
<label class="" for="inputDelivery"style="color:white">Restaurent Name</label>
<input class="form-control input-box form-foodwagon-control" name="restaurent_name" id="inputDelivery" type="text" placeholder="Enter Restaurent Name" /><br>
</div>
<div class="col-4">
<label class="form-label" for="customFile" style="color:white">LOGO</label>
<input type="file" class="form-control" name="image" />
</div>
</div> </center>
</div>
<center><button type="submit" class="btn btn-success">REGISTER NOW</button></center><br>
</form>
</div>
</div>
</div>
</div>
</section>

request.FILES is always empty

When I try to post a Django form containing a file field, the file field is being passed as part of the request.POST rather than request.FILES (which is empty). This throws a MultiValueDictKeyError on submitting the form.
Form html
<form class="form-horizontal" action="{% url 'drinkConf' %}" method="post" enctype="multipart/form-data" >
{% csrf_token %}
<!-- Text input-->
<label class="col-md-4 control-label" for="date">Date</label>
<div class="col-md-4">
<input id="date" name="date" type="text" placeholder="" class="form-control input-md" required="">
</div>
<!-- Textarea -->
<label class="col-md-4 control-label" for="notes">Notes</label>
<div class="col-md-4">
<textarea class="form-control" id="notes" name="notes"></textarea>
</div>
<!-- Multiple Radios (inline) -->
<label class="col-md-4 control-label" for="rating">Rating</label>
<div class="col-md-4">
<label class="radio-inline" for="rating-0">
<input type="radio" name="rating" id="rating-0" value=1 checked="checked">
1
</label>
<label class="radio-inline" for="rating-1">
<input type="radio" name="rating" id="rating-1" value=2>
2
</label>
<label class="radio-inline" for="rating-2">
<input type="radio" name="rating" id="rating-2" value=3>
3
</label>
<label class="radio-inline" for="rating-3">
<input type="radio" name="rating" id="rating-3" value=4>
4
</label>
<label class="radio-inline" for="rating-4">
<input type="radio" name="rating" id="rating-4" value=5>
5
</label>
</div>
<label class="form-label" for="image">Upload an image</label>
<input type="file" class="form-control" id="image" name="image" />
<!-- Button (Double) -->
<label class="col-md-4 control-label" for="Submit"></label>
<div class="col-md-8">
<input class="btn btn-success" type="submit" value="Submit" />
<button id="Cancel" name="Cancel" class="btn btn-inverse">Cancel</button>
</div>
</div>
</form>
My view
#login_required
def DrinkBeerConfirm(request):
if request.method == 'POST':
if request.POST['date']:
cellar_id = request.session['cellar'] #Get cellar record ID
cellarEntry = Cellar.objects.get(pk=cellar_id)
journal = Journal() #make journal entry
journal.user = request.user
journal.beer = cellarEntry.beer
journal.date = request.POST['date']
journal.notes = request.POST['notes']
journal.rating = request.POST['rating']
journal.image = request.FILES['image']
journal.servingType = request.POST['servingType']
beer = beer.objects.get(id = cellarEntry.beer) #update beer ratings
currentRating = beer.rating * beer.numRatings
beer.numRatings = beer.numRatings + 1
beer.rating = currentRating / beer.numRatings
""" if cellarEntry.container == 'KG': #update stock quantity for keg
cellarEntry.vol = cellarEntry.vol - serving_qty
if cellarEntry.vol <= 0:
cellarEntry.delete()
else:
cellarEntry.save()
#display a toast here and delete entry
else:
cellarEntry.qty = cellarEntry.qty - 1 """
if cellarEntry.qty <= 0:
cellarEntry.delete()
else:
cellarEntry.save()
journal.save() #Save journal, beer and cellar records
beer.save()
As far as I can tell, this is all correct: I have enctype="multipart/form-data" set for the form, and the form fields for the file and submit look OK. I feel like I'm missing something obvious...
I guess you incorrect close tag , it affects to POST request.
Check that.

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.

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

{% 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