How to save image to model in wagtail? - django

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>

Related

django form return Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance

Am working on school database, when I'm trying to submit my django form using pure html form, it throws me an error like this: ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. How can i solve this error please?
Am using this method for the first time:
class PrimaryCreativeView(LoginRequiredMixin, CreateView):
model = Primary
fields = ['profilePicture', 'firstName', 'sureName',
'gender', 'address', 'classOf', 'album',
'hobbies', 'dateOfBirth','year',
'name', 'contact', 'homeAddress',
'emails', 'nationality','occupations',
'officeAddress', 'state', 'localGovernments',
'relationship' ]
template_name = 'post_student_primary.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
form.instance.user = self.request.user
return super (PrimaryCreativeView, self).form_valid(form)
so I changed it to this method down below, but I don't know why it throws me this error:ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. when I submitted the form. How can I solve? And why this error is shown?
my Views:
def primary_submit_form(request):
albums = PrimaryAlbum.objects.filter(user=request.user)
if request.method == 'POST':
addmisssion_number = request.POST.get('addmisssion_number')
profile_picture = request.POST.get('profile_picture', None)
first_name = request.POST.get('first_name')
sure_name = request.POST['sure_name']
gender = request.POST['gender']
address_of_student = request.POST['address_of_student']
class_Of_student = request.POST['class_Of_student']
album = request.POST['album']
date_of_birth = request.POST['date_of_birth']
nationality_of_student = request.POST['nationality_of_student']
state_of_student = request.POST['state_of_student']
local_government_of_student = request.POST['local_government_of_student']
certificate_of_birth_photo = request.FILES.get('certificate_of_birth_photo')
residential_certificate_photo = request.FILES.get('residential_certificate_photo')
name = request.POST['name']
contact = request.POST['contact']
address_2 = request.POST['address_2']
nationality_2 = request.POST['nationality_2']
occupations = request.POST['occupations']
work_address = request.POST['work_address']
state_2 = request.POST['state_2']
local_government_2 = request.POST['local_government_2']
relationship = request.POST['relationship']
student_create = Primary.objects.create(
addmisssion_number=addmisssion_number, profile_picture=profile_picture,
first_name=first_name, sure_name=sure_name, gender=gender, address_of_student=address_of_student,
class_Of_student=class_Of_student, album=album, date_of_birth=date_of_birth,
nationality_of_student=nationality_of_student, state_of_student=state_of_student, local_government_of_student=local_government_of_student,
certificate_of_birth_photo=certificate_of_birth_photo, residential_certificate_photo=residential_certificate_photo,
name=name, contact=contact, address_2=address_2, nationality_2=nationality_2, occupations=occupations, work_address=work_address,
state_2=state_2, local_government_2=local_government_2, relationship=relationship
)
student_create.save()
return redirect('Primary-Albums')
return render(request, 'create_primary_student_information.html', {'albums':albums})
my models:
class PrimaryAlbum(models.Model):
name = models.CharField(max_length=100)
user = models.ForeignKey(User,
on_delete=models.CASCADE)
def __str__(self):
return self.name
class Primary(models.Model):
addminssion_number = models.CharField(max_length=40)
profilePicture = models.FileField(upload_to='image')
first_name = models.CharField(max_length=40)
sure_name = models.CharField(max_length=40)
gender = models.CharField(max_length=25)
address_of_student = models.CharField(max_length=50)
class_Of_student = models.CharField(max_length=20)
date_of_birth = models.CharField(max_length=20)
album = models.ForeignKey(PrimaryAlbum, on_delete=models.CASCADE)
hobbies = models.TextField(blank=True, null=True)
nationality_of_student = models.CharField(max_length=50)
state_of_student = models.CharField(max_length=30)
local_government_of_student = models.CharField(max_length=50)
certificate_of_birth_photo = models.FileField(upload_to='image')
residential_certificate_photo = models.FileField(upload_to='image')
#Guadians
name = models.CharField(max_length=30)
contact = models.CharField(max_length=15)
address_2 = models.CharField(max_length=50)
nationality_2 = models.CharField(max_length=50)
occupations = models.CharField(max_length=50)
work_address = models.CharField(max_length=50)
state = models.CharField(max_length=30)
local_government = models.CharField(max_length=50)
relationship = models.CharField(max_length=25)
def __str__(self):
return str(self.first_name)
My Templates:
<form action="{% url 'Create-Primary-Student' %}" method="POST">
{% csrf_token %}
<div class="container">
<div class="row">
<div class="text-center">
{% for message in messages %}
<h5>{{message}}</h5>
{% endfor %}
</div>
<div class="col-md-4">
<label for="" class="form-label">Admission Number</label>
<input type="text" class="form-control" name="addmission_number">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Profile Picture</label>
<input type="file" class="form-control" name="profile_picture">
</div>
<div class="col-md-4">
<label for="" class="form-label">First Name</label>
<input type="text" class="form-control" name="first_name">
</div>
<div class="col-md-4">
<label for="" class="form-label">Sure Name</label>
<input type="text" class="form-control" name="sure_name">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label"> Gender</label>
<input type="text" class="form-control" name="gender">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Address</label>
<input type="text" class="form-control" name="address_of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Class</label>
<input type="text" class="form-control" name="class_Of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Date Of Birth</label>
<input type="date" class="form-control" name="date_of_birth">
</div>
<div class="col-md-4">
<label for="" class="form-group">Year Of Graduation</label>
<select class="form-select" aria-label="Default select example" name="album">
<option selected>Select Year Of Graduation</option>
{% for album in albums %}
<option value="{{ album.id }}">{{ album.name }}</option>
{% endfor %}
</select>
<br>
</div>
<div class="col-md-4">
<label class="form-label">Example textarea</label>
<textarea class="form-control" rows="3" name="hobbies"></textarea>
<br>
</div>
<div class="col-md-4">
<br>
<label class="form-label">Student Country</label>
<input type="text" class="form-control" name="nationality_of_student">
</div>
<div class="col-md-4">
<br>
<label for="" class="form-label">State Of Origin</label>
<input type="text" class="form-control" name="state_of_student">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Local Government</label>
<input type="text" class="form-control" name="local_government_of_student">
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Certificate of Birth Photo</label>
<input type="file" class="form-control" name="certificate_of_birth_photo">
</div>
<div class="col-md-4">
<label for="" class="form-label">Student Indigen Photo</label>
<input type="file" class="form-control" name="residential_certificate_photo">
</div>
<div class="text-center">
<br>
<h2>Guidance Information</h2>
<br>
</div>
<div class="col-md-4">
<label for="" class="form-label">Full Name</label>
<input type="text" class="form-control" name="name">
</div>
<div class="col-md-4">
<label for="" class="form-label">Phone Number</label>
<input type="text" class="form-control" name="contact">
</div>
<div class="col-md-4">
<label for="" class="form-label">Home Address</label>
<input type="text" class="form-control" name="address_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Country</label>
<input type="text" class="form-control" name="nationality_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Occupation</label>
<input type="text" class="form-control" name="occupations">
</div>
<div class="col-md-4">
<label for="" class="form-label">Work Address</label>
<input type="text" class="form-control" name="work_address">
</div>
<div class="col-md-4">
<label for="" class="form-label">State Of Origin</label>
<input type="text" class="form-control" name="state_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Local Government</label>
<input type="text" class="form-control" name="local_government_2">
</div>
<div class="col-md-4">
<label for="" class="form-label">Relationship To Student</label>
<input type="text" class="form-control" name="relationship">
</div>
<button type="submit" class="btn btn-success">create album</button>
</div>
</div>
</form>
You create this by assigning it to album_id, not album:
student_create = Primary.objects.create(
addmisssion_number=addmisssion_number,
profile_picture=profile_picture,
first_name=first_name,
sure_name=sure_name,
gender=gender,
address_of_student=address_of_student,
class_Of_student=class_Of_student,
album_id=album,
date_of_birth=date_of_birth,
nationality_of_student=nationality_of_student,
state_of_student=state_of_student,
local_government_of_student=local_government_of_student,
certificate_of_birth_photo=certificate_of_birth_photo,
residential_certificate_photo=residential_certificate_photo,
name=name,
contact=contact,
address_2=address_2,
nationality_2=nationality_2,
occupations=occupations,
work_address=work_address,
state_2=state_2,
local_government_2=local_government_2,
relationship=relationship,
)
I would however strongly advise to use a ModelFormĀ [Django-doc] this will remove a lot of boilerplate code from the view, do proper validation, and create the object effectively.

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 Save a ImageField in a model in Django?

