Playing around with FileFiled and trying to update a form. I think my problem comes from the views.py.
I have a template where I can see a product, and I have the option to update the product by clicking on the update button.
When clicking on the update button, I am redirected to a form where I can update the product.
template
{% for TermsAndConditions in commercial_list %}
<a class="btn btn-outline-secondary" href="{% url 'update-commercial' TermsAndConditions.id %}">Update
</a>
{% endfor %}
templateform.py
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h6>Upload terms</h6>
{{ form.attachment| as_crispy_field}}
{% if url %}
<p>Uploaded file {{url}}</p>
{%endif%}
<button type="submit" value="Submit" id="profile-btn" class="btn btn-primary custom-btn">Update</button>
</form>
My normal upload form (without FileField) looks like this:
views (without FileField)
def update_commercial(request, termsandconditions_id):
commercials = TermsAndConditions.objects.get(pk=termsandconditions_id)
form = TermsAndConditionsForm(request.POST or None, instance=commercials )
if form.is_valid():
form.save()
return redirect('list-commercial')
return render(request, 'main/update_commercial.html',{'form':form,'commercials':commercials})
With the addition of the FileField, I thought I would do something like this:
views (with FileField)
def update_commercial(request, termsandconditions_id):
commercials = TermsAndConditions.objects.get(pk=termsandconditions_id)
form = TermsAndConditionsForm(request.POST or None, request.FILES ,instance=commercials ) #the change being request.FILES
if form.is_valid():
form.save()
return redirect('list-commercial')
return render(request, 'main/update_commercial.html',{'form':form,'commercials':commercials})
Problem is, when I do that the update button in the template becomes invalid (it doesn't redirect to the update form).
I think my problem is how to handle the or None and request.FILES together. I tried different combinations but none have worked. Hoping someone might be able to shed some light.
(I have add the models and url files, as I dont think these are the problem and didnt want to make this post longer than it should be, but feel free to let me know)
Ok, figured it out in the end.
Posting the answer just in case for anyone who needs it.
I needed to repeat or None for request.FILES.
def update_commercial(request, termsandconditions_id):
commercials = TermsAndConditions.objects.get(pk=termsandconditions_id)
form = TermsAndConditionsForm(request.POST or None, request.FILES or None,instance=commercials )
if form.is_valid():
form.save()
return redirect('list-commercial')
return render(request, 'main/update_commercial.html',{'form':form,'commercials':commercials})
Related
I cannot understand why it is working in one instance but not the other. I am working with django and output in django template. The only difference between the views/functions are in the second one (the one that is not working) I update the field with time. Time updates, saves in the model and displays updated time correctly. It is just the redirect that is not working.
The working redirect code-
Template, this code takes me to the edit page. Name of the url is "update" -
<td><button>Edit</button></td>
The form on the dit page-
{% block content %}
<div class="wrapper">
<h1 class="ok">Entry Form</h1>
<form action="" method="POST">
{% csrf_token %}
{{form}}
<input type="submit" value="submit">
</form>
</div>
<br>
{% endblock content %}
url-
path('update_entry/<str:pk>/', views.update, name = "update"),
And views.py-
def update(request, pk):
order=Bank1.objects.get(id=pk)
form = Bank1Form(instance=order)
if request.method == 'POST':
form = Bank1Form(request.POST, instance=order)
if form.is_valid():
form.save()
return redirect('/bank1')
context = {'form':form}
return render(request, 'myapp/entry.html', context)
Now here is the non working code. Template, the line that takes me to the update page. Name of the url is "update_enter_workout.-
<td><button>Start Time</button></td>
Form on the Edit page. Didn't add the entire form since I only need to update the time from this page. Just the submit button.-
{% block content %}
<Button>Close this page and go to Home</Button>
<div class="wrapper">
<h1 class="ok">Start/End the set now?</h1>
<form action="" method="post">
{% csrf_token %}
<input type="submit" value="YES!">
</form>
</div>
{% endblock content %}
url-
path('update_enter_workout/<str:pk>/', views.update_workout, name='update_enter_workout'),
Views.py-
def update_workout(request, pk):
order=WorkOut.objects.get(id=pk)
form=WorkOutForm(instance=order)
if request.method=='POST':
form=WorkOutForm(request.POST, instance=order)
time=datetime.now().strftime('%H:%M:%S')
WorkOut.objects.filter(id=pk).update(start=time)
if form.is_valid():
form.save()
return redirect('/bank1')
context={'form':form}
return render(request, 'myapp/enter_workout.html', context)
As you can see they are written the same way, but in the second instance redirect is not working. Any idea what can be changed. It is so simple, couldn't even find a typo or simple mistake like that.
Any advise?
Are you accepting str for id fields? Primary Keys are integers, not strings. You need to cast to an int path converter:
Instead of:
path('update_enter_workout/<str:pk>/', views.update_workout, name='update_enter_workout'),
Use:
path('update_enter_workout/<int:pk>/', views.update_workout, name='update_enter_workout'),
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'
I have apparently forgotten something really basic about django. Here's my views.py:
def sourcedoc_create(request):
if request.method == 'POST': # If the form has been submitted...
form = SourcedocForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
handle_uploaded_file(request.FILES['doc'])
form.save()
return HttpResponseRedirect('/index/') # Redirect after POST
else:
form = SourcedocForm() # An unbound form
return render_to_response(
'sourcedoc_create.html',
{'form': form},
RequestContext(request)
Here's the relevant part of urls.py:
url(r'^$', index),
url(r'^index/', index),
url(r'^sourcedoc/create/', sourcedoc_create),
When I run the app, I create the record in the database, and the uploaded file appears successfully in the relevant directory (thus I infer that the form.save worked ok), but then I get:
KeyError at /sourcedoc/create/
0
Request Method: POST
Request URL: http://www.rosshartshorn.net/worldmaker/sourcedoc/create/
Django Version: 1.4.3
It appears that my HttpResponseRedirect is, for whatever reason, not working, and it's trying to re-POST and throwing a KeyError off a blank form? Or something. In any event, it's not redirecting. When I manually go to /index/, all is well, and the new record is there.
Any ideas what is wrong with my redirect?
In case the forms are relevant:
<body>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<h1>New Post</h1>
<form enctype="multipart/form-data" action="" method="post">
<table>
{{ form.as_table }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
Also, I'm using mongoforms, which is supposed to work like ModelForms:
from mongodbforms import DocumentForm
class SourcedocForm(DocumentForm):
class Meta:
document = Sourcedoc
It seems to have been at least somewhat related to this post: Django MongodbForms KeyError _meta['cascade'].
So, I just upgraded to Django 1.5 and the newest mongodbforms. This eliminated that error, although I was then getting a problem similar to this:
MongoKit "ImportError: No module named objectid " error
I just implemented keppla's answer from that second post, and it now seems to work!
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
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.