Hi I have saved an image using my django project with the help of models
as
Image = models.ImageField(upload_to="images/profileimages/")
name = models.CharFiled(max_length=20)
#rest of the fileds.
Once I have saved this information I want to change/update it. For this i have used a view as
def Information_change(request):
instance = get_object_or_404(information,pk=request.user.id)
if request.method == 'POST':
iform = informationForm(instance=instance, data=request.POST, files=request.FILES)
if iform.is_valid():
instance = iform.save()
return HttpResponseRedirect('/')
else:
iform = informationForm(instance=instance)
return render_to_response('registration/information_change.html',{'iform':iform}, RequestContext(request))
In my templates am getting all the information in realated fields like name fields contains my name and all the charfields are showing the information, but the image fileds did not show the image/path or any other thing. Rest of the fields can be changed and i am able to edit my name fileds but unable to replace/change the image using this code. how can I fix this. Any help would be greatly appreciated.
My .html file contains
{% block content %}
{% if iform.errors %}
<p style="color: red;">
Please correct the error{{ iform.errors|pluralize }} below.
</p>
{% endif %}
<form method="post" action=".", enctype="multipart/form-data>
{{ iform.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
First of all do what #Rohan has suggested you. In your view you have a bug, what if there was a case when your form is not valid? Then your view will not return an HTTP response because you have not handled that. Just remove the else of if request.Method == 'POST' and indent back following two lines:
iform = informationForm(instance=instance)
return render_to_response('registration/information_change.html',{'iform':iform}, RequestContext(request))
This will fix the bug which I mention. May be that will show some form errors which is related to image field.
I see 2 issues in your form tag:
comma ',' after actions attribute
No closing quote for enctype attribute value
Related
I have the following code and I'm submitting a form. When I hit the submit button, my form validation prints out False. I've checked and made sure I'm including everything from different posts, but I can't get it to validate. Is there anything I'm doing wrong?
#app.route('/index.html', methods=['GET', 'POST'])
def index():
user = {'nickname': 'Rafa'}
form = FilterForm()
print("about to validate", file=sys.stderr)
if form.validate_on_submit():
print("validated", file=sys.stderr)
filters_array = form.filter.split(',')
streaming(filters_array)
response = {"response", "yes"}
redirect("/authenticate")
return render_template('index.html',
title="Home",
user=user,
form=form)
class FilterForm(Form):
filter = StringField('filter', validators=[DataRequired()])
Here is my Jinja file
{% block content %}
<h1> I have successfully navigated to the title pagee </h1>
<h1> Hello, {{user.nickname}}!</h1>
<h1> Get Tweets </h1>
<p> Please enter a comma delimited list of filters</p>
<form action="" method="post" name="login">
{{form.filter(size=80)}}
<input type="submit" value="Get Tweets!">
</form>
{% endblock %}
FilterForm should not be indented at the same level as def index(). More importantly, you don't have a csrf_token in your form. Which will prevent it from validating.
Add this to your form:
{{ form.csrf_token }}
Lastly, when validating with wtforms, the errors are populated in the form object. So after an if validate, try printing form.errors and you'll find out exactly what is wrong.
Another requirement is that when you use form.validate_on_submit, you have to make sure that you had use all fields of your form model.
I have found some syntax error in your code, maybe that will cause the problem you have met.
first, the problem in your decorator app.route:
app.route('/index')
second, in your html file:
form action='/index'
Extreme noob here. I have been trying to create a simple form in Django where the user can select from the models that are present in the database and then click submit (whereupon I will then return a list of objects).
However, I am getting the following error: 'ModelBase' object is not iterable
Note all I am trying to achieve so far is to actually render the form.
Here is the code:
HTML
<form action="." method="">
{% csrf_token %}
{% for field in output %}
{{ output.as_p }}
{% endfor %}
<input type="submit" value="Save" />
</form>
Forms.py
from projectdb.models import *
class TablesForm(forms.Form):
models = models.get_models()
select = forms.ChoiceField(choices=models)
Views.py
def output_form(request):
form = TablesForm()
return render(request, 'projectdb/output.html', {'output': form})
Much obliged for any help!
Some object is not iterable errors will be fixed by adding .all() where you're doing the foreach loop. If the loop is in the template, try .all only
In a view:
for something in array.all():
In a template:
{% for field in output.all %}
And everytime I do a form in Django my method on the form is empty method="". This let's you return to the same view and process your data there. If you have errors on the form you can redirect to the same form but with the pre-saved data that the user has wrote.
Hope it helps.
I'm going through the book Django 1.0 Website Development where you build a small social bookmarking application. I'm at chapter 5 where you create a form to add bookmarks and although I've followed the instructions and have been struggling on this error for days. I get the error:
AttributeError at /save/
'set' object has no attribute 'get'
The error is being thrown on line 6 of the template {{ form.as_p }}
The views.py code is:
def bookmark_save_page(request):
if request.method == 'POST':
form = BookmarkSaveForm(request)
if form.is_valid():
# create or get link.
link, dummy = Link.objects.get_or_create(
url=form.cleaned_data['url']
)
# create or get bookmark.
bookmark, created = Bookmark.objects.get_or_create(
user=request.user,
link=link
)
# if bookmark is being updated, clear the old tag list
if not created:
bookmark.tag_set.clear()
# create new tag list
tag_names = form.cleaned_data['tags'].split()
for tag_name in tag_names:
tag, dummy = Tag.objects.get_or_create(name=tag_name)
bookmark.tag_set.add()
# save bookmark to database
bookmark.save()
return HttpResponseRedirect(
'/user/%s/' % request.user.username
)
else:
form = BookmarkSaveForm()
variables = RequestContext(request, {
'form' : form
})
return render_to_response('bookmark_save.html', variables)
And the template code is:
{% extends "base.html" %}
{% block title %}Save Bookmark{% endblock %}
{% block head %}Save Bookmark{% endblock %}
{% block content %}
<form method="post" action=".">{% csrf_token %}
**{{ form.as_p }}**
<input type="submit" value="save" />
</form>
{% endblock %}
Any help would be much appreciated as I'm stuck at this point in the book and can't seem to find an answer. Thanks!
Is this an error for you?
for tag_name in tag_names:
tag, dummy = Tag.objects.get_or_create(name=tag_name)
bookmark.tag_set.add() # not adding the tag?
Shouldn't it be: bookmark.tag_set.add(tag) ? The .add() doesn't actually cause an error, but I know you aren't adding your tag.
Without seeing the traceback, I'm guessing.
My other guess is that you might be using the RequestContext wrong?
return render_to_response('bookmark_save.html',
{'form': form},
context_instance=RequestContext(request))
I believe the way you are using it now is meant for the non-shortcut approach of using an HttpResponse()
I have a form like so:
class MyForm(forms.Form):
site = forms.ChoiceField(choices=SITE_CHOICES, label=ugettext_lazy('Site'),)
...
params = forms.MultipleChoiceField(
choices=PARAM_CHOICES,
label=ugettext_lazy('Select Parameters'),
widget=forms.CheckboxSelectMultiple()
)
And in my template:
<form action="{% url results %}" method="get">{% csrf_token %}
{% for field in myform %}
<div class="field_wrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
<input type="submit" name="submit" value="{% trans 'Query' %}" />
</form>
My problem is that when I submit the form as GET the variables are like the following:
site=1¶ms=foo¶ms=bar¶ms=something&submit=Query
my params variable is clearly being overwritten by the last choice? How can get access to the submitted data as separate variables?
Any help appreciated.
Using Django forms
You should be using Django's form handling with a POST which would majke things easier. Here goes:
if request.method == 'GET':
form = MyFormClass()
else:
form = MyFormClass(request.POST)
if form.is_valid():
do_something_with(form.cleaned_data['params'])
return redirect('somewhere')
return render_to_response('my_template.html', RequestContext(request, {'form':form}))
Notes on using GET vs POST with forms
It's useless to include {% csrf_token %} if you're going to GET the form (Absolutely no csrf validation is done with GET requests, which make sense, as GET requests are supposed to be non-data-altering.
Anyway, if you're really going to GET the page, you can still use the same logic as written before, with a little tuning:
form = MyFormClass(request.GET)
if form.is_valid():
do_something_with(form.cleaned_data['params'])
return render_to_response('some_template.html', {'stuff':some_stuff})
return render_to_response('form_submission_page.html', {'form':form})
Last thing, using GET to submit data is usually bad practice, unless you're creating some search function or altering display (pagination & all).
Using request.GET
Now, if for some reason you don't want to use Django forms, you can still get around the problem and retrieve your params, you simply need to use the QueryDict.getlist instead of using the QueryDict.get method.
Here goes:
my_data = request.GET.getlist('params')
Documentation
Don't forget to check out the Django documentation on QueryDicts and on forms
And use {% csrf_token %} in get request is a bad practice.
Use form.is_valid() and form.cleaned_data['params'].
I have a form which allows users to select several parameters to allow faceted querying of data. As there is no data entry going on here I want the form to post to GET and I have a another view with a different template which displays the results.
I want the form to validate as normal so that if a required field is not completed the corresponding errors are displayed. At the moment my process looks like this (simplified):
my search view:
def search(request):
...
context['form'] = GraphForm()
...
return render(request, 'search.html', context)
my results view:
def results(request):
if 'submit' in request.GET:
# process GET variables as query
...
return render(request, 'results.html', context)
my search.html template:
<form action="{% url results %}" method="get">{% csrf_token %}
{% for field in form %}
<div class="field_wrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
<input type="submit" name="submit" value="Query" />
</form>
Given that the form submits to another url with separate view code, what is the best way to go about validating (highlighting errors), and ensuring I have my GET data?
Any help much appreciated.
This might be a little late, but I think the following will work while maintaining similarity to 'POST' workflow:
Instead of having two different views for searching and displaying results, just have one view. The normal codepath described for post forms can then be followed. Instead of using request.method == 'POST' to detect form submission, we instead use 'submit' in request.GET. If using javascript to submit the form, make sure that 'submit' is included in the GET data or use a hidden field to detect form submission.
views.py
def search(request):
context_dict = {}
if 'submit' in request.GET:
form = GraphForm(request.GET)
if form.is_valid():
#do search and add results to context
#If you don't want to use a single view,
# you would redirect to results view here.
results = get_results(**form.cleaned_date)
context_dict['results'] = results
else:
form = GraphForm()
context_dict['form'] = form
return render(request, 'search.html', context_dict)
search.html
<form action="{% url 'search' %}" method="get">
{{form}}
<input type="submit" name="submit" value="Query" />
</form>
{% if results %}
{% include 'results.html' %}
{% endif %}
You should be able to pass request.GET just like request.POST to the form. The form simply accepts a data dictionary. It doesn't care where that comes from. Have you already tried that?
Use JavaScript/jQuery for form validation. All you need to do is add an id to form, and in the corresponding Javascript, do something like
document.getElementById("#form").onsubmit = checkForm();
or using jQuery
$("#form").submit(checkForm);
where checkForm() returns true upon successful validation, and false otherwise. (Note that, if you do not return false, form submission will continue as usual.)
Which fields you check for/validate can also change by using Django's templates.