Django 1.6: Form not displaying in template - django

I'm trying to implement a form where I can get userinput, but for some reason the form in not showing in the template. I have two fields in the form and one of the field is a dropdown menu. The template is not showing the dropdown list.
Here is the form that I'm trying to use
TIME_CHOICES = (
(5, 'Less than 5 Minutes'),
(10, 'Less than 10 Minutes'),
(15, 'Less than 15 Minutes'),
)
class UserContentForm(forms.ModelForm):
time = forms.ChoiceField(required=True, choices = TIME_CHOICES, widget = forms.Select)
comment = forms.CharField(max_length=2000, required= False,widget=forms.TextInput())
class Meta:
model = UserContent
fields = ("time","comment")
Here is the view where I'm tyring to save the form
def addContent(request, id):
d = getVariables(request)
profile = Doctor.objects.get(id=id)
if request.user.is_authenticated():
user = request.user
ds = DoctorSeeker.objects.get(user=user)
d['doctorseeker'] = ds
doctorLiked = Like.objects.filter(doctor_id=profile.id,user_id=user.id)
d['my_doctor'] = profile.id == request.user.id
d['username'] = user.username
if doctorLiked:
d['liked'] = True
else:
d['liked'] = False
if request.method == "POST":
form = UserContentForm(request.POST)
if form.is_valid():
time = form.cleaned_data['time']
comment = form.cleaned_data['comment']
con = UserContent(time=time, comment = comment, doctor_id = profile.id, user_id = request.user.id)
con.save()
return render(request,'meddy1/docprofile.html',{'doctor': profile})
else:
form = UserContentForm()
d.update({'doctor': profile, 'UGC': UserContent.objects.all()})
return render(request, 'meddy1/usercontent.html',d)
here is the template where I'm trying to render it
<form action="" method="post" id="user_uploader" > {% csrf_token %}
<input type="hidden" name="user" value="{{ user.id }}" />
<input type="hidden" name="doctor" value="{{ doctor.id }}" />
<select class="form-control" id="s1" name="time">
<option><b>Select a Time...</b></option>
{% for value, text in form.time.field.choices %}
<option value="{{ value }}">{{ text }}</option>
{% endfor %}
</select>
<input type="text" class="form-control" id="comment" placeholder="Comment" name="comment">
<button class="btn btn-primary" type="submit" name="submit" id="ss-submit">Submit Review</button>
</form>
Here is the model
class UserContent(models.Model):
time = models.IntegerField(blank = True)
comment = models.TextField(blank = True)
doctor = models.ForeignKey(Doctor)
user = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now_add=True)

You are not passing the form variable to template. Update the line to
d.update({'doctor': profile, 'UGC': UserContent.objects.all(),
'form': form #add form variable
})
Also, instead of manually rendering select tag you can do {{ form.time }} to render it.

Related

How to get selected radio button choice in django form?

I've a form
class ScoreUpdateForm(forms.Form):
answer_id = forms.IntegerField()
given_score = forms.FloatField()
CHOICES = [('calculated_score', 'Calculated Score'),
('given_score', 'Given Score')]
final_score = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())
Here is my template
<form action="/teachers/questions/{{ answer.question.id }}/score" method="post">
{{ form.given_score }}
{{ form.final_score }}
<input type="submit" value="Submit"/>
</form>
here is my view
def score(request, pk):
if request.method == 'POST':
form = ScoreUpdateForm(request.POST)
if form.is_valid():
given_score = form.cleaned_data['given_score']
final_score = form.cleaned_data['final_score']
I can get given_score value but not the final_score. I want to get the value of the selected choice in my view after the post.
try to use
final_score = form.cleaned_data['final_score']
final_score = dict(form.fields['final_score'].choices)[final_score]

Django Saving Data into Database

