Django form not visible - python

Only the button is visible and headings are visible cannot see CharField
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
index.htm
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>

You should give the if form.is_valid() part, one more tab.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})

I'm not yet allowed to add comments to your question, but you did notice, that your view renders name.html while you're providing the code for index.htm.
Basically your code seems valid, while it can be further optimized:
def get_name(request):
form = NameForm(request.POST or None)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
return render(request, 'name.html', {'form': form})

<form action="/your-name/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
This should work by adding editing {{form.as_p}}

Related

Django Form Fields won't show in my template

The form field won't show up in the browser. There is only the submit button showing up.
views.py code:
def vote(request, pk):
# check if request is post
if request.method == 'POST':
# create a form and populate it with data from request
form = forms.Vote(request.POST)
if form.is_valid():
fact = Fact.objects.get(pk=pk)
fact.votes += int(form.cleaned_data['vote'])
fact.save()
return HttpResponseRedirect(reverse(
'facts:detail',
args=(pk,)
))
else:
form = forms.Vote()
return render(request, 'facts/fact_detail.html', {'form': form})
template(fact_detail.html) code:
<form method='POST'>
{% csrf_token %}
{{ form }}
<input type="submit" value="vote" />
</form>
Form class(forms.py) code:
VOTE_CHOICES = [
(1, 'upvote'),
(0, 'downvote')
]
class Vote(forms.Form):
vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect())
In views.py for the vote method initialize the form variable locally, before passing it as a parameter.
def vote(request, pk):
form=""
//rest of the code//
return render(request, 'facts/fact_detail.html', {'form': form})
I recommend check generic editing views from django documentation I think it has the solution
[ https://docs.djangoproject.com/en/1.11/ref/class-based-views/generic-editing/#createview][1]

render two views to a single html template

I have two views and I want to render those views to a single HTML page. I know how to render a single view to an HTML page but don't know how to render two views to a single HTML page.
views.py file
from django.shortcuts import render
from django.http import HttpResponse
from app.models import *
# Create your views here.
def collegeview(request):
if request.method == 'POST':
form = collegeform(requst.POST)
if form.is_valid():
form.save()
return HttpResponse('its done here')
else:
form = collegeform()
return render(request, 'about.html', {'form':form})
def schoolview(request):
if request.method == 'POST':
f = schoolform(requst.POST)
if f.is_valid():
f.save()
return HttpResponse('its done here')
else:
f = schoolform()
return render(request, 'about.html', {'f':f})
about.html
<html>
<body>
<h1>its working </h1>
first view <br>
<form action ='' method = 'POST'> {% csrf_token %}
{{form.as_p}}
<input type='submit' name='submit'>
</form>
2nd view<br>
<form action='' method='POST'> {% csrf_token %}
{{f.as_p}}
<input type='submit' name='submit'>
</form>
</body
</html>
single view working corresponding to the URL.
Not possible to render two different views to the same template, but you can add both the logics in a single view and then render both forms in that:
from django.shortcuts import render
from django.http import HttpResponse
from app.models import *
def institute_view(request):
f = schoolform(requst.POST or None)
form = collegeform(requst.POST or None)
if request.method == 'POST':
if form.is_valid():
form.save()
return HttpResponse('its done here')
elif f.is_valid():
f.save()
return HttpResponse('its done here')
else:
f = schoolform()
form = collegeform()
return render(request, 'about.html', {'f':f,'form':form})
By this method, both of your forms can be handled and whenever anyone of them gets posted the values will be saved accordingly.

How to save a data after user logs in DJANGO

After user logs in, user is able to submit a form. On click of submit button, data is being stored in DB, but how should I connect this information to the submitting user.
I would need the code as well as the structure of the new db
Kind of starting out in django.
Any help would be appreciated!!!
I have included user as foreign key in the CustomizeRequest model, but now how do i fill in this information?
Exact Scenario: After user log in, once he comes to contactUs.html, he submits a form which tells the number of travellers. This number is being stored in the DB. But now how do I connect each of these numbers to the submitted user?
models.py
class CustomizeRequest(models.Model):
user = models.ForeignKey(User)
travellers = models.CharField(max_length=2)
def __str__(self):
return self.travellers
contactUs.html
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="btn-group" data-toggle="buttons">
{% for radio in crform.travellers %}
<label class="btn btn-default {% if radio.choice_label = '1' %}active{% endif %}" for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
{{ radio.tag }}
</label>
{% endfor %}
</div>
<button type="submit" class="btn btn-default btn-block btn-warning">SUBMIT</button>
</form>
views.py
def contactUs(request):
if request.method=="POST":
form = CustomizeRequestForm(request.POST)
form.save()
else:
form = CustomizeRequestForm()
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
Based on catavaran answer (with a check to see if the form is valid):
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
#login_required
def contactUs(request):
form = CustomizeRequestForm(data=request.POST or None)
if request.method == "POST":
if form.is_valid():
customize_request = form.save(commit=False)
customize_request.user = request.user
customize_request.save()
return redirect('.')
else:
pass # could add a notification here
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
Logged user is available as request.user property. You can get the unsaved model instance using form.save(commit=False) trick, set the user field and then save the instance to database:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
#login_required
def contactUs(request):
if request.method == "POST":
form = CustomizeRequestForm(request.POST)
if form.is_valid():
customize_request = form.save(commit=False)
customize_request.user = request.user
customize_request.save()
return redirect('.')
else:
form = CustomizeRequestForm()
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)

