How to force this field to submit data? - django

I have a form that looks like
I am trying to add a product. The description of which will be entered through this form. But my textarea dont send data to product
html:
<div class="col-12">
<div class="mb-2">
<label class="form-label">Текст новости</label>
<div id="blog-editor-wrapper">
<div id="blog-editor-container">
<div class="editor">
<textarea name="text" class="form-control" id="text" rows="3" required>TEXT</textarea>
</div>
</div>
</div>
</div>
</div>
vievs:
def create(request):
if (request.method == 'POST'):
obj, created = Posts.objects.get_or_create(title=request.POST.get("title"))
obj.text=request.POST.get("text")
obj.preview=request.POST.get("preview")
obj.date=request.POST.get("date")
obj.image=request.POST.get("image")
obj.save()
models:
text = models.TextField('Текст статьи')
Мy other fields (not custom) look like this
<label class="form-label" for="blog-edit-title">Заголовок</label>
<input type="text" id="blog-edit-title" class="form-control" value="" name="title" />

Related

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.

Django - how to modify crispy forms?

First, I want to generate a page that looks like this:
There are three things that makes it difficult.
1. Label + Input field set should line up horizontally
2. Some of the fields have checkbox
3. Date Field has a special Bootstrap plugin.
Here are the html source code for each types:
generic type:
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" style="margin-bottom: 5px">
<label class="input-upper-title">Drill String Name</label>
<input type="text" id="" class="form-control input-field-height-vertical" name="" required="">
</div>
has checkbox:
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" style="margin-bottom: 5px">
<label class="input-upper-title">String Length (ft)</label>
<div class="has-checkbox">
<input type="checkbox"><input disabled="disabled" type="text" id="" class="form-control input-field-height-vertical input-calculated" name="" data-parsley-trigger="" required="">
</div>
</div>
has date plugin:
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" style="margin-bottom: 5px">
<label class="input-upper-title">Date Run</label>
<div class="form-group">
<div class="input-group date" id="datetimepicker7" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input input-field-height-vertical" data-target="#datetimepicker7"/>
<div class="input-group-append" data-target="#datetimepicker7" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
</div>
And here is my forms.py:
class BHA_overall_Form(forms.ModelForm):
prefix = 'bha_overall'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
class Meta():
model = BHA_overall
fields = '__all__'
How should I modify my forms.py, using crispy_forms to get the same effect as my html source code does?

Django:get field values using views.py from html form

Hello everyone I have an HTML form as follows:
<body class="">
<div class="navbar navbar-static-top navbar-inverse"></div>
<div style="height:20%; width:30%; margin-top:12%; margin-left:40%;">
<div class="list-group">
<form role="form">
<br/>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-circle-o-notch" ></i></span>
<input type="text" name="Username" class="form-control" placeholder="Username" />
</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-tag" ></i></span>
<input type="text" name="first_name" class="form-control" placeholder="FIRST_NAME" />
</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-tag" ></i></span>
<input type="text" name="last_name" class="form-control" placeholder="LAST_NAME" />
</div>
...
...
POST
</form>
</div>
</div>
</body>
and after clicking on post i am redirecting it to views.py. can any one tell me how to get the field values of all the fields of the form into views.py. thanks in advance
Each input should have a name attribute:
<input type="text" name="username" class="form-control"
placeholder="Desired Username" />
And then in your view you can access that data using request.POST or request.GET dictionary-like objects (it depends on the method attribute of the <form> tag):
def register(request):
username = request.POST['username']
...
But you shouldn't render/handle forms this PHPish way. Learn the django forms.
To catch the data in python backend
for POST request:
def register(request):
username = request.POST.get('username')
for GET request
def register(request):
username = request.GET.get('username')
.get was missing on earlier answer