Django - How do I get the files submitted to a form? - django

In my Django project, I have this view:
def create_format(request, **kwargs):
if request.method == 'POST':
form = FormatUpdateForm(request.POST)
if form.is_valid():
business_type = int(request.POST.get('business_type'))
... more fields ...
constitutive_act_copy = clean_str(request.POST.get('constitutive_act_copy'))
return HttpResponseRedirect(reverse('formats:formats'))
elif request.method == 'GET':
form = FormatUpdateForm()
return render(request, 'format_form.html', context={'form': form, 'autocomplete': SearchableData.objects.all()})
I have many fields, some of which are FileFields. I want to create an object with the data obtained from the form, and I can do that for all fields except the FileFields. What is the correct way to obtain the Files uploaded in the form and use them as attributes when creating an object?

Related

DJANGO 'WSGIRequest' object has no attribute 'get'

I get this error 'WSGIRequest' object has no attribute 'get' in my code
Below is my function in views.py
def user_attendance(request):
# Get the attendance records for the current user
attendance_records = Attendance.objects.filter(user=request.user)
# Create a form instance
form = CompensationRequestForm()
# Check if the form has been submitted
if request.method == 'POST':
# Bind the form with the POST data
form = CompensationRequestForm(request.POST)
# Check if the form is valid
if form.is_valid():
# Save the form data
form.save()
# Redirect to the user_attendance view
return redirect('user_attendance')
context = {'attendance_records': attendance_records, 'form': form}
# Render the template with the attendance records and form
return render(request, 'user_attendance.html', context)
and below is my form in forms.py
class CompensationRequestForm(forms.Form):
date = forms.DateField()
reason = forms.CharField(widget=forms.Textarea)
def save(self):
# Save the form data to the database
pass
how to fix this?
chatgpt didnt help, so i asked here
instead of this form = CompensationRequestForm(request.POST) try this way:
form = CompensationRequestForm(data=request.POST)

Django Send Form By Authenticated User

i stuck when trying to send data or save data with django form by user it self (logged).
When i test why form "From" user must be selectable not automatic selected by user it self.
class ValidationCreate(forms.ModelForm):
class Meta:
model = About
fields = '__all__'
def upload(request):
upload = ValidationCreate()
if request.method == 'POST':
upload = ValidationCreate(request.POST, request.FILES)
if upload.is_valid():
upload.save()
return redirect('validation')
else:
return HttpResponse("""your form is wrong, reload on reload""")
else:
return render(request, 'upload_form.html', {'about_form': upload})
sample
this way you can assign the request.user
if upload.is_valid():
instance = upload.save(commit=False)
instance.profile = Profile.objects.get(user=request.user) # you can change the user if field name is different
instance.save()
return redirect('validation')
else:
in forms
fields = ['field_1', 'field_2',] # except user field

Django - uploading image to database raises IntegrityError