Uploading csv file from url using django forms

So I am trying to upload and save a csv file to a variable via a POST to a url. I have looked through the django documentation on file uploads found here. I just don't understand the use of a form? What's the purpose in this situation?
They use an example with a form:
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
Upload html:
<form enctype="multipart/form-data" action="/upload/" name="test" method="post">
<input id="file" type="file" name="test" />
<input id="signUpSubmit" type="submit" value="Submit">
</form>
models.py
from django.db import models
class Upload(models.Model):
name = models.CharField(max_length=100)
file = models.FileField(upload_to="images")
forms.py
from django import forms
from app_name.models import Upload
class UploadForm(forms.ModelForm):
class Meta:
model = Upload
views.py
def upload_file(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
upload.html
<form enctype="multipart/form-data" action="/upload/" name="test" method="post">
{% csrf_token %}
{{form.as_p}}
<input id="signUpSubmit" type="submit" value="Submit">
</form>

form.save() not saving

For some reason, I can't get form.save() to save to my database. I'm able to create the form, and have the form pass itself off to my template, but nothing is getting saved to the database. I've mucked around with it for many hours and haven't been able to get it to work.
Any help is appreciated.
Here is the relevant code..
This is my add/model.py
from django.db import models
from django.forms import ModelForm
class addTask(models.Model):
task = models.CharField('Task', max_length=60)
taskNotes = models.CharField('Notes', max_length=600)
def __unicode__(self):
return self.task
class addTaskForm(ModelForm):
class Meta:
model = addTask
template/addTHEtask.html. This is getting referenced correctly.
<form action="/todo/" method="post">
{{ form.as_p }}
<input type="submit" value="Add Task" />
</form>
add/views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from myToDo.add.models import addTask, addTaskForm
def create_task(request):
if request.method == 'POST':
form = addTaskForm(request.POST)
if form.is_valid():
form.save()
else:
form = addTaskForm()
return render_to_response('addTHEtask.html', {'form': form})
To properly debug your code, change your template to:
<form action="/todo/" method="post"> {{ csrf_token }}
{{ form.errors }}
{{ form.as_p }}
<input type="submit" value="Add Task" />
</form>
And your view to:
def create_task(request):
if request.method == 'POST':
form = addTaskForm(request.POST)
if form.is_valid():
form.save()
else:
form = addTaskForm()
return render_to_response(
'addTHEtask.html',
{'form': form},
context_instance=RequestContext(request))
I don't think the context_instance will do anything significant for you, but it is usually the right thing to pass when using render_to_response.
Showing the errors in the form may help you track down what the actual problem is. Your code looks (mostly) correct, except the missing csrf_token. Adding the token, and displaying any errors, should show you what is going wrong.

Categories