Do I need extra code for Image Field in Django - python

I have this in Model
image_name = models.ImageField(upload_to='accounts/')
In my view I have
def account_form(request):
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = AccountForm() # An unbound form
return render_to_response('account_form.html', {
'form': form,
})
Do I need to do extra coding for saving image or django will do it itself

Also make sure your form enctype is set in the HTML to submit file data:
<form action="..." method="POST" enctype="multipart/form-data">

You need to pass request.FILES to your account form as well.
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
Reference: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
Other than the save() and save_m2m() methods, a ModelForm works exactly the same way as any other forms form. For example, the is_valid() method is used to check for validity, the is_multipart() method is used to determine whether a form requires multipart file upload (and hence whether request.FILES must be passed to the form), etc.

Related

django cookies not getting set

i am trying to set django test cookies on homepage but it is not getting set set.I have tried everything from changing middleware classes to sessionengines
my index function
def index(request):
request.session.set_test_cookie()
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
here is my other function to test cookie
def register(request):
if request.session.test_cookie_worked():
print ">>>> TEST COOKIE WORKED!"
request.session.delete_test_cookie()
# Like before, get the request's context.
context = RequestContext(request)
# A boolean value for telling the template whether the registration was successful.
# Set to False initially. Code changes value to True when registration succeeds.
registered = False
# If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST':
# Attempt to grab information from the raw form information.
# Note that we make use of both UserForm and UserProfileForm.
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
# If the two forms are valid...
if user_form.is_valid() and profile_form.is_valid():
# Save the user's form data to the database.
user = user_form.save()
# Now we hash the password with the set_password method.
# Once hashed, we can update the user object.
user.set_password(user.password)
user.save()
# Now sort out the UserProfile instance.
# Since we need to set the user attribute ourselves, we set commit=False.
# This delays saving the model until we're ready to avoid integrity problems.
profile = profile_form.save(commit=False)
profile.user = user
# Did the user provide a profile picture?
# If so, we need to get it from the input form and put it in the UserProfile model.
# Now we save the UserProfile model instance.
profile.save()
# Update our variable to tell the template registration was successful.
registered = True
# Invalid form or forms - mistakes or something else?
# Print problems to the terminal.
# They'll also be shown to the user.
else:
print user_form.errors, profile_form.errors
# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else:
user_form = UserForm()
profile_form = UserProfileForm()
# Render the template depending on the context.
return render_to_response(
'register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
you do not need to do all those middle ware changes to your settings file. I have just tried setting up a simple demonstration of your code and it works perfect.
First thing, try minimizing your code to only the cookie setting 'experiment'. You can try this demo here.
One one view maybe an index of a home view set the cookie.
On another view maybe an index view of another app test the cookie.
From the docs you can only test using another page request I quote
*test_cookie_worked()* "Returns either True or False, depending on whether the user’s
browser accepted the test cookie. Due to the way cookies work,
you’ll have to call set_test_cookie() on a previous,
separate page request. See Setting test cookies below for more information."
project/appxx/views ... request.session.set_test_cookie() #inside a view
project/appyy/views ... if request.session.test_cookie_worked():
request.session.delete_test_cookie()
return HttpResponse(">>>> TEST COOKIE WORKED!")
Then you can add on the logic later. I have used the HttResponse method instead of the print statment you used.

Prepopulating Django form - request.FILES and instance

I have this weird problem in Django.
I have a form with several text fields and a ImageField. In an edit view, I want the form to be prepopulated with values from an instance, retrieved from the database.
The below code seems to work:
form = UserForm(request.POST or None, instance=instance)
It prepopulates my form with the text fields. The ImageField is also prepopulated, but no matter what new image I choose, it doesn't update after the submission of the form.
I've tried:
form = UserForm(request.POST or None, request.FILES, instance=instance)
which, for some reason, causes every field in the form to be empty with the exception of the ImageField, which I can now change.
What I want to achieve is: the text fields to be prepopulated, as well as the ImageField. I should be able to change the ImageField.
Any thoughts on that?
One example the save data with request.files and instance with forms.
def LocationEdit(request, pk):
locations = Location.objects.get(pk=pk)
form = LocationForm(request.POST or None, instance=locations)
if request.method == 'POST':
form = LocationForm(request.POST or None, request.FILES or None, instance=locations)
print(form)
if form.is_valid():
form.save()
messages.success(request, "I saved it successfully")
return redirect('location:location_list')
types = Location.STATUS
return render(request, 'backend/location/edit.html', {'form' : form, 'locations' : locations, 'types' : types})
just try
form = UserForm(request.POST,request.FILES OR None)

Django form submit again on refresh

Hello I am working on a simple form. The form submits fine but if I refresh the page it resubmits the data. Seems the form is holding the data after submit and I assume since after the submit the request method is post. Question is what is the best way after the submit to clear the form in Django. After the submit the form variables should not be holding the values anymore. Thanks
def testimonials(request, template_name="testimonials.html"):
reviews = Reviews.objects.all()
if request.method == 'POST':
form = forms.ReviewsForm(data = request.POST)
# create a new item
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
if form.is_valid():
nameIn = form.cleaned_data['name']
reviewIn = form.cleaned_data['review']
newReview = Reviews(name = nameIn, review = reviewIn)
newReview.save()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
else:
# This the the first page load, display a blank form
form = forms.ReviewsForm()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Typically, you would issue a redirect after processing a form/POST request (this is common web development practice to avoid the resubmission issue you mentioned). So instead of a render_to_response, you might issue a HttpResponseRedirect like so:
if form.is_valid():
# Process form as desired here
# Simple example; use reverse() to avoid hard-coding URLs
return HttpResponseRedirect('/success/')
Check out the using a form in view for a skeleton of how forms are typically processed.
use reverse instead of render to response
if form.is_valid():
nameIn = form.cleaned_data['name']
reviewIn = form.cleaned_data['review']
newReview = Reviews(name = nameIn, review = reviewIn)
newReview.save()
return HttpResponseRedirect(reverse('app_name:url'))
You could also use the 'redirect' shortcut:
from django.shortcuts import redirect
...
return redirect(newReview)
This is assuming you have get_absolute_url defined in your Review Model.
See the docs for more info.

simple django code snippet from file upload

sorry for dumb question.
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
what happens really in the background when i bind the request to the Form?
It creates an empty form to be passed to the template upload.html since the previous form in upload.html did not pass the validation. When a form has some error, Validation Error exception is raised, then the form is invalid, or when the view is called and request does not include the method POST therefor you must render it again.

Django: construct form without validating fields?

I have a form MyForm which I update using ajax as the user fills it out. I have a view method which updates the form by constructing a MyForm from request.POST and feeding it back.
def update_form(request):
if request.method == 'POST':
dict = {}
dict['form'] = MyForm(request.POST).as_p()
return HttpResponse(json.dumps(dict), mimetype='application/javascript')
return HttpResponseBadRequest()
However, this invokes the cleaning/validation routines, and I don't want to show error messages to the user until they've actually actively clicked "submit".
So the question is: how can I construct a django.forms.Form from existing data without invoking validation?
Validation never invokes until you call form.is_valid().
But as i am guessing, you want your form filled with data user types in, until user clicks submit.
def update_form(request):
if request.method == 'POST':
if not request.POST.get('submit'):
dict = {}
dict['form'] = MyForm(initial = dict(request.POST.items())).as_p()
return HttpResponse(json.dumps(dict), mimetype='application/javascript')
else:
form = MyForm(request.POST)
if form.is_valid():
# Your Final Stuff
pass
return HttpResponseBadRequest()
Happy Coding.

Categories

Resources