I use the length tag in my template to count the number of items in my drop down list. The length is well displayed the first time the form is rendered. When the form is submitted and when the length has changed, the value is not updated but the drop down list is updated! Why? :(
In forms.py:
lawsToValidate=forms.ModelChoiceField(queryset=LawsIdsModel.objects.filter(validated=0), empty_label="Select a law to validate", widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
In my template:
{{ form.lawsToValidate.field.choices|length }}
<form id="lawsIdsForm" action="{% url lawsValidation.views.lawsView %}" method="post">{% csrf_token %}
{{ form.non_field_errors }}
{{ form.lawsToValidate.field.choices|length }} laws to validate!
<div id="lawsToValidateChoice" class="fieldWrapper">
{{ form.lawsToValidate.errors }}
{{ form.lawsToValidate }}
</div>
</form>
In views.py:
def lawsView(request):
responseDic={}
state="display"
if request.method == 'POST':
lawToValidate=request.POST.getlist('lawsToValidate')[0]
#if a law is selected
if lawToValidate!="":
law=LawsIdsModel.objects.get(id=lawToValidate)
#saves the law
if 'lawsValidationSaveButton' in request.POST:
law.validated=True
form = LawsIdsForm(request.POST, instance=law)
if form.is_valid():
form.save()
del form
state="saved"
responseDic['success']="The law releveAnnee=" + str(law.releveAnnee) + ", releveMois=" + str(law.releveMois) + ", noOrdre=" + str(law.noOrdre) + " has been validated!"
else:
state="ongoing"
#displays the retrieved information of the law to validate (selection of a law in the drop down list)
if state!="saved":
#a law has been selected in the drop down list -> the related information are displayed
if state=="display":
form = LawsIdsForm(instance=law, initial={'lawsToValidate': lawToValidate, 'releveAnnee': law.releveAnnee, 'releveMois': law.releveMois, 'noOrdre': law.noOrdre})
#an error occured while validating the law -> display of these errors
elif state=="ongoing":
form = LawsIdsForm(request.POST, instance=law, initial={'lawsToValidate': lawToValidate, 'releveAnnee': law.releveAnnee, 'releveMois': law.releveMois, 'noOrdre': law.noOrdre})
responseDic['form']=form
responseDic['law']=law
#~ #if form has not been created yet -> unbound form
if 'form' not in locals():
responseDic['form'] = LawsIdsForm()
return render_to_response('lawsValidation/index.html', responseDic, context_instance=RequestContext(request))
Thank you in advance,
Romain
I think you've come across issue 18066. It's been closed as 'needs info', but it looks like a bug to me.
As a work around, try
{{ form.lawsToValidate.field.choices.queryset.all|length }}
Related
Depending on the arguments I pass to the form I want to return different form fields.
class TestForm(FlaskForm):
"""Test Form."""
if one:
field1 = StringField('Field 1')
if two:
field2 = StringField("Field 2")
if three:
field3 = StringField("Field 3")
submit = SubmitField("Add Service")
def __init__(self, one=None, two=None, three=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.one = one
self.two = two
self.three = three
I am not able to see the arguments when doing the if statements.
I am aware of the option to have logic in html when rendering the form, however due the nature of the project have opted to use quick_form on the html side.
Here is the html code I am using.
{% import 'bootstrap/wtf.html' as wtf %}
<h3 >Add Service</h3>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
Instead of creating this logic in your form class. I would recommend to create all the fields you need and then dynamically choose which to show the user using jinja2 in your html file.
Here's an example.
{% for fields in fields_list %}
{% if field == '1' %}
{{ form.field1.label(class="form-control-label") }}
{{ form.field1(class="form-control form-control-lg") }}
{% endif %}
{% if field == '2' %}
{{ form.field2.label(class="form-control-label") }}
{{ form.field2(class="form-control form-control-lg") }}
{% endif %}
{% if field == '3' %}
{{ form.field3.label(class="form-control-label") }}
{{ form.field3(class="form-control form-control-lg") }}
{% endif %}
{% endfor %}
And then when you render or redirect to your .html from your routes code, don't forget to send
the proper arguments, such as
# create your fields list, which do I want to show?
# Make it a list of integers
fields_list = [1, 2, 3]
return render_template('insert-name.html', fields_list , form=form)
If my answer helped you, please consider accepting my answer.
I am new to this site and trying to build up some reputation :)
Thank you! Happy Coding!
If someone ever comes accross the same question, here is a quick solution I came upon some times ago.
It is in part inspired from the accepted answer here.
In your forms.py or wherever you declare your TestForm class, put the class declaration inside a function that takes your parameter as an argument and returns the class object as output.
The argument will now be accessible within the class itself, allowing for any test you may want to perform.
Here's a working example based on your original question (I just added a default value to get at least one StringField in case the parameter is ommited):
def create_test_form(var='one'):
class TestForm(FlaskForm):
"""Test Form."""
if var == 'one':
field1 = StringField('Field 1')
if var == 'two':
field2 = StringField("Field 2")
if var == 'three':
field3 = StringField("Field 3")
submit = SubmitField("Add Service")
return TestForm()
Then simply create the form in your routes like so:
form = create_test_form('two')
Finally pass it to your HTML to render the form with quick_form like you did.
This example will render a form with a single StringField named "Field 2" and a "Add Service" submit button.
I am creating a multi-choice quiz app, I have created a view which shows the question and 4 option. I have given radio button to each option but is giving me this error:
MultiValueDictKeyError at /quiz/2/11/ 'choice'
views.py
def question_detail(request,question_id,quiz_id):
q = Quiz.objects.get(pk=quiz_id)
que = Question.objects.get(pk=question_id)
ans = que.answer_set.all()
selected_choice = que.answer_set.get(pk=request.POST['choice'])
if selected_choice is True:
come = que.rank
came = come + 1
later_question = q.question_set.get(rank=came)
return render(request,'app/question_detail.html',{'que':que , 'later_question':later_question, 'ans':ans})
else:
come = que.rank
later_question = q.question_set.get(rank=come)
return render(request, 'app/question_detail.html', {'que': que, 'later_question': later_question, 'ans': ans})
question_detail.html
<form action="{% 'app:detail' quiz_id=quiz.id question_id=que.id %}" method="post">
{% csrf_token %}
{% for choice in que.answer_set.all %}
<input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}">
<label for="choice{{forloop.counter}}">{{choice.answer}}</label>
{% endfor %}
</form>
Okay like I said in my comment, you're most likely getting that error because the POST object will be empty during a normal GET request. So you should wrap everything that's meant to happen after a request in an IF block:
if request.method === 'POST':
selected_choice = que.answer_set.get(pk=request.POST['choice'])
# Every other post-submit task
You should always check for the POST method in your views if you're expecting form data. Others have answered this more in-depth before so I would just direct you there:
What does request.method == "POST" mean in Django?
I'm working on my first django project which is a sport betting app. My models are:
class Game(models.Model):
home_team = models.CharField(max_length=100)
away_team = models.CharField(max_length=100)
class GameBet(models.Model):
gameid = models.ForeignKey(Game)
bet = models.IntegerField(default=None) #values: 1(home win), 0 (draw), 2 (away win)
userid = models.ForeignKey(User)
I am able to save user bets using a single game view, when I pass gameid in url, but that is not very effective.
I created a simple page with list of games with 1 form per game for a start (at the end I would prefer to send all bets with one button):
{% for game in games %}
{{ game.id }} | {{ game.home_team }} | {{ game.away_team }} | <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="bet" /> </form> <br> {% endfor %}
and my form is:
if request.method == 'POST':
#if request.POST["bet"] == 'bet':
form = NewBetForm(request.POST)
if form.is_valid():
bet = form.save(commit=False)
bet.gameid = [r.id for r in owing_games] #it gives me a list and ValueError Cannot assign "[10, 11, 12]": "GameBet.gameid" must be a "Game" instance.
bet.userid_id = current_user.id
bet.bet = form.value()
bet.save()
How can I pass a single game.id in that case?
EDIT:
I think I can use request.POST.get(something) but I don't know how to pass my {{ game.id }} from template to views
Create a hidden input field with value as game.id.
Example:
<input type='hidden' value='{{ game.id }}' name='game_id'>
Place the above html code within the form block. Now, you can access the value in the view as request.POST['game_id'].
And, if you want to place same bet for multiple game ids, then loop over game ids, retrieve the Game instance from database and assign each new GameBet instance gameid as the retrieved Game instance.
Single Game ID Example:
game_id = request.POST['game_id']
if request.method == 'POST':
# rest of the code
if form.is_valid():
bet.game_id = Game.objects.get(id=game_id)
Multiple Game IDs Example:
game_ids = request.POST['game_ids']
if request.method == 'POST':
for game_id in game_ids:
bet = form.save(commit=False)
bet.game_id = Game.objects.get(id=game_id)
bet.save()
# return response after loop
I have a model in Django that allows blanks for two date fields:
class ReleaseStream(models.Model):
name = models.CharField(max_length=200,db_column='name')
version = models.CharField(max_length=20,blank=True,db_column='version')
target_date = models.DateTimeField(null=True,blank=True,db_column='target_date')
actual_date = models.DateTimeField(null=True,blank=True,db_column='actual_date')
description = models.TextField(db_column='description')
...and a form definition:
class ReleaseStreamForm(ModelForm):
class Meta:
model = ReleaseStream
When the form comes up, I can fill in a value for the "target_date", and not for the "actual_date" fields, and when the form.save() fires it appears to write the value supplied for "target_date" into both fields. I have looked at the post data going into the code that does the form.save() and it definitely has a value for "target_date" and a '' for "actual_date", so I don't think that there is something weird with the form itself, variable names in the POST, etc.
Now, if I supply a non-blank value for "actual_date", the form.save() does the right thing - both the "target_date" and "actual_date" have the correct values written in. Am I doing something wrong, or is this potentially a bug in django?
Here is the template (sorry for the blank comment below:)
{% extends "base.html" %}
{% block title %}{{ form_title }}{% endblock %}
{% block subtitle %}{% endblock %}
{% block content %}
<form action={{ action_url }} method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit" />
</form>
{% endblock %}
And the code that handles the form:
def edit_release_stream(request,req_release_stream_id=None):
form_title = 'Edit release stream'
if request.method == 'POST':
if req_release_stream_id!=None:
release_stream_entry=ReleaseStream.objects.get(pk=req_release_stream_id)
form = ReleaseStreamForm(request.POST,instance=release_stream_entry)
else:
form = ReleaseStreamForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/releases/')
elif req_release_stream_id!=None:
release_stream_entry=ReleaseStream.objects.get(pk=req_release_stream_id)
form = ReleaseStreamForm(instance=release_stream_entry)
else:
form_title = 'Add new release stream'
form = ReleaseStreamForm()
return render_to_response('dashboard/tableform.html', {
'action_url': request.get_full_path(),
'form_title': form_title,
'form': form,
})
... And the post data coming in:
<QueryDict: {u'name': [u'NewRelease'], u'target_date': [u'2011-06-15 00:00'], u'version': [u'4.5.1'], u'actual_date': [u''], u'description': [u'']}>
You can see that it has a valid POST var of "actual_date", with an empty string. This post yields a form.save() that stores the string provided above for "target_date" for both "target_date" and "actual_date".
If I then run a post with differing values for the two dates - here is the post:
<QueryDict: {u'name': [u'NewRelease'], u'target_date': [u'2011-06-15 00:00'], u'version': [u'4.5.1'], u'actual_date': [u'2011-07-15 00:00'], u'description': [u'']}>
In this case, with two distinct, non-empty strings, it writes the correct value shown in the POST above into each of the fields in the db.
I don't believe it to be a bug in Django, or somebody would have seen this problem a long time ago. Can you show us the template that renders the form? Also, if you can show the contents of the request.POST, that'd also be useful.
I'm guessing that your template code is incorrect somehow. The only other problem I can think of would be custom validation in your form (if there is any). Is that the whole ModelForm definition that you've supplied?
I'm new to Django and I'm creating an app to create and display employee data for my company.
Currently the model, new employee form, employee table display, login/logout, all works. I am working on editing the current listings.
I have hover on row links to pass the pk (employeeid) over the url and the form is populating correctly- except the manytomanyfields are not populating, and the pk is incrementing, resulting in a duplicate entry (other than any data changes made).
I will only put in sample of the code because the model/form has 35 total fields which makes for very long code the way i did the form fields manually (to achieve a prettier format).
#view.py #SEE EDIT BELOW FOR CORRECT METHOD
#login_required
def employee_details(request, empid): #empid passed through URL/link
obj_list = Employee.objects.all()
e = Employee.objects.filter(pk=int(empid)).values()[0]
form = EmployeeForm(e)
context_instance=RequestContext(request) #I seem to always need this for {%extend "base.html" %} to work correctly
return render_to_response('employee_create.html', locals(), context_instance,)
#URLconf
(r'^employee/(?P<empid>\d+)/$', employee_details),
# snippets of employee_create.html. The same template used for create and update/edit, may be a source of problems, they do have different views- just render to same template to stay DRY, but could add an additional layer of extend for differences needed between the new and edit requests EDIT: added a 3rd layer of templates to solve this "problem". not shown in code here- easy enough to add another child template
{% extends "base.html" %}
{% block title %}New Entry{% endblock %}
{% block content %}
<div id="employeeform">
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="/newemp/" method="post" class="employeeform">{% csrf_token %} #SEE EDIT
<div class="left_field">
{{ form.employeeid.value }}
{{ form.currentemployee.errors }}
<label for="currentemployee" >Current Employee?</label>
{{ form.currentemployee }}<br/><br/>
{{ form.employer.errors }}
<label for="employer" class="fixedwidth">Employer:</label>
{{ form.employer }}<br/>
{{ form.last_name.errors }}
<label for="last_name" class="fixedwidth">Last Name:</label>
{{ form.last_name }}<br/>
{{ form.facility.errors }} #ManyToMany
<label for="facility" class="fixedwidth">Facility:</label>
{{ form.facility }}<br/><br/>
</div>
<div id="submit"><br/>
<input type="submit" value="Submit">
</div>
</form>
#models.py
class Employee(models.Model):
employeeid = models.AutoField(primary_key=True, verbose_name='Employee ID #')
currentemployee = models.BooleanField(null=False, blank=True, verbose_name='Current Employee?')
employer = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
facility = models.ForeignKey(Facility, null=True, blank=True)
base.html just has a header on top, a menu on the left and a big empty div where the forms, employee tables, etc all extend into.
screenshot2
So, how do I need to change my view and/or the in the template to update an entry, rather than creating a new one? (
And how do I populate the correct foriegnkeys? (the drop down boxes have the right options available, but the "-----" is selected even though the original database entry contains the right information.
Let me know if i need to include some more files/code
I have more pics too but i cant link more or insert them as a new user :< I'll just have to contribute and help out other people! :D
EDIT:
I've been working on this more and haven't gotten too far. I still can't get the drop-down fields to select the values saved in the database (SQLite3).
But the main issue I'm trying to figure out is how to save as an update, rather than a new entry. save(force_update=True) is not working with the default ModelForm save parameters.
views.py
def employee_details(request, empid):
context_instance=RequestContext(request)
obj_list = Employee.objects.all()
if request.method == 'POST':
e = Employee.objects.get(pk=int(empid))
form = EmployeeForm(request.POST, instance=e)
if form.is_valid():
form.save()
return HttpResponseRedirect('/emp_submited/')
else:
e = Employee.objects.get(pk=int(empid))
form = EmployeeForm(instance=e)
return render_to_response('employee_details.html', {'form': form}, context_instance,)
also changed template form action to "" (from /newemp/ which was the correct location for my new employee tempalte, but not the update.
Thanks to this similar question.
updating a form in djnago is simple:
steps:
1. extract the previous data of the form and populate the edit form with this these details to show to user
2. get the new data from the edit form and store it into the database
step1:
getting the previous data
views.py
def edit_user_post(request, topic_id):
if request.method == 'POST':
form = UserPostForm(request.POST)
if form.is_valid():
#let user here be foreign key for the PostTopicModel
user = User.objects.get(username = request.user.username)
#now set the user for the form like: user = user
#get the other form values and post them
#eg:topic_heading = form.cleaned_data('topic_heading')
#save the details into db
#redirect
else:
#get the current post details
post_details = UserPostModel.objcets.get(id = topic_id)
data = {'topic_heading':topic.topic_heading,'topic_detail':topic.topic_detail,'topic_link':topic.topic_link,'tags':topic.tags}
#populate the edit form with previous details:
form = UserPostForm(initial = data)
return render(request,'link_to_template',{'form':form})