Django | how to append form field to the urlconf - django

I want to pass a form's field value to the next page (template) after user submit the page, the field could be user name, consider the following setup
def form_submit(request):
if request.method == 'POST':
form = UsersForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
try:
newUser = form.save()
return HttpResponseRedirect('/mysite/nextpage/')
except Exception, ex:
return HttpResponse("Error %s" % str(ex))
else:
return HttpResponse('Error')
"nextpage" is the template that renders after user submit the form, so I want to know how to append the form's field (user name) to the url and get that value from the view in order to pass it to the next page..
thanks.

Change redirect in your controller to include the user name (I guessed at the field name):
def form_submit(request):
if request.method == 'POST':
form = UsersForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
try:
newUser = form.save()
return HttpResponseRedirect('/mysite/nextpage/{0}/'.format(newUser.UserName)
except Exception, ex:
return HttpResponse("Ane apoi %s" % str(ex))
else:
return HttpResponse('Error')
Then you will need a new controller:
def user_redirected_here(request, username):
#do something
And finally add something like this to your urls.py to route to the new view:
urlpatterns = patterns('',
(r"^nextpage/.+$", user_redirected_here),
)

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 form fields not showing up

I am new to django and trying to show a form in an html file and I don't see the fields when I get to this particular page on my browser. Anybody has an idea why?
Here is the html file : In which I can see everything but the form showing up
add_device.html
{% extends 'layout/layout1.html' %}
{% block content %}
<form action = "userprofile/" method = "post">
{% csrf_token %}
{{ form }}
<input type = "submit" value = "Submit"/>
</form>
{% endblock %}
forms.py
from django import forms
from models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('deviceNb',)
models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
deviceNb = models.CharField(max_length = 100)
User.profile = property(lambda u : UserProfile.objects.get_or_create(user = u)[0])
views.py
def user_profile(request):
if request.method == 'POST':
#we want to populate the form with the original instance of the profile model and insert POST info on top of it
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid:
form.save()
#to go back to check that the info has changed
return HttpResponseRedirect('/accounts/loggedin')
else:
#this is the preferred way to get a users info, it is stored that way
user = request.user
profile = user.profile
#if we have a user that has already selected info, it will pass in this info
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
print(form)
return render_to_response('profile.html',args)
I am pretty sure my url file is ok, since I get to the right urls, my problem is really the form fields not showing up.
Thank you so much!!
You are not handling GET request in your view. Update code of the view as
def user_profile(request):
if request.method == 'POST':
# your existing code
# .....
else : #when its get request
form = UserProfileForm(instance=request.user.profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('profile.html',args)
This is a sample code, it can be improved.
The indentation of your view is incorrect. The else block belongs with the if request.method == 'POST' statement, and handles GET requests.
You also need to fix the indentation at the end of the method, so that you return a response for get and post requests. It's better to use render instead of the obsolete render_to_response. This simplifies your code, because you don't need to call args.update(csrf(request)) anymore.
from django.shortcuts import render
def user_profile(request):
if request.method == 'POST':
#we want to populate the form with the original instance of the profile model and insert POST info on top of it
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid:
form.save()
#to go back to check that the info has changed
return HttpResponseRedirect('/accounts/loggedin')
else:
#this is the preferred way to get a users info, it is stored that way
user = request.user
profile = user.profile
#if we have a user that has already selected info, it will pass in this info
form = UserProfileForm(instance=profile)
args = {}
args['form'] = form
return render(request, 'profile.html', args)
You should handle GET request, too. Try this in your view:
def user_profile(request):
form = UserProfileForm()
if request.method == 'GET':
# handle GET request here
form = UserProfileForm(instance=request.user.profile)
elif request.method == 'POST':
#we want to populate the form with the original instance of the profile model and insert POST info on top of it
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid:
form.save()
#to go back to check that the info has changed
return HttpResponseRedirect('/accounts/loggedin')
args = {}
args['form'] = form
return render_to_response('profile.html',args)
And in your profile.html, you can do something like this:
{{ form.as_p }}

Django Redirect treating view as a URL

For some reason, Redirect thinks my call to a view 'clients.views.teacher_profile' is a URL, putting it directly in the address bar as shown:
Page Not Found Screenshot
How do I link it to the view and not treat it as a URL?
Note: I have altered some settings to accommodate django-allauth.
My code:
#views.py
def teacher_profile(request, username):
user = get_object_or_404(User, username=username)
context = {
'user':user,
'teacher':user.teacher,
}
return render(request, 'clients/teacher_profile.html', context)
def edit_profile(request):
teacher = get_object_or_404(Teacher, user=request.user)
if request.method == 'POST':
form = TeacherForm(request.POST, instance=teacher)
if form.is_valid():
teacher = form.save(commit=False)
teacher.user = request.user
teacher.save()
return redirect('clients.views.teacher_profile', username=request.user.username)
else:
form = TeacherForm(instance=teacher)
return render(request, 'clients/edit_profile.html', {'form':form})
#urls.py
urlpatterns = [
url(r'^list/$', views.teacher_list, name='teacher_list'),
url(r'^(?P<username>[\w.#+-]+)/$', views.teacher_profile, name='teacher_profile'),
url(r'^accounts/settings/$', views.edit_profile, name='edit_profile'),
]
Don't use the view's module path in the call to redirect; use the name which you explicitly defined in the url pattern.
return redirect('teacher_profile', username=request.user.username)

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