Goal: to create a question where a user creates a poll question that is "mad-libs" style (i.e. "Would you fool around with _(text)__ if she wasnt dating _(text)_?").
Code: This file creates a django form corresponding to an appengine entity.
from django import newforms as forms
import models
from google.appengine.ext.db import djangoforms
class PollForm(djangoforms.ModelForm):
class Meta:
model = models.Poll
This is an excerpt from the models.py file
from google.appengine.ext import db
from django import newforms as forms
class Poll(db.Model):
question = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add = 1)
created_by = db.UserProperty()
def __str__(self):
return '%s' %self.question
def get_absolute_url(self):
return '/poll/%s/' % self.key()
here is the html for this section
<form action="." method="post">
{{pollform.as_p}}
{% for form in choiceforms %}
{{form.as_p}}
{% endfor %}
<input type="submit" name="createpoll" value="createpoll" />
</form>
Is there a fairly straightforward way to create a question like this with some pre-coded text and some input text? Can I harcode it in the HTML?
Any direction is greatly appreciated!
I still don't totally understand your question. If you post your full source and an example of the result you are trying to get, then you will get a better response.
Here's an example of constructing a form for someone to answer the question. I hard coded the question, but you could easily retrieve that dynamically.
class Answer(models.Model):
answer1 = models.CharField(max_length=100)
answer2 = models.CharField(max_length=100)
class AnswerForm(forms.ModelForm):
class Meta:
model = Answer
def test(request):
if request.method == 'GET':
form = AnswerForm()
question_template = 'Would you fool around with %s if she wasn\'t dating %s?'
html = question_template % (form['answer1'], form['answer2'])
params = {'form': form,
'html': html}
return render_to_response('test.html',
params,
context_instance=RequestContext(request))
Template:
<form method="post" action="">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{{ html|safe }}
<input type="submit" value="Save"/>
</form>
Related
views.py
def registerPage(request):
form = UserCreateForm()
if request.method=='POST':
form=UserCreateForm(request.POST)
if form.is_valid():
user=form.save(commit=False)
user.save()
return redirect('home')
return render(request,'base/signup.html',{'form':form})
model.py
class User(AbstractUser):
name = models.CharField(max_length=200,null=True)
email = models.EmailField(unique=True,null=True)
bio=models.TextField(null=True)
avatar = models.ImageField(upload_to='images/',null=True)
USERNAME_FIELD='email'
REQUIRED_FIELDS=['username']
forms.py
class UserCreateForm(UserCreationForm):
class Meta:
model = User
fields = ['name','email','password1','password2','bio','avatar']
htmltemplate
{% include 'main.html' %}
{% block content %}
<div>
<form method="POST">
{% csrf_token %}
{% for field in form %}
{{field.label}}
{{field}}
{% endfor %}
<input type="submit" value="Register" >
</form>
</div>
{% endblock content %}
when ever i try to sign up on html template it doesnt work but if i do it in admin panel it works how can i solve it ?
First of all, it is generally not recommended to mess with the default User model from django. Its better to create a Profile model with a OneToOneField relationship with the user.
Other than that, your issue lies with your form. Since you have avatar which is an ImageField you need to change your form in a way that it can accept FILES.
So what you need to do is change your form like this:
<form method="post" action="" enctype="multipart/form-data" >
When you are writing client-side code:
use multipart/form-data when your form includes any <input type="file"> elements.
In order to make your POST request valid, you need to also receive your FILES on your view. That can be done by changing your code to:
if request.method=='POST':
form=UserCreateForm(request.POST, request.FILES)
if form.is_valid():
....
I am looking to create a dropdown in a template where the values of the dropdown come from a field (reference) within my Orders model in models.py. I understand creating a dropdown where the values are set statically, but since I am looking to populate with values stored in the DB, I'm unsure of where to start.
I've created the model and attempted playing around with views.py, forms.py and templates. I am able to get each of the order numbers to display but not in a dropdown and I am struggling with how to write my template.
models.py
from django.db import models
class Orders(models.Model):
reference = models.CharField(max_length=50, blank=False)
ultimate_consignee = models.CharField(max_length=500)
ship_to = models.CharField(max_length=500)
def _str_(self):
return self.reference
forms.py
from django import forms
from .models import *
def references():
list_of_references = []
querySet = Orders.objects.all()
for orders in querySet:
list_of_references.append(orders.reference)
return list_of_references
class DropDownMenuReferences(forms.Form):
reference = forms.ChoiceField(choices=[(x) for x in references()])
views.py
def reference_view(request):
if request.method == "POST":
form = references(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = references()
return render(request, 'proforma_select.html', {'form': form})
proforma_select.html
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label"> {{ field.label }}</label>
<div class="col-10">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary" name="button">Add Order</button>
</form>
</div>
{% endblock %}
All I get when I render the template is each of the reference #s listed out but NOT within a dropdown. This leads me to believe my problem is mainly with the template, but I'm unsure as I am new to using Django.
Are you using Materialize CSS? If yes, then Django forms renders dropdowns differently from how Materialize expects them. So you will want to override the form widget. You can do something like so:
forms.py:
class DropDownMenuReferences(forms.Form):
reference = forms.ChoiceField(choices=[(x) for x in references()],
widget=forms.Select(choices=[(x) for x in references()], attrs={'class':
'browser-default'}))
This overrides the parameters passed into html. You can also pass any name tags in the attrs too.
The issue:
https://github.com/Dogfalo/materialize/issues/4904
I use smart_selects to realize secondary linkage in Django admin page. Succeed! When I choose one university, only the colleges those belong to the university can be chosen.
But, when it comes to the form in webpage, the second level form cannot display any option.This is the wrong webpage:
Here are the codes:
models.py
class StudentModel(models.Model):
GENDER_CHOICES = (('M','男'),('F','女'),)
name = models.CharField(verbose_name='姓名',max_length=20)
gender = models.CharField(blank = True,max_length=4,choices = GENDER_CHOICES,verbose_name='性别')
date_of_birth = models.DateField(verbose_name='出生日期',blank=True,null=True)
age = models.IntegerField(verbose_name='年龄',default=0)
highschool = models.ForeignKey(SeniorHighSchoolModel,verbose_name='高中名称')
university = models.ForeignKey(UniversityModel,verbose_name='大学名称')
college = ChainedForeignKey(CollegeModel,chained_field='university',chained_model_field='university',show_all=False,blank=True,null=True,verbose_name='学院名称')
def __str__(self):
return self.name
forms.py
from django import forms
from .models import StudentModel
class LoggingForm(forms.ModelForm):
class Meta:
model = StudentModel
fields=['name','gender','date_of_birth','age','highschool','university','college']
logging.html
<form action="" method="POST">
{% csrf_token %}
{{form.as_p}}
<input type='submit' />
I found an resolution,just add {{form.media.js}} in logging.html.
<form action="" method="POST">
{% csrf_token %}
**{{form.media.js}}**
{{form.as_p}}
<input type='submit' />
<a>You will recieve an email from us.</a>
</form>
The answer is found in this question:
How to use django smart-selects with modelform?
Thanks for the edition from Donald Duck.
I am building a web application on django. As part of this, I have created one html form like following:
<form method="post" action="/voting/add_state/">{% csrf_token %}
State name:<br>
<input type="text" name="state_name"><br>
<input type="submit" value="Submit">
</form>
In models.py I have added unique constraint validation on name like following:
class State(models.Model):
name = models.CharField(max_length=200, unique=True)
vote_counted = models.BooleanField(default=False)
So for duplicate name, it throws a unique constraint error which I would like to capture in the template. Can anyone please give any suggestion.
Create a form based on your model
#forms.py
from django import forms
from .models import State
class StateForm(forms.ModelForm):
class Meta:
model = State
fields = ('name',)
now use this form on your views
#views.py
from django.views.generic import FormView
from .forms import StateForm
class MyView(FormView):
template_name = 'template.html'
form_class = StateForm
success_url = '/my-url-to-redirect-after-submit/'
template.html
<form method="post">
{% csrf_token %}
Name
{{ form.name }}
{{ form.name.errors }}
<input type="submit" value="Create">
</form>
Django has Form processing built in. Django has "Model Forms", which automatically render the form for your model. If you pass it through the view and reference it in the context it will automatically generate the html for you, but if you would like more control over what is rendered in the template then you can reference the form attributes that Django Model Form produces.
I strongly suggest working within the framework Django provides to you for building forms; it provides a lot of boilerplate code for building, validating and abstracting forms and is especially competent for simple forms like these.
Here is an example:
models.py
class State(models.Model):
name = models.CharField(max_length=200, unique=True)
vote_counted = models.BooleanField(default=False)
forms.py
class StateForm(forms.ModelForm):
model = State
fields = (name,)
views.py
from django.views.generic.edit import FormView
class StateForm(FormView):
template_name = 'state_form.html'
form_class = StateForm
success_url = '/thanks/'
state_form.html (example of auto generated form)
{{ form }}
state_form.html (example of custom form)
<form action="/" method="post">
{% csrf_token %}
{{ form.errors }}
{% for field in form %}
<input type="{{ field.type }}" name='{{ field.name }}' class="submit" value="{{ field.value}}">
{% endfor %}
<input type="submit" name='submit" value="Submit">
</form>
References:
Django Forms:
https://docs.djangoproject.com/en/1.9/topics/forms/
Django Model Forms: https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/
Django Generic Views:
https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-editing/#django.views.generic.edit.FormView
You could create a form for State model and create the validator, so if the user try with a duplicate name, the form raise a message something like this:
models.py
class State(models.Model):
name = models.CharField(max_length=200, unique=True)
vote_counted = models.BooleanField(default=False)
forms.py
def unique_name(value):
exist = State.objects.filter(name=value)
if exist:
raise ValidationError(u"A state with the name %s already exist" % value)
class StateForm(forms.Form):
name = forms.CharField(label=('Name:'), validators=[unique_name])
Then you just need to render the StateForm in the template.
So I want to create a super basic form with a single input field which will be used to query my database.
My model (models.py) is as follows:
from django.db import models
class Book(models.Model):
uid = models.IntegerField(primary_key=True)
title = models.CharField(max_length=30)
class Meta:
db_table = u'books'
forms.py:
from django import forms
from myapp.models import Book
class EnterIDForm(forms.form):
book_id = forms.CharField()
# add a custom clean function to validate that the user input
# is a valid book ID
def clean_book_id(self):
try:
book_id = int(self.cleaned_data["book_id"])
except:
book_id = None
if book_id and Book.objects.filter(uid=book_id).count():
return book_id
else:
raise forms.ValidationError("Please enter a valid book ID number.")
views.py:
from django.shortcuts import render_to_response
from myapp.models import Book
def form_view(request):
if request.method == "POST":
# the user has submitted the form, see if we have a book
book_id_form = EnterIDForm(request.POST) # instantiate our form class with the user data
if book_id_form.is_valid():
# if our form is valid, then we have a book_id that works:
the_book = Book.objects.get(uid=book_id_form.cleaned_data["book_id"])
return render_to_response("book_template.html", { "the_book": the_book }, context_instance=RequestContext(request))
# if the form wasn't valid, it will fall through to the other return statement.
else:
# If the user didn't submit a form, instantiate a blank one.
book_id_form = EnterIDForm()
return render_to_response("form_template.html", { "book_id_form": book_id_form }, context_instance=RequestContext(request))
I want the input field to collect the "uid" from the user and display the all of the data from the Book model instance where uid is some book in the database.
I have an understanding of how the form is tied in with the view, and later templates, but I just cannot seem to get it to work.
I've endlessly searched the Django site and many other resources for an example I can learn from, but nothing.
Anyone mind helping me out?
Thanks.
You can do a simple search here. You do not need any POST calls or form creation. However, if you want to create a form this should still point you in the correct direction.
Try something like this:
search.html:
<form method="get" action="/search/">
Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
views.py:
from myapp.models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
def search(request):
query = request.GET.get('q')
try:
query = int(query)
except ValueError:
query = None
results = None
if query:
results = Book.objects.get(uid=query)
context = RequestContext(request)
return render_to_response('results.html', {"results": results,}, context_instance=context)
results.html:
{% if results %}
{% for result in results %}
{{ result.uid }}
{{ result.xxxx }}
{{ result.xxxx }}
{% endfor %}
{% else %}
<h3 class='error'>Please enter a valid UID</h3>
<form method="get" action="/search/">
Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
{% endif %}