I'm trying to allow users to upload an image. When users are first created, they are given a unique ID / primary key. When users upload an image, I want to save that image in a folder depending on what the users unique ID is. For example, if the users unique ID is 1, I want to save it in
1/uploadedPhotos/imageName
This is my model:
def get_file_path(instance, filename):
return os.path.join('%s/uploadedPhotos' % instance.user_id, filename)
class UserImages(models.Model):
user = models.ForeignKey(User)
photo = models.ImageField(upload_to=get_file_path)
and this is my form:
class UploadImageForm(forms.ModelForm):
class Meta:
model = UserImages
fields = ['photo']
and this is my view:
def uploadImageView(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return redirect('/')
else:
form = UploadImageForm()
return render(request, 'uploadImagePage.html', {'uploadImageForm': form})
The URL which calls the uploadImageView view is /uploadImage/. when I go to that URL and upload an image using the uploadImageForm, it gives an error saying:
IntegrityError at /uploadImage/
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (1, null, None/uploadedPhotos/imageName.png).
and the traceback leads back to the
form.save()
line in my uploadImageView. What am I doing wrong to cause this error?
Your UserImages model requires user but your form UploadImageForm is asking only asking for photo. You need to set user, try something like this:
def uploadImageView(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('/')
else:
form = UploadImageForm()
return render(request, 'uploadImagePage.html', {'uploadImageForm': form})
obj = form.save(commit=False)
obj.user = request.user
obj.save()
You must extract user from request.user and add it to form data.

Django: Cleaning and validating FORMS that depend on each other

The django docs cover cleaning and validating FIELDS that depend on each other, but I can't find anything that covers forms that depend on each other.
I have a single HTML form with which contains both a standard django form and a django formset. Proper validation of each form in the formset is entirely conditional based on a value from the main form (e.g. check a box on the main form, and a specific field on each form in the formset suddenly becomes required).
My intuition is to "simply" pass the entire main form into the formset validation call, like so:
def my_view(request):
MyFormSet = formset_factory(MyForm, extra=2, can_order=True)
if request.method == 'POST':
form = MainForm(request.POST)
formset = MyFormSet(request.POST)
if form.is_valid() and formset.is_valid(form): # <-- ?!?!
# The formset is now validated based on the form
However, to make that work, I believe I would have to override both the formset is_valid() along with the underlying form is_valid() and clean() method. So, it gets pretty messy pretty quick.
Is there a better way to do this?
I investigated doing something like this once, and this tutorial http://yergler.net/blog/2009/09/27/nested-formsets-with-django/ was fairly helpful.
Another way to do this is:
def my_view(request):
MyFormSet = formset_factory(MyForm, extra=2, can_order=True)
if request.method == 'POST':
form = MainForm(request.POST)
formset = MyFormSet(request.POST, other_form = form)
if form.is_valid() and formset.is_valid(): # <-- ?!?!
# The formset is now validated based on the form
Then
class MyFormSet(...):
def __init__(self, *args, **kwargs):
if kwargs.has_key('other_form'):
self.myformforlater = kwargs.pop('other_form')
Super(MyFormSet, self).__init__(*args, **kwargs)
This way you only have to override the init method, and you have access to the outer form from any validation step.
Here's the code I ended up with, using Ted's answer (django 1.3):
class BaseMyFormSet(BaseFormSet):
main_form = None
def __init__(self, *args, **kwargs):
# Save the main form until validation
if kwargs.has_key('main_form'):
self.main_form = kwargs.pop('main_form')
super(BaseMyFormSet, self).__init__(*args, **kwargs)
def clean(self):
if any(self.errors):
# Don't bother validating the formset unless each
# form is valid on its own
return
checkbox = self.main_form.cleaned_data['my_checkbox']
if checkbox:
for form in self.forms:
# Do some extra validation
def my_view(request):
MyFormSet = formset_factory(MyForm, extra=2, can_order=True,
formset=BaseMyFormSet)
if request.method == 'POST':
form = MainForm(request.POST)
formset = MyFormSet(request.POST, main_form=form)
if form.is_valid() and formset.is_valid():
# The formset is now validated based on the form

Saving modelform - won't validate

I'm doing something wrong here, but I can't find it.
I'm using a model form:
class ArtistInfo(ModelForm):
class Meta:
model = Onesheet
fields = (
'name',
'genre',
'location',
'biography',
)
And trying to save the data entered for an existing record.
def edit_artist_info(request, onesheet):
onesheet = Onesheet.objects.get(id = onesheet)
if request.method == 'POST':
form = ArtistInfo(request.POST, instance=onesheet)
if form.is_valid():
test = form.save(commit=False)
test.save()
HttpResponseRedirect('/')
form = ArtistInfo(instance=onesheet, label_suffix='')
variables = RequestContext(request, {
'onesheet':onesheet,
'form': form,
})
return render_to_response('edit_artist_info.html', variables)
But it's not saving. It just reloads the page with whatever the user changed, but if you actually refresh the page (grabbing the value from the DB), it's the old value.
Any ideas? If it's because the form isn't actually validating, I dont know why it's not validating.
try just
if request.method == 'POST':
form = ArtistInfo(request.POST, instance=onesheet)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
You were missing the return statement in your code, and the extra save() was unnecessary