Hi im trying to pass a name from a form to a view in django using POST. There are no errors in the execution but its passing nothing from the template and dont know if i doing something wrong here. Im starting with django so i can have newbie errors. If u need more information tell me pls.
Views.py
def crear_pdf(request):
empresa_selec = ""
form = EmpModelForm()
if request.method == 'POST':
form = EmpModelForm(data=request.POST)
if form.is_valid():
empresa_selec = form.cleaned_data['nombre']
#"empresa_selec" that's the empty variable
Models.py
class Empresa_modelo(models.Model):
nombre = models.CharField(max_length=100,blank=True,null=True)
Forms.py
class EmpModelForm(forms.ModelForm):
class Meta:
model = Empresa_modelo
fields = ["nombre"]
template.html
<div class="container-fluid">
<form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %}
<p>Empresa</p>
<input type="text" name="empresa">
<br>
<button type="submit">Subir</button>
</form>
<br>
<a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a>
</div>
You haven't got a field called nombre in your template; you only have empresa.
That's presumably because you don't ouput your EmpModelForm in the template. You don't show your render call in the view, but assuming you pass it as form, you should just do {{ form.as_p }} in the template.
Try using:
<input type="text" name="nombre">
There is no field named empresa.
Had a look at your code,there are a couple of issues.First you are not using the model form defined in your forms.py file in your template. Second you have defined an input text box with the name that you are not referring in your views. Either use the model form or use the same name of your input text box in your views.
def crear_pdf(request):
empresa_selec = ""
form = EmpModelForm()
if request.method == 'POST':
form = EmpModelForm(data=request.POST)
if form.is_valid():
empresa_selec = form.cleaned_data['nombre']
else:
return render(request,"template.html",{"form":form})
And in your template you can edit as such:
<div class="container-fluid">
<form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %}
{{ form.as_p }}
<br>
<button type="submit">Subir</button>
</form>
<br>
<a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a>
</div>
Hope this helps.
Related
Suppose im saving a url from a texbox given by user the URL is submitted by user and its saved to my models and now what i wanna do is let the user add different sections/clusters such as technology,sports etc from his end suppose where he inputs the URL there itself he can define that cluster/section and save that particular URL to the particular section/cluster he made or selected in the option is the section/cluster was already there! could anyone help or give me a small example for the same? what would be a better approach do it with django choices or some other way?
TIA.
ill paste the current code below :
form.py
class UrlSaveForm(ModelForm):
class Meta:
model = UrlSaveModel
fields = ['the_url']
models.py (below)
class UrlSaveModel(models.Model):
the_url = EmbedVideoField()
desc = models.CharField(max_length=200)
def __str__(self):
return self.desc
HTML for saving: save.html
{% extends 'base.html' %} {% block content %}
<form method="post" action="{% url 'func' %}">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1"
>Enter the URL here to save video to the library:</label
>
<textarea
class="form-control"
id="exampleFormControlTextarea1"
rows="2"
name="the_url"
placeholder="Enter the URL here"
></textarea>
<br />
<button type="submit" class="btn btn-primary mb-2">Save URL</button>
</div>
</form>
{% endblock %}
"""and little snippet of views.py"""
if form.is_valid():
print('form is valid')
posted_url = request.POST['the_url']
yt = YouTube(posted_url)
description = yt.title
print('description-extracted:', description)
print('Posted_url', posted_url)
obj = UrlSaveModel(desc=description, the_url=posted_url)
obj.save()
return HttpResponse('saved sucessfully!')
How can I save django form without validating. I have a simple form. Like i have a dropdown option if a user select a figi it brings a different field from the model payment and if a user select bank teller it brings a different field from the model payment. So I wanna save them. But its not saving when I use form.is_valid() and it still shows me code post 200 but its not in my database and when I remove form.is_valid(), it throws valueError:validation error. Now the imagefield doesn't save
class payments(models.Model):
Amount=models.IntegerField(default=00000)
figiID=models.CharField(default='F-00000',max_length=10,required=False)
Bank_Teller=models.ImageField(upload_to='media/',required=False)
html
<select id='modePayment'>
<option value='test1'>Figi</option>
<option value='test2'>Bank Teller</option>
</select><br><br>
<div class="test1 pricebox">
<form method="post">
{% csrf_token %}
<h6>Amount:{{pDetail.Amount}}</h6>
<h6>Figi-ID{{pDetail.figiID}}</h6>
<button style="background:#4CAF50;color:white;width:150px;height:40px;" value="submit" >Invest</button>
</form>
</div>
<div class="test2 pricebox">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<h6>Amount:{{pDetail.Amount}}</h6>
<h6>Bank Teller{{pDetail.Bank_Teller}}</h6>
<button style="background:#4CAF50;color:white;width:150px;height:40px;" value="submit" >Invest</button>
</form>
</div>
views.py
def dashboard(request):
if request.user.is_authenticated:
allDocs = Registration.objects.all()
pDetail=payment_form()
if request.method=='POST':
pDetail=payment_form(request.POST,request.FILES)
if pDetail.is_valid():
pDetail.save()
context={'doc':allDocs,'pDetail':pDetail,'iDetail':investment}
return render(request,'dashboard.html',context)
else:
return redirect('Tan:login')
You forgot to save the form variable pDetail.
Views.py
def dashboard(request):
if request.user.is_authenticated:
allDocs = Registration.objects.all()
pDetail=payment_form()
if request.method=='POST':
pDetail=payment_form(request.POST,request.FILES)
if pDetail.is_valid():
pDetail=pDetail.save()
pDetail.save() #<----- Add this
context={'doc':allDocs,'pDetail':pDetail,'iDetail':investment}
return render(request,'dashboard.html',context)
else:
return redirect('Tan:login')
Image cannot be uploaded.form.is_valid() always returned Flase.I wrote in html
<main>
<form action="/app/img/" method="POST" enctype="multipart/form-data" role="form">
{% csrf_token %}
<h3>Upload Image!!</h3>
<div class="input-group">
<label class="input-group-btn">
<span class="btn-lg">
Select image
<input id="file1" type="file" name="image" accept="image/*">
</span>
</label>
</div>
<div class="col-xs-offset-2">
<input id="send" type="submit" value="Send" class="form-control">
</div>
</form>
</main>
in views.py
#require_POST
def img(request):
img_form = ImageForm(request.POST or None)
print(img_form.is_valid())
if request.method == "POST" and img_form.is_valid():
image = request.POST.get("image", "")
in forms.py
class ImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = Image
fields = ('image',)
I really cannot understand why I can't sent images.form.is_valid() returned Flase means Form cannot be gotten images, right? What is wrong in my code?How should I fix this?
From the documentation:
When Django handles a file upload, the file data ends up placed in request.FILES.
You are not passing request.FILES to your form, so it never sees the uploaded file. You need to pass this to the form as follows:
img_form = ImageForm(request.POST, request.FILES)
i am not able to upload an image from html page but it is possible from admin page
here is my models.py:
def get_upload_file_name(instance,filename):
return "image/%s_%s"%(str(time()).replace('.','_'),filename)
class Company_Profile(models.Model):
user = models.ForeignKey(User)
name = models.CharField(_('Company Name'), max_length= 30)
logo = models.FileField(_('Company Logo'), upload_to=get_upload_file_name)
address = models.TextField(_('Contact Address'), max_length=50)
phone_no = models.IntegerField(_('Contact No'), max_length=12)
my views.py:
def company_prof(request):
if request.method == 'POST':
comp_prof = Company_Prof(request.POST, request.FILES)
if comp_prof.is_valid():
save_prof = comp_prof.save(commit=False)
save_prof.user = request.user
save_prof.save()
messages.success(request, 'Thank you for Registration')
return HttpResponseRedirect('company/'+str(save_prof.id))
else:
comp_prof =Company_Prof()
variables = RequestContext(request, {
'comp_form': Company_Prof()})
return render_to_response("comp_profile.html",
locals(),
context_instance = RequestContext(request))
my settings.py is:
MEDIA_ROOT ='G:\Mini project\Pycharm projects\project4\static/'
MEDIA_URL = ''
html page is:
<form enctype="application/x-www-form-urlencoded" class="global_form" action="" method="post"><div><div><h3>Create Account</h3>
<div id="connect_signup_box" class="connect_box_form clearfix">
<form method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ comp_prof.as_p }}
<input type="submit" class="btn btn-success" value="submit">
{% if save_prof %}
<h3>The details are submitted</h3>
{% endif %}
<input type="reset" class="btn" value="cancel">
{% if value == 'cancel' %}
<h3>Canceled</h3>
{% endif %}
</form>
</div>
</div>
</div>
</form>
when i submit it says no files are chosen. but from admin page there is no problem.
help me..
I think the problem is you have nested forms, which isn't supported by browsers (Can you nest html forms?).
So I am assuming that the browser is just using the first form definition, which has the wrong enctype. Try removing the first form declaration and just keeping this one: <form method="POST" enctype="multipart/form-data">.
I am working with Django forms and for some reason, this form will not validate! It submits alright, or at least the runserver shows an http post response with code 200 (ok). For some reason though, my form will not pass the is_valid test!
views.py:
def new_show(request):
if request.method == 'POST':
img_form = ImageForm(request.POST, request.FILES)
show_form = NewShowForm(request.POST)
if show_form.is_valid():
new_Show = Show()
new_Show.title=show_form.cleaned_data['title']
new_Show.body=show_form.cleaned_data['body']
new_Show.pub_date=timezone.now()
new_Show.location=show_form.cleaned_data['location']
new_Show.time=show_form.cleaned_data['time']
new_Show.save()
if img_form.is_valid():
image=Image(image=request.FILES['imageFile'])
new_Show.image_set.add(image)
return HttpResponseRedirect(reverse('shows'))
else:
return HttpResponseRedirect(reverse('shows'))
else:
show_form = NewShowForm()
img_form = ImageForm()
return render_to_response(
'shows/new_show.html',
{'show_form': show_form, 'img_form': img_form},
context_instance=RequestContext(request)
)
Here is my template snippet:
<form action="{% url "new_show" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ show_form.non_field_errors }}</p>
<p>
<label for="title">Title:</label>
<input type="text" name="title"/>
</p>
<p>
<label for="body">Body:</label>
<textarea type="text" name="body"> </textarea>
</p>
<p>
<label for="location">Location:</label>
<input type="text" name="location"/>
</p>
<p>
<label for="time">Date:</label>
<input type="text" id="time" maxlength="25" size="25" name="time"><img src="{{ STATIC_URL }}../../static/cal.gif" width="16" height="16" border="0" alt="Pick a date">
</p>
<!-- Upload Form. Note enctype attribute! -->
{% csrf_token %}
<p>{{ img_form.non_field_errors }}</p>
<p>{{ img_form.imageFile.label_tag }}</p>
<p>
{{ img_form.imageFile.errors }}
{{ img_form.imageFile }}
</p>
<p><input type="submit" value="Add Upcoming Show"></input></p>
</form>
Here is my form Class:
class NewShowForm(forms.Form):
title=forms.CharField()
body=forms.CharField(widget=forms.TextArea)
location=forms.CharField()
time=forms.DateTimeField(required=True)
class ImageForm(forms.Form):
imageFile = forms.FileField(required=False, label='Select an Image')
Please help me!
If new_Show is a model, why not create a ModelForm instead of forms.Form?
So, instead of
class NewShowForm(forms.Form):
title=forms.CharField()
body=forms.CharField(widget=forms.TextArea)
location=forms.CharField()
time=forms.DateTimeField(required=True)
class ImageForm(forms.Form):
imageFile = forms.FileField(required=False, label='Select an Image')
why not using,
from django.forms import ModelForm
class NewShowForm(ModelForm):
class Meta:
model = NewShow
class ImageForm(ModelForm):
class Meta:
model = Image
?
Using ModelForm will ensure that form validation meets that of model. Moreover, it can cut off your code (especially line 6 to 11).
It will help to add these two lines to your view before if is_valid() to see the errors it's giving:
if request.method == 'POST':
img_form = ImageForm(request.POST, request.FILES)
show_form = NewShowForm(request.POST)
print(form.is_valid())
print(form.errors)
if show_form.is_valid():
You can paste the errors here and we can see what's the issue
Since you've put 2 Django forms together under one HTML form tag, when you submit the form on the front-end you're sending an extra field through request.POST that your NewShowForm doesn't have. If you combine both forms into a single Django form, you should be able to get this to work.