request.FILES is always empty - django

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.

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>

How to force this field to submit data?

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" />

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

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>

Django error: didn't return an HttpResponse object. It returned None instead

I have the following form:
class PrestataireProfilForm(forms.ModelForm):
class Meta:
model = Prestataire
fields = ["user", "name", "address", "phone", "fax", "city"]
def __init__(self, *args, **kwargs):
super(PrestataireProfilForm, self).__init__(*args, **kwargs)
self.fields['city'].widget.attrs.update({'class' : 'custom-select'})
self.fields['city'].label = ""
And this is my view:
#login_required
def prestataire_profil(request):
prestataire = Prestataire.objects.filter(user=request.user).first()
is_prestataire = request.user.groups.filter(name='Prestataire').exists()
form = PrestataireProfilForm(request.POST or None, instance=prestataire)
if request.method == 'POST':
context = {
'profil': prestataire,
'is_prestataire': is_prestataire,
'form': form
}
if form.is_valid():
prestataire = form.save(commit=False)
prestataire.save()
context = {
'profil': prestataire,
'is_prestataire': is_prestataire
}
# return render(request, 'dashboard/prestataires/profil.html', context)
return redirect('prestataire_profil')
else:
context = {
'profil': prestataire,
'is_prestataire': is_prestataire,
'form': form
}
return render(request, 'dashboard/prestataires/profil.html', context)
And this is my html form:
<form method='POST'>
{% csrf_token %}
<div class="form-group row">
<label for="name" class="col-4 col-form-label">Nom d'utilisateur</label>
<div class="col-8">
<input value="{{ profil.user.username }}" id="name" name="name" placeholder="Nom d'utilisateur" class="form-control here" required="required" type="text" disabled>
</div>
</div>
<div class="form-group row">
<label for="name" class="col-4 col-form-label">Nom*</label>
<div class="col-8">
<input value="{{ profil.user.last_name }}" id="name" name="name" placeholder="Nom" class="form-control here" required="required" type="text">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-4 col-form-label">Prénom*</label>
<div class="col-8">
<input value="{{ profil.user.first_name }}" id="name" name="name" placeholder="Prénom" class="form-control here" required="required" type="text">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-4 col-form-label">Raison sociale*</label>
<div class="col-8">
<input value="{{ profil.name }}" id="name" name="name" placeholder="Raison sociale" class="form-control here" required="required" type="text">
</div>
</div>
<div class="form-group row">
<label for="address" class="col-4 col-form-label">Adresse</label>
<div class="col-8">
<input value="{{ profil.address }}" id="address" name="address" placeholder="Adresse" class="form-control here" type="text">
</div>
</div>
<div class="form-group row mb-0">
<label for="address" class="col-4 col-form-label">Ville</label>
<div class="col-8">
{{ form.city|as_crispy_field }}
</div>
</div>
<div class="form-group row">
<label for="phone" class="col-4 col-form-label">Téléphone</label>
<div class="col-8">
<input id="phone" name="phone" placeholder="Téléphone" class="form-control here" type="text">
</div>
</div>
<div class="form-group row">
<label for="fax" class="col-4 col-form-label">Fax</label>
<div class="col-8">
<input value="" id="fax" name="fax" placeholder="Fax" class="form-control here" type="text">
</div>
</div>
<div class="form-group row">
<div class="offset-4 col-8">
<button name="submit" type="submit" class="btn btn-primary">Update My Profile</button>
</div>
</div>
</form>
When I click on the submit button, it gives me the following error:
Exception Type: ValueError
Exception Value: The view dashboard.views.prestataire_profil didn't return an HttpResponse object. It returned None instead.
The data does not change, and there is no information whatsoever on the debug to see what went wrong. As you can notice in the view, I commented the return render line. I changed it to the return redirect, but same issues!
Please help! Thank you.
Salut !
What I think is that your form is not valid (have you checked it was?). You treated the case if form.is_valid(), but what if it is not? Then you are not returning anything! So, if in all cases you are going to redirect to prestataire_profil, you should do:
#login_required
def prestataire_profil(request):
[...]
if request.method == 'POST':
[...]
if form.is_valid():
[...] # do your stuff
# return redirect('prestataire_profil') <--- wrong indentation
return redirect('prestataire_profil') # <--- there, it will return something anyway
else:
[...]
return render(request, 'dashboard/prestataires/profil.html', context)
A try... except... finally... statement would be a better thing to do, because the way you did won't prevent you to return None instead of an expected HttpResponse object.