I'm having an issue, what I need is to save a part number into a database table. So everytime a user enters the SOSS it should be save in my table. This is my code but is not saving anything, not sure what I'm doing wrong.
manifiestos.html
<form action="{% url 'manifiestos' %}" method="post"> {% csrf_token %}
<p><label for="date"> Date:</label> <input type="text" name="date" value={% now "Y-m-d" %} /> </p>
<p><label for="soss"> SOSS:</label> <input type="text" name="soss" id="soss" /> </p>
<input type="submit" value="Submit" />
</form>
models.py
class manifiestos_bts(models.Model):
soss = models.CharField(max_length=50)
date = models.DateTimeField(null=True, blank=True)
user = models.CharField(max_length=50)
forms.py
class ManifiestosForm(forms.Form):
soss = forms.CharField()
date = forms.DateTimeField()
user = forms.CharField()
html_views
#login_required(login_url='/msr/login')
def manifiestos(request):
if request.method == 'POST':
form = ManifiestosForm(request.POST)
if form.is_valid():
soss = request.POST.get('soss', '')
date = request.POST.get('date', '')
manifiestos_obj = manifiestos_bts(soss= soss, date= date)
manifiestos_obj.save()
return HttpResponseRedirect(reverse('manifiestos'))
else:
form = ManifiestosForm()
return render(request, 'manifiestos.html', {'form': form})
urls.py
url(r'^manifiestos$', html_views.manifiestos, name='manifiestos'),
Thanks for your time :)
If you need more details just let me know.
Your form.is_valid() will fail because you are not passing user from your template. Either remove it from ManifiestosForm or pass it from manifiestos.html

Django 1.6: Matching query does not exist

I'm trying to implement a dropdown form which filters objects depending on the selection from the dropdown. I don't have any issues doing that but it gives me an error when nothing is selected and clicked submit. I want it to not filter anything and just give the entire list of the objects but i get the following error Specialization matching query does not exist on line
spec = Specialization.objects.get(name = s_name)
Here is the template where I've the form
<form action="/doclistings/" method="GET" >
<select class="form-control" id="selection" name="selection">
<option><b>Choose a Speciality...</b></option>
{% for value, text in form.selection.field.choices %}
<option name="choicemade" value="{{ value }}">{{ text }}</option>
{% endfor %}
<!-- {% csrf_token %} -->
</select>
<span class="input-group-btn">
<button class="btn btn-primary" type="submit" name="submit" id="ss-submit">Find Doctors</button>
</span>
</form>
here is the form
MY_CHOICES = (
('Dermatologist', 'Dermatologist'),
('Dentist', 'Dentist'),
('Orthopedist', 'Orthopedist'),
('Pediatrician', 'Pediatrician'),
)
class DropdownSelectionForm(forms.Form):
selection = forms.ChoiceField(choices=MY_CHOICES, widget = forms.Select, required = False)
genderselect = forms.ChoiceField(choices=GENDER_CHOICES, widget= forms.Select, required = False)
here is the view that's rendering the dropdown form
def index(request):
d = getVariables(request,dictionary={'page_name': "Home"})
if request.method == "POST":
form = DropdownSelectionForm(request.POST)
if form.is_valid():
selection = form.cleaned_data['selection']
return HttpResponseRedirect('/doclistings')
else:
form = DropdownSelectionForm()
return render(request, 'meddy1/index.html', {'form': form})
Here is the view that's rendering the objects based on the selection
def doclistings(request):
d = getVariables(request)
if request.method == "GET":
s_name = request.GET['selection']
if s_name == "":
doctors = Doctor.objects.all().order_by('-netlikes')
else:
spec = Specialization.objects.get(name = s_name)
doctors = Doctor.objects.filter(specialization = spec).order_by('-netlikes')
else:
return HttpResponseRedirect('/doclistings')
d['doctors'] = doctors
return render_to_response('meddy1/doclistings.html',d)
This is why you should use the QueryDict methods as this:
s_name = request.GET.get('selection', None)
if not s_name:
#if s_name is None
#...
That way it will fallback correctly if s_name is not present.

