How to pre-populate Django form with part of URL? - python

I'm completely new to programming (Django), and I'm trying to pre-populate a django_messages form with a snippet of the URL.
For example, for a compose form at www.mywebsite.com/compose_root/Chris88, I want the "Recipient" field to be pre-populated with "Chris88".
Is there any way to do this? In urls.py, I have:
url(r'^compose_root/(<recipient>[\w.#+-]+)/$', compose, name='messages_compose_to'),
I already tried plugging in recipient as an initial in the "Recipient" form field, but it didn't work, so it might be easier just to pre-populate with an excerpt of the URL.
Help is much appreciated.

Assuming you have a form that looks something like:
class New_form(Form.form):
... FormStuff
recipient = Some Field
Add a view that looks like:
def compose_root(request,recipient):
...# View Stuff
form = New_form(initial={"recipient": recipient})
return render_to_response('form-template.html', {'form':form})
And in your form-template
{{form}}

Related

validating a form dynamically built in flask

I have a problem sending data in a form, which will not be the case. In the view, I build a dynamically form of agreement has some more complex models in the code is much simpler but the idea is the same.
When I complete the form, this is never processed. I really do not know what may be the problem.
code:
from wtforms import StringField,SubmitField
from flask.ext.wtf import Form
#preguntas.route('/pregunta/encuesta/', methods=['GET','POST'])
def view():
class F(Form):
pass
#building form
setattr(F,'funcion1', StringField(label='fun1'))
setattr(F,'funcion2', StringField(label='fun2'))
setattr(F,'enviar', SubmitField('enviar formulario'))
formulario = F()
if formulario.validate_on_submit():
#never comes to this part of the code
print "saving data..."
return render_template('pregunta/page.html',form = formulario)
thanks for your answers
I think there are a few things you need to check. What is it in the form that you are trying to validate? In you code sample I don't see the use of validator. for example,
setattr(F,'funcion1', StringField(label='fun1', [validators.Length(max=10)]))
This should add a validators that validate that no more than 10 characters were entered. You can add to the list of validators any validator you would like
In addition if you are using CSRF protection and POST you should include the {{hidden_tag}}or{{formulario.csrf_token}}` as the first element in your form
your form in your template should look like this:
<form action="{{url_for('some_view'}}">
{{hidden_tag}}
<!-- rest of form elements -->
</form>
And try to see what errors you get from your forms bu doing this:
formulario = F()
print formulario.errors
if formulario.validate_on_submit():
# some code

django forms, cleaned_data is empty

I have been playing around with forms a little and cant seem to understand why cleaned_data is not giving me any usable output (aka the dict appears to be completely empty). What id like to do is have a form on a page with two date selector so the user can select a from and to date that Django will then query a database that has periodic thermocouple measurements and create a table.
views.py
def temperature_data(request):
date_select_form = CalLabDateSelect(request.POST)
if request.method == 'POST':
if date_select_form.is_valid(): # All validation rules pass
print "this should be some date/time data from date_select_form:", date_select_form.cleaned_data
#return HttpResponseRedirect('/test_page/') # Redirect after POST
raw_data = Callab.objects.all().using('devices').order_by('-time')
return render_to_response("temperature_display.html",
locals(),
context_instance=RequestContext(request))
forms.py
def make_custom_datefield(f):
formfield = f.formfield()
if isinstance(f, models.DateField):
formfield.widget.format = '%m/%d/%Y'
formfield.widget.attrs.update({'class':'datePicker', 'readonly':'true'})
return formfield
class CalLabDateSelect(forms.Form):
formfield_callback = make_custom_datefield
when i visit the page and select a date then submit the form i see this outputted to the console:
QueryDict: {u'date': [u'10/04/2014'], u'csrfmiddlewaretoken': [u'C5PPlMU3asdFwyma9azFDs4DN33CMmvK']}
this should be some date/time data from date_select_form: {}
all i notice is that the dictionary is empty {} but the request.POST data shows 10/04/2014???
any ideas why this is happening??
And thank you all very much for any help in understand this!!
Your form doesn't actually define any fields, so I don't know what you're expecting to get in cleaned_data. formfield_callback is only useful in a ModelForm, where it operates on the fields already defined by a model: but your form is not based on a model.
Either use a model form, or define your form fields explicitly in your form class.

Keeping typed in form data in django

I have a form where i would like the data to be still present in the form fields if there is a form validation error. By default when i try to submit data in the form django clears all the fields. What is the best approach for doing this using django 1.6 ?
I thought i would just fetch data like so: request.POST['field'], send it to the template and then let the template run a conditional if statement by im getting an error from django telling me that the values isnt found in the multidict but it is found when i fill out the form field so that doesnt seem to work. I also tried to check if the value was present directly in the view but i ended up with a ridicoulus amount of if statements to be able to do this which is just an ugly hack.
Can someone suggest a good working solution on this ? Ive seem threads on SO on kind of the same problem but people just wrote that it should be the default to keep data but that doesnt seem to be the case for django 1.6.
I imagined your form class MyForm(). If the form is not valid send form = MyForm(request.POST) to template.
some view:
def myview(request):
if request.method=='POST':
form = MyForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'success.html')
else:
form = MyForm()
return render(request, 'form.html',{'form':form})
<form action="." method="POST">
{{form}}
</form>

django ModelForm save() method issue

I have a model form:
class SnippetForm(ModelForm):
class Meta:
model = Snippet
exclude = ['author', 'slug']
and I want to be able to edit a particular instance by using this:
def edit_snippet(request, snippet_id):
#look up for that snippet
snippet = get_object_or_404(Snippet, pk=snippet_id)
if request.user.id != snippet.author.id:
return HttpResponseForbidden()
if request.method == 'POST':
form = SnippetForm(data=request.POST, instance=snippet)
if form.is_valid():
form.save()
return HttpResponseRedirect(snippet.get_absolute_url())
else:
form = SnippetForm(instance=snippet)
return render_to_response(SNIPPET_EDIT_TEMPLATE,
{'form':form, 'add':False, 'user':request.user},
RequestContext(request))
Notice that at the line
form = SnippetForm(data=request.POST, instance=snippet)
, I created a form that use the data supplied from the user, and bound it with the instance found using the primary key (received from the url). According to django documentation, when I call save() the existing instance should be updated with POSTED data. Instead, what I see is a new object is created and saved into the database. What went wrong? Thanks a lot.
[Edit] This is really embarrassed. The code indeed has nothing wrong with it. The only thing that messed up the whole thing was the action I put in the template (as I use a same template for add and edit a snippet)....Thanks a lot for your help, really appreciate that.
I don't see why it would happen. What version of django is it?
In any case, you can manually force update passing the corresponding argument.
form = SnippetForm(data=request.POST, instance=snippet, force_update=True)

Django: Adding inline formset rows without javascript

This post relates to this:
Add row to inlines dynamically in django admin
Is there a way to achive adding inline formsets WITHOUT using javascript? Obviously, there would be a page-refresh involved.
So, if the form had a button called 'add'...
I figured I could do it like this:
if request.method=='POST':
if 'add' in request.POST:
PrimaryFunctionFormSet = inlineformset_factory(Position,Function,extra=1)
prims = PrimaryFunctionFormSet(request.POST)
Which I thought would add 1 each time, then populate the form with the post data. However, it seems that the extra=1 does not add 1 to the post data.
Got it.
Sometimes it's the simplest solution. Just make a copy of the request.POST data and modify the TOTAL-FORMS.
for example..
if request.method=='POST':
PrimaryFunctionFormSet = inlineformset_factory(Position,Function)
if 'add' in request.POST:
cp = request.POST.copy()
cp['prim-TOTAL_FORMS'] = int(cp['prim-TOTAL_FORMS'])+ 1
prims = PrimaryFunctionFormSet(cp,prefix='prim')
Then just spit the form out as normal. Keeps your data, adds an inline editor.

Categories