views.py:
def index(request):
if request.method == 'POST':
data = request.POST['data']
context = {'mydata': data}
return render(request, 'home/index.html', context)
else:
html_template = loader.get_template('home/index.html')
HttpResponse(html_template.render(request))
index.html:
<form method = 'POST' id = 'post-form'>
<select name = 'data' id = 'data'>
<option> 1 </option>
<option> 2 </option>
</select>
<button type="submit" name = 'post-form'> submit </button>
</form>
<h2> {{ mydata}} </h2> // this line print nothing.
When I click the submit button, I can access data from html submit in views.py.
However, I can't access mydata from Django in html.
How can I solve it?
There are minor mistakes in the code:
You need to return HttpResponse so return HttpResponse(html_template.render(request)), but I'd recommend you to directly use return render(request, 'home/index.html').
Also need to place {% csrf_token %} while dealing with POST data inside form, unless you have mentioned #csrf_exempt decorator on view.
So, try this code:
views.py:
def index(request):
if request.method == 'POST':
data = request.POST.get('data')
context = {'mydata': data}
return render(request, 'home/index.html', context)
else:
return render(request, 'home/index.html')
# OR #
# html_template = loader.get_template('home/index.html')
# return HttpResponse(html_template.render({}, request))
index.html:
<form method='POST' id='post-form'>
{% csrf_token %}
<select name='data' id='data'>
<option> 1 </option>
<option> 2 </option>
</select>
<button type="submit" name='post-form'> submit </button>
</form>
<h2> {{mydata}} </h2>
Related
i made a form in django with one field required (imagefield) but when I fill it by selecting an image, once I fill it it considers that the form is not valid and asks to fill it again I don't understand why, here is my code below:
view.py:
def success(request):
return HttpResponse('successfully uploaded')
def contact(request, plage_name):
name = plage_name
plage = Spot.objects.get(name__iexact=name)
if request.method == 'POST':
form = ContactUsForm(request.FILES) # ajout d’un nouveau formulaire ici
if form.is_valid():
print("it's valide")
plage.photo = form.cleaned_data['photo']
plage.save()
return redirect('success')
else:
form = ContactUsForm()
return render(request,
'pages/Testform.html',
{'form': form}) # passe ce formulaire au gabarit
form.py
class ContactUsForm(forms.Form):
photo = forms.ImageField(required=True)
html
<form action="" method="post" novalidate>
{% csrf_token %}
{{ form }}
<input type="submit" value="Envoyer">
</form>
Url.py
urlpatterns = [
path('contact-us/<path:plage_name>', views.contact, name='contact'),
]
in views.py
if request.method == 'POST':
form = ContactUsForm(request.POST,request.FILES)
in HTML
<form action="" method="post" novalidate enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Envoyer">
</form>
I think your error is on the parameters of form init. The first paramters is for POST data, not FILES:
form = ContactUsForm(request.POST, request.FILES)
And after, you have to call form.save(), probably better than make the update yourself...
in my django website I'm trying to building a page in which there are multiple forms (In particular 3: the first is simply a checkbox, as the second one. The third one requires the entering of two text fields). I've already managed the presence of multiple forms and I've no problem when the user performs the first assignment. The problem is instead during the updating of the answers that the user gave the first time: there are no problems when adding new instances of the text fields of the third form, while instead if I've selected one checkbox of the first two forms and I want to change them unchecking them it seems like django doesn't save the new values. Any idea of why it's happening?
Here's the view associated:
def new_4e2(request, pk, var=None):
if Specifiche.objects.filter(ID_rich = pk).exists():
specs = Specifiche.objects.filter(ID_rich = pk)
choicesp =[]
lista =[]
for spec in specs:
choicesp+=[(spec.id, str(spec.rif))]
lista+=[spec.id]
att = MAIN.objects.get(id=pk)
unform = FormUn(instance=att)
data = {'ID_rich': pk}
form = UnicitaForm(initial=data)
form.fields['rifext'].choices = choicesp
if Unicita.objects.filter(rifext__in = lista).exists():
uns=Unicita.objects.filter(rifext__in = lista)
context={
'att': att,
'uns': uns,
'var':var,
'specs': specs
}
else:
context = {
'att': att,
'var':var,
'specs': specs,
}
form = UnicitaForm(initial = data)
form.fields['rifext'].choices = choicesp
similiform = SimiliForm(instance=att)
if request.method=='POST':
if 'Aggiungi' in request.POST:
form = UnicitaForm(request.POST, initial=data)
form.fields['rifext'].choices = choicesp
if form.is_valid():
form.save()
return redirect(f'/new_4e2/{pk}/{var}//')
if 'Simili' in request.POST:
similiform = SimiliForm(request.POST, instance=att)
if similiform.is_valid():
similiform.save()
return redirect(f'/new_4e2/{pk}/{var}//')
if 'Unicita' in request.POST:
unform = FormUn(request.POST, instance=att)
if unform.is_valid():
unform.save()
return redirect(f'/new_4e2/{pk}/{var}//')
context = context | {'form': form, 'unform':unform, 'similiform': similiform}
return render(request, 'new_4e2.html', context)
The two forms for which I have this problems are: 'unform' and 'similiform'
And here is my template.html
<form method="POST">
{% csrf_token %} 4.1 | {{unform}}
<input type="submit" name="Unicita">
</form>
{% if not att.Unicita %}
<div style="position:relative; left:50 px; height: 10 px; width:500 px;">
<form method="POST">
{% csrf_token %} {{similiform}}
<input type="submit" name="Simili">
</form>
<form action ="" method="POST">
{% csrf_token %}
<h4>Insert Unicita</h4>
{{form}}
<input type="submit" name="Aggiungi">
</form>
...
I have a form in my Django project. I want to when user fills the form and click the send button form will be posted and redirect a URL. I am using action in form for that but when I do this the form is not submitted but it opens the link, and when I delete action, the form is being submitted. I do not know why it is not working?
approval_page.html
<form method="POST" enctype="multipart/form-data"
class="lead_form"
id="lead_form"
action="{% url 'approvals:approve_pending' pk=approval.pk%}"
>
<!-- Very Important csrf Token -->
{% csrf_token %}
{{ form_approval.media }}
{{ form_approval|crispy }}
<input type="hidden" name="rank_name" value="{{ waiting.rank.rank_name }}" />
<input type="submit" class="btn btn-success btn-xs" value="Approve" >
<a href="{% url 'approvals:decline_pending' pk=approval.pk%}">
<button class="btn btn-danger btn-xs" id="approve-btn">Decline</button>
</a>
</form>
views.py
def approval_page(request, id):
...
form_approval = LeadApprovalForm(request.POST)
if request.method == 'POST':
if form_approval.is_valid():
print(request.POST.get('approver_name', None))
lead_approval = form_approval.save()
lead_approval.user = request.user
lead_approval.approval_id = approval
lead_approval.rank = request.POST.get('rank_name', None)
lead_approval.save()
else:
form_approval = LeadApprovalForm()
context = {
...
'form_approval ': form_approval ,
...
}
return render(request, 'approval_page.html', context)
def approve_pending(request, pk):
pending_approval = ApprovalProcess.objects.get(pk=pk)
customer = pending_approval.doc_id.owner
pdf = pending_approval.doc_id
priority_number = 0
...
approval_step.delta_time = abs((approval_step.finish_time - approval_step.start_time).days)
approval_step.save()
...
return redirect('ocr_approve', pending_approval.doc_id.id)
urls.py
url(r'^ocrs/(?P<id>\d+)/analysis/approve$', views.approval_page, name="ocr_approve"),
path('approvals/<int:pk>/', views.approve_pending, name='approve_pending'),
I have a Django form that asks for id number. Hence, when the user clicks on submit, that id number is passed as a parameter to the endpoint.
This URL path('verify/nin/', views.post_nin, name='post_nin') contains the form and asks for the id number while I am submitting the data to this URL to
path('nin/<str:nin>',
views.nin_verification_vw, name="nin_verification")
So I expect to be redirected to http://127.0.0.1:8000/api/nin/15374020766 but instead it is redirecting me to http://127.0.0.1:8000/api/nin/%3Cinput%20type=%22text%22%20name=%22nin%22%20required%20id=%22id_nin%22%3E?nin=15374020766&csrfmiddlewaretoken=u5UmwDW4KRUIvYWXAa64J8g1dTPoJ3yDqtoCuKjboIE2TNxI3tPbjPmCK6FztVwW
How do I avoid the unnecessary parameters?
Here is my forms.py:
class NINPostForm(forms.Form):
"""Form for a user to verify NIN"""
nin = forms.CharField(required=True, help_text='e.g. 123xxxxxxxx')
# check if the nin is a valid one
def clean_nin(self):
nin = self.cleaned_data['nin']
regex = re.compile("^[0-9]{11}$")
if not regex.match(nin):
raise forms.ValidationError("NIN is incorrect.")
return nin
Here is my views.py:
def post_nin(request):
submitted = False
if request.method == 'POST':
form = NINPostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data['nin']
return HttpResponseRedirect('/verify/nin?submitted=True')
else:
form = NINPostForm()
context = {
'form': form,
# 'cd': cd,
}
return render(request, 'ninform.html', context)
And here is my HTML template:
<form action="{% url 'nin_verification' form.nin %}" method="POST">
<table>
{{ form.as_table }}
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
{% csrf_token %}
</form>
first import redirect : from django.shortcuts import redirect
Change your view to :
<form action="{% url 'post_nin' %}" method="POST">
<table>
{{ form.as_table }}
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
{% csrf_token %}
</form>
You were passing the whole field instead of a String by using form.nin in your form action you should use your post_nin view to parse the nin field so...
Change your view to :
def post_nin(request):
submitted = False # Don't understand this part
if request.method == 'POST':
form = NINPostForm(request.POST)
if form.is_valid():
nin = form.cleaned_data['nin']
return redirect('nin_verification', nin=nin)
else:
form = NINPostForm()
context = {
'form': form,
}
return render(request, 'ninform.html', context)
`
I am new to django, my question is simple. How can I add two form in the same page? I tried many things as making a class in views or add a second urls path but didn't find how. Thanks you for helping
this is my code:
forms.py
class scrap_info(forms.Form):
url = forms.CharField(label="Urls")
website = forms.ChoiceField(label="Website", choices=ask_website)
class sms_info(forms.Form):
data = forms.ChoiceField(label="Data list", choices=ask_data)
number = forms.CharField(label="Sms number")
views.py
def scrap_app(request):
form1 = scrap_info(request.POST or None)
return render(request, "sms/scrap_app.html", {'form1': form1})
def sms_app(request):
form2 = sms_info(request.POST or None)
return render(request, "sms/sms_app.html", {"form2": form2})
scrap_app.html
<body>
<div>
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-outline-info" type="submit" value="Save">SCRAP</button>
</form>
</div>
</body>
urls.py
urlpatterns = [
path("/scrap_app", views.scrap_app, name="scrap_app"),
]
I have encountered this problem just recently and I solved it by adding a hidden field on every form and getting that hidden value to determine what form was submitted by using an if condition in views
Here's how I did it using CBV.
views.py
class ContactUsView(TemplateView):
template_name = 'yourtemplate.html'
def get(self, request, *args, **kwargs):
inquiry_form = InquiryForm(self.request.GET or None, prefix='inquiry_form')
complaint_form = ComplaintForm(self.request.GET or None, prefix='complaint_form')
context = self.get_context_data(**kwargs)
context['complaint_form'] = complaint_form
context['inquiry_form'] = inquiry_form
return self.render_to_response(context)
def post(self, request):
# instantiate all unique forms (using prefix) as unbound
inquiry_form = InquiryForm(prefix='inquiry_form')
complaint_form = ComplaintForm(prefix='complaint_form')
# determine which form is submitting (based on hidden input called 'action')
action = self.request.POST['action']
# bind to POST and process the correct form
if action == 'inquiry':
inquiry_form = InquiryForm(data=request.POST, prefix='inquiry_form')
if inquiry_form.is_valid():
# Your logic here
return self.render_to_response(
self.get_context_data(
inquiry_form=inquiry_form,
complaint_form=complaint_form,
)
)
messages.error(self.request,
'Inquiry form is invalid.')
elif action == 'complaint':
complaint_form = ComplaintForm(data=request.POST, prefix='complaint_form')
if complaint_form.is_valid():
# Your logic here
return self.render_to_response(
self.get_context_data(
inquiry_form=inquiry_form,
complaint_form=complaint_form,
)
)
messages.error(self.request,
'Complaint form is invalid.')
# prep context
context = {
'inquiry_form': inquiry_form,
'complaint_form': complaint_form,
}
return render(request, self.template_name, context)
yourtemplate.html
<!-- First Form -->
<form action="" method="post" role="form">
{% csrf_token %}
<input type='hidden' name='action' value='inquiry'>
{{ form1 }}
<button type="submit" title="Send Inquiry">Send Inquiry</button>
</form>
<!-- Second Form -->
<form action="" method="post" role="form">
{% csrf_token %}
<input type='hidden' name='action' value='complaint'>
{{ form2 }}
<button type="submit" title="Send Complaint">Send Complaint</button>
</form>
As you can see there's a hidden value in every form named 'action', that will be the one to determine which form was submitted.