Django CSRF verification failed. Request aborted

I have a model:
class Tour(models.Model):
owner_id = models.ForeignKey(User)
name = models.CharField(max_length=50)
location = models.ManyToManyField(Location)
subscribers = models.ManyToManyField(User, related_name="sub")
tour_date = models.DateField(null=True)
description = models.CharField(max_length=300, null=True)
And a template that includes this form:
<form method="post" action="/mytours/">
{% csrf_token %}
<input name="name" value="{{ name }}" class="pull-left" type="text" placeholder="Type the tour name... "></br>
<input name="tour_date" value="{{ tour_date }}" type="text" id="datepicker" placeholder="Pick a tour date..."/>
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</form>
And in my views I am trying to add to my database what is filled in the form:
if request.method == 'POST':
location = Location.objects.get(id=1)
name = request.POST.get('name', '')
tour_date = request.POST.get('tour_date', '')
tour = Tour()
tour.owner_id = user.pk
tour.name = name
tour.tour_date = tour_date
tour.location = location
tour.save()
c = {'name':name, 'tour_date':tour_date, 'tour':tour}
c.update(csrf(request))
return render_to_response("myTours.html", c)
I am new in django and I don't know where is the problem.
You're misunderstanding what to do with the CSRF token. You're creating it on POST, but the point is to create it for the original display of the form on the GET request. It is checked by the middleware on POST, so you don't need to add it there.
You should use the render call as recommended by surfeurX, but on the call that displays the form in the first place.
What I do when I implement forms in django is writing a form class and creating an instance of it in the view. Then pass the instance to the template.
# form class eg. in models.py
from django import forms
class TourForm(forms.Form):
name = forms.CharField(max_length=50)
# in the view
if request.method == 'POST':
form = TourForm(request.POST)
if form.is_valid():
# do your stuff here with form data
else:
form = TourForm() # An unbound form
return render(request, 'myTours.html', {
'form': form,
})
in your template you can display the generated form like this:
<form action="/mytours/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" class="btn btn-primary" />
</form>
for further information just look inside the official django forms documentation
You probably need to add django.middleware.csrf.CsrfViewMiddleware to MIDDLEWARE_CLASSES and add a RequestContext to your response:
return render_to_response("myTours.html", c, context_instance=RequestContext(request))
https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/
How do you render your template ??? I think your csrf_token doesn't print any hidden input, add "request" in your template context like:
return render(request, "template.html", {"var": var})
https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render

django hidden field error

i'm building a message system for a virtual community, but i can't take the userprofile id
i have in views.py
def save_message(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.sender = request.user
u = UserProfile.objects.get(request.POST['userprofile_id'])
new_obj.owner = u
new_obj.save()
return HttpResponseRedirect('.')
else:
form = MessageForm()
return render_to_response('messages/messages.html', {
'form': form,
},
context_instance=RequestContext(request))
and the template:
{% block primary %}
<form action="." method="post">
{{ form.as_p }}
<p><input type="hidden" value="{{ userprofile.id }}" name = "owner" /></p>
<p><input type="submit" value="Send Message!" /></p>
</form>
{% endblock %}
forms.py:
class MessageForm(ModelForm):
class Meta:
model = Messages
fields = ['message']
models.py:
class Messages(models.Model):
message = models.CharField(max_length = 300)
read = models.BooleanField(default=False)
owner = models.ForeignKey(UserProfile)
sender = models.ForeignKey(User)
I don't figure out why i get this error,since i'm just trying to get the profileId of a user, using a hiddeen field.
the error is:
Key 'UserProfile_id' not found in <QueryDict: {u'owner': [u''], u'message': [u'fdghjkl']}>
and i'm getting it after i fill out the message text field.
Thanks!
it should be
u = UserProfile.objects.get(request.POST['owner'])
because the input's name is 'owner!!
Can you set raise(raise Exception,request.POST) before string: u = UserProfile.objects.get(request.POST['userprofile_id'])
And show me output.