Prepopulating Django form - request.FILES and instance - python

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)

Related

How can I post data to the django database and to a CSV file

I am trying to have an output (csv/txt) from a Django form input in addition to saving in the SQL tables
my code is here
def booking_view(request):
global form
if request.method == 'POST':
form = BookingForm(request.POST, request.FILES)
if form.is_valid():
form.save()
**WRITE TO A CSV FILE**
form = BookingForm()
return render(request, 'booking/sandpit.html', {'form': form})
else:
form = BookingForm()
return render(request, 'booking/sandpit.html', {'form': form})
How can i take the form data and save as CSV/TXT
Thanks in advance
Since you are doing form.is_valid(), the form data is available in a usable state in the dictionary cleaned_data. To access this data, call
val1 = form.cleaned_data['fieldNameOne']
val2 = form.cleaned_data['fieldNameTwo']
With these values you can then write to a csv as needed.
Python has a built-in module named csv, and this is probably what you could use.

Django updating profile photo

Look I have a problem with displaying photos after updating.
I have a function from my views.py
def addHW(request):
if request.user.is_authenticated:
obj = Profile.objects.get(user=request.user.id)
else:
obj = ''
profile = request.user.profile
form = CustomerForm(instance=profile)
template = 'HW/add.html'
context = {'form': form, 'profile': obj}
if request.method == 'POST':
form = CustomerForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
Profile.objects.get(user=request.user.id).photo.delete()
form.save()
return render(request, template, context)
and after deleting previous photo and saving of new photo, page must be reloaded. And page shows visual reloading, but HTML shows src of previous image. And after manual refreshing page displays new src of photo.
How i can resolve it?
In case of a successful post, you need to make a redirect to implement the Post/Redirect/Get pattern. – Willem Van Onsem 32 mins ago

Obtaining data from the form with GET data. Django

How can I get data from the form using the GET method?
For example, I have this form:
class LoansSearchForm(forms.Form):
balance = forms.IntegerField(label='', required=False)
In my view display in the form template this way:
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
But i still a error:
'LoansSearchForm' object has no attribute 'cleaned_data'
When trying to get them this way:
word = form['balance']
I receive a field with completed data. How to get the data from my the form correctly?
Is my form written correctly? Should I use something like that?
(sorry if my question is trivial, but I found very little information about GET forms)
if request.method == 'GET':
form = LoansSearchForm(request.GET)
if form.is_valid():
print('Hello World')
else:
form = LoansSearchForm()
Recommended: run form.is_valid() and then you do form.cleaned_data
def search_results(request):
form = LoansSearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
word = cd['balance']
else:
word = None
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it anywhere.
more on cleaned data - documentation
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data # here <------
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
The problem with your code is that forms are not filled on initialization but when you call form.is_valid, if the form is indeed valid, then it populates cleaned_data
You can read more about the related documentation.
I used name=form.data['field_name'], think it answers your answer of obtaining form values on submit.

django-form show form data after saving it

I want to show same data to user as posted by him using form after saving it in database.
I am not getting the logic for it.
I am trying to do something like this:
def CreateDeal(request):
if request.method == "POST":
form = DealForm(request.POST)
if form.is_valid():
form.save(commit = True)
data = form.data
return render(request, '/path_to/deal_detail.html',data=data)
Is it ok ?
Is there any better way to do it?
If you do it this way, a redirect of the "detail" page will resubmit the form. This is generally not desired behaviour.
A better way would be to create a detail view for you saved object (if you haven't already) and redirect the user to the detail view of that particular object:
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def CreateDeal(request):
if request.method == "POST":
form = DealForm(request.POST)
if form.is_valid():
obj = form.save(commit=True)
return HttpResponseRedirect(reverse('deal-detail-view', args=(obj.id,)))
# or return HttpResponseRedirect(obj.get_absolute_url())
# if `get_absolute_url` is defined

Do I need extra code for Image Field in Django

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.

Categories

Resources