I have a CustomUser Model with following fields
class CustomUser(AbstractUser):
image = models.ImageField(upload_to='images/',blank=True,null=True)
email = models.EmailField(_('email address'), unique=True)
fullname = models.CharField(null=True,max_length=40)
dob = models.DateField(default=date.today)
phonenumber = models.CharField(max_length=10, blank=True)
passportnumber = models.CharField(max_length=10, blank=True)
I am trying to have a progress bar for the image upload so I have two forms in single page as follows
<body>
<div class='row'>
<div class='col-sm-3'></div>
<div class="col-sm-6 ">
<h4>Register</h4>
<form id="uploadform" method=POST enctype=multipart/form-data action="/upload/">
{% csrf_token %}
<input type=file id="media" name=media ;>
<input type="submit" onclick='copy_url(document.getElementById("media").files[0].name)'>
</form>
<div class="progress">
<div id="progress-bar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0"
aria-valuemin="0" aria-valuemax="100">0%</div>
</div>
<form id="registerform"method="post" enctype="multipart/form-data">
{% csrf_token %}
<!-- <div class="form-group ">
<label>Image</label>
<input name="image" type="file" value="">
</div> -->
<div class="form-group ">
<input id="image" name="image" type="hidden" value="">
</div>
<div class="form-group ">
<label>Email address</label>
<input name="email" class="form-control" type="email" value="">
</div>
<div class="form-group ">
<label>Fullname</label>
<input name="fullname" class="form-control" type="text" value="">
</div>
<div class="form-group ">
<label>Dob</label>
<input name="dob" class="form-control" type="date" value="">
</div>
<div class="form-group ">
<label>Phonenumber</label>
<input name="phonenumber" class="form-control" type="text" value="">
</div>
<div class="form-group ">
<label>Passportnumber</label>
<input name="passportnumber" class="form-control" type="text" value="">
</div>
<div class="form-group ">
<label>Username</label>
<input name="username" class="form-control" type="text" value="">
<span class="help-block">Required. 150 characters or fewer. Letters, digits and #/./+/-/_
only.</span>
</div>
<div class="form-group ">
<label>Password</label>
<input name="password" class="form-control" type="text" value="">
</div>
<div class="form-group ">
<label>Confirm password</label>
<input name="confirm_password" class="form-control" type="text" value="">
</div>
<!-- <label for="{{ serializer.fullname.id_for_label }}">Fullname:</label>
<input type="text" id ="{{ serializer.fullname }}"><br/>
<label for="{{ serializer.dob.id_for_label }}">Dob:</label>
<input type="date" id ="{{ serializer.dob }}"><br/> -->
<!-- {% render_form serializer %} -->
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</body>
After uploading the image. I want that image to be stored in my model for the corresponding user.How do I do that?
I am using ajax for the progress bar
$(document).ready(function(){
$('#uploadform').on('click', function(event){
event.preventDefault();
var formData = new FormData($('#uploadform')[0]);
$.ajax({
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress',function(e){
if(e.lengthComputable){
console.log('Bytes Loaded :' + e.loaded)
console.log('Total Size:' + e.total)
console.log('Percentage Uploaded:' + e.loaded/e.total)
var percent = Math.round(e.loaded / e.total * 100);
$('#progress-bar').attr('aria-valuenow',percent).css('width',percent+'%').text(percent+'%')
}
})
return xhr;
},
type : 'POST',
url : '/upload/',
data : formData,
processData : false,
contentType : false,
success : function(response){
var fs = response
alert('File uploaded!');
}
})
});
});
I tried to pass the location of the image uploaded in form1 say /images/photo.jpeg to the imagefield but it throws error. How do I pass that to the imagefield ???

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>