DJANGO 'WSGIRequest' object has no attribute 'get' - django

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)

Related

How to get the ID of the record created in the model after saving it from a Form

Let's say I submit a form to the back-end and I save a record of the model in the following way:
views.py:
def viewName(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save() #I want to get the id of this after it is saved
else:
print (form.errors)
form = ProjectForm()
return render(request, 'index.html', context)
forms.py:
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = '__all__'
Right after saving the form, I would like to get the id of the record for the model.
I tried with form.id and form.pk as I saw in other similar questions without success.
How can I get the id or the pk of the new entry added to the Project model?
form.save() returns the object, so:
obj = form.save()
print(obj.pk)

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

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?

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.

Attribute error 'WSGIRequest' object has no attribute 'Post' when using multiple submit buttons in my view

I am making a blog app and I need to give multiple buttons to the user when submitting his blog. I am checking which button is set and trying to do the action accordingly but it is not working properly.
Here is my views portion where I am checking which button is set in the POST data but when I click publish it works fine, but if I click save or publish then i get the error
Attribute error 'WSGIRequest' object has no attribute 'Post'
#login_required
def blog_form(request,author_id=None,slug=None):
context_instance=RequestContext(request)
# This view will have a valid creator_id and slug field if the
# blog is being edited and in this case the creator and user should be same
if ( author_id and slug):
author = User.objects.get(pk=author_id)
blog = get_object_or_404(Entry, creator = author, slug = slug)
if blog.creator != request.user:
raise HttpResponseForbidden()
# We set the user and created date and make a new object
else:
blog = Entry(creator=request.user,created_date=datetime.datetime.now() )
if request.method == 'POST':
#if the blog is not published
if 'save' in request.POST:
form = EntryForm(request.Post, instance = blog)
if form.is_valid():
form.save()
elif 'publish' in request.POST:
blog.pub_date = datetime.datetime.now()
blog.status = 1
form = EntryForm(request.POST, instance = blog)
if form.is_valid():
form.save()
return render_to_response('blog/blog_view.html', {'blog': blog,},context_instance=RequestContext(request))
elif 'preview' in request.POST:
form = EntryForm(request.Post, instance = blog)
if form.is_valid():
form.save()
return render_to_response('blog/blog_view.html', {'blog': blog,},context_instance=RequestContext(request))
else:
form = EntryForm(instance = blog)
return render_to_response('blog/blog.html', {'form':form}, context_instance)
The exception is telling you everything you need to know - there is no attribute "Post" on request. However, there is request.POST

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