When I don't fill out anythin in 'Title', I expect It shows me the message 'Fill out title. But It just shows me blank..
views.py
def add_post(request):
entry_title = request.POST.get("title", False)
if request.POST.has_key('title') == False:
return HttpResponse('Fill out title')
else:
return HttpResponse('Hello %s' % entry_title)
write.html
<form method="post" action="/blog/add/post/">{% csrf_token %}
<p>
<label for "title">Title</label>
<input type="text" id="title" name="title" value="" />
</p>
</form>
Firstly, foo.has_key('bar') should be spelled 'bar' in foo.
Secondly, all you're doing is checking if there is a field called title in the form. Well, yes, of course there is, because you put it there yourself. What you should be checking is if that field has any actual content.
if not entry_title:
return HttpResponse('Fill out title')
Related
I have made a form and set method=post and while taking request.post['name'] to a variable MultiValueDictKeyError is Coming why is that ?
<form action="verify_user" method="post">
{% csrf_token %}
<input required type="text" placeholder="Name" name="name"><br><br>
<input required type="password" placeholder="Password" name="password"><br><br>
<input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br>
<br><br><h1>{{ messages }}</h1>
<button type="submit">Create</button>
</form>
this is my form ------
def verify_user(request):
inputname = request.POST['name']
inputpass = request.POST['password']
inputconfirmpass = request.POST['confirm_password']
if not inputpass == inputconfirmpass:
messages.info(request,"Passwords don't match")
else:
messages.info(request,"Passwords match")
return redirect('/verify_user')
this is my function in views.py -------------
MultiValueDictKeyError at /verify_user
'name'
Request Method: GET
Request URL: http://127.0.0.1:8000/verify_user
Django Version: 4.1.2
Exception Type: MultiValueDictKeyError
Exception Value: 'name'
this is the error --------
Try to provide another name as name for e.g. person_name something like that, also I'd recommend you to use .get() so that you can also provide some other default value.
views.py:
def verify_user(request):
if request.method=="POST":
inputname = request.POST.get('person_name', False)
inputpass = request.POST.get('password', False)
inputconfirmpass = request.POST.get('confirm_password', False)
if not inputpass == inputconfirmpass:
messages.info(request,"Passwords don't match")
else:
messages.info(request,"Passwords match")
return redirect('/verify_user')
else: # GET request
return render(request, "some_folder_name/your_template.html")
Template file:
<form method="POST">
{% csrf_token %}
<input required type="text" placeholder="Name" name="person_name"><br><br>
<input required type="password" placeholder="Password" name="password"><br><br>
<input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br>
<br><br><h1>{{ messages }}</h1>
<button type="submit">Create</button>
</form>
I am attempting to pass date values from views.py (passed in from managers.py), but they are not rendering in my template.
I made sure that the date value is correct by printing it to the console and adding it to my template. It renders fine without any filters, but when I used the exact same syntax from earlier in my project—where it worked—all I get are blank values.
managers.py
tz = pytz.timezone('America/Chicago')
class ProfileManager(Manager):
def index(self, request):
profile = models.Profile.objects.get(user__pk=request.session['id']) \
if 'id' in request.session else None
appts = []
next_appt = None
if profile != None:
try:
next_appt = Appointment.objects.get(
profile=profile,
date_end__gt=datetime.now(pytz.utc),
)
except Appointment.DoesNotExist:
next_appt = None
except MultipleObjectsReturned:
next_appt = Appointment.objects.filter(
profile=profile,
date_end__gt=datetime.now(pytz.utc),
).first()
appts = Appointment.objects \
.filter(date_end__gt=datetime.now(pytz.utc)) \
.exclude(profile__user=None)
return {
'profile': profile,
'next_appt': next_appt,
'appts': appts,
'TIME_ZONE': TIME_ZONE,
'current_date': datetime.now(tz),
}
views.py
def index(request):
response = Profile.objects.index(request)
return render(request, 'users/index.html', response)
index.html
<div id="datePickerDate">
{{ current_date }}
<input type="hidden" name="year" value="{{ current_date|date:'Y' }}" autocomplete="off">
<input type="hidden" name="month" value="{{ current_date|date:'n' }}" autocomplete="off">
</div>
Result
<div id="datePickerDate">
Aug. 19, 2019, 4:27 p.m.
<input name="year" value="" autocomplete="off" type="hidden">
<input name="month" value="" autocomplete="off" type="hidden">
</div>
I can't think of what I'm missing. Any help is appreciated.
I found that the issue was in my JavaScript. I was adding values to the input fields though jQuery without realizing it, and those values were undefined. It appears I should be more cognizant of what code I actually need when I copy and paste code from other parts of a project, or any other source for that matter.
I got an error,ValueError at /accounts/upload_save/
The view accounts.views.upload_save didn't return an HttpResponse object. It returned None instead.
Always image cannot be sent normally. I wrote in views.py
def photo(request):
d = {
'photos': Post.objects.all(),
}
return render(request, 'registration/accounts/profile.html', d)
def upload_save(request):
if request.method == "POST":
print(444)
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
print(5555)
image1 = form.cleaned_data.get('image1')
image2 = form.cleaned_data.get("image2")
user = request.user
ImageAndUser.objects.create(
User=user,
image=image1,
image2=image2,
image3=image3,
)
return redirect('registration/accounts/photo.html')
else:
print(666)
form = UserImageForm(request.POST or None)
return render(request, 'registration/profile.html',{'form':form})
in profile.html
<main>
<div>
<img class="absolute-fill">
<div class="container" id="photoform">
<form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form">
{% csrf_token %}
<div class="input-group">
<label>
<input id="image1" type="file" name="image1" accept="image/*" style="display: none">
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="input-group">
<label>
<input id="image2" type="file" name="image2" accept="image/*" style="display: none">
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="input-group">
<label>
<input id="image3" type="file" name="image3" accept="image/*" style="display: none">
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<input id="send" type="submit" value="SEND" class="form-control">
</form>
</div>
</div>
</div>
</main>
in forms.py
class UserImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = ImageAndUser
fields = ('image1','image2','image3')
in urls.py
urlpatterns = [
url(r'^profile/$', views.profile, name='profile'),
url(r'^photo/$', views.photo, name='photo'),
url(r'^upload_save/$', views.upload_save, name='upload_save'),
]
I really cannot understand why this error happens.I surely send images so I think type is not None.What is wrong in my code?How should I fix this?I debuged my views.py code,so 444 is shown in print(444).Traceback is
Traceback:
File "/Users/xxx/anaconda/envs/py35/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/xxx/anaconda/envs/py35/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
198. "returned None instead." % (callback.__module__, view_name)
Exception Type: ValueError at /accounts/upload_save/
Exception Value: The view accounts.views.upload_save didn't return an HttpResponse object. It returned None instead.
couple of thing wrong in your code:
First you model looks like this:
Modle: ImageAndUser contain four fieds: user, image, image2, image3
as you have mentioned in object creation.
ImageAndUser.objects.create(User=user,image=image1,image2=image2,image3=image3
)
and you mentioned field in form:
class UserImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = ImageAndUser
fields = ('image1','image2','image3')
where image1 is coming from. It's image attribute.
do it like this.
class UserImageForm(forms.ModelForm):
class Meta:
model = ImageAndUser
fields = ('image','image2','image3')
Make Edit in your template side.
<input id="image" type="file" name="image" accept="image/*" style="display: none">
</label>
Hope this works.
For one thing, image3 is not being set. Try adding this line
image3 = form.cleaned_data.get("image3")
after the one that does the same thing for image2.
Further to that, the view will return None if the form is invalid, i.e. if form.is_valid() returns False.
I wrote codes, but I don't know how to set 'name' and 'value' of hidden tag with Django template. I read Django's Widgets Docs, but I couldn't find the way.
(Pdb) print(errors)
<ul class="errorlist"><li>friend_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>add_remove<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
First, I tried to write like
<input type="hidden" name="friend_id" value="{{ user_info.user_id }}">
and
friend_id = request.POST.friend_id
But I couldn't get how to get POST values without Django's Form. So, I used Django's Form with following codes.
views.py
from myapp.forms import HiddenUserPage
hiddenform = HiddenUserPage
if request.method == 'POST':
hidden = hiddenform(request.POST)
if hidden.is_valid():
from myapp.models import Friends
try:
friend_id = hidden.cleaned_data['friend_id']
add_remove = hidden.cleaned_data['add_remove']
if add_remove == "add":
f = Friends(user_id=request.user.user_id, friend_id=friend_id)
f.save()
elif add_remove == "remove":
f = Friends.objects.filter(user_id=request.user.user_id).get(friend_id=friend_id)
f.delete()
except:
errors = "DB error"
else:
errors = hidden.errors
else:
hidden = hiddenform()
errors = ""
view = {
'errors': errors,
'hidden': hidden,
}
template = 'myapp/user/user_page.html'
return render(request, template, view)
forms.py
class HiddenUserPage(forms.Form):
friend_id = forms.CharField(widget=forms.HiddenInput())
add_remove = forms.CharField(widget=forms.HiddenInput())
user_page.html
<form method="POST" action="" class="">
{% csrf_token %}
<p class="submit">
<button class="confirmbutton" type="submit">
{% if is_friend %}
remove friend
<!-- # I'd like to write like # -->
<!-- <input type="hidden" name="friend_id" value="remove"> # -->
<!-- <input type="hidden" name="friend_id" value="{{ user_info.user_id }}"> # -->
{{ hidden.add_remove }}
{{ hidden.friend_id }}
{% else %}
add friend
<!-- <input type="hidden" name="friend_id" value="add"> # -->
<!-- <input type="hidden" name="friend_id" value="{{ user_info.user_id }}"> # -->
{{ hidden.add_remove }}
{{ hidden.friend_id }}
{% endif %}
</button>
</p>
</form>
Sorry, my code is filthy.
Looks like the question is in providing initial data to the form, then it's is generally done in the view passing initial to the form instantiation, e.g.:
# In your view.py
def ...(...):
# Inside your view function
if request.method == 'GET':
# Provide initial data to the form here
# Get your 'user_info' from models or sessions,
# or wherever you keep it
hidden = hiddenform(initial={"friend_id":user_info.user_id})
if reuest.method == 'POST':
hidden = hiddenform(request.POST)
# Process posted form data
...
# More code general for both HTTP verbs
view = {'errors': errors, 'hidden': hidden}
template = 'myapp/user/user_page.html'
return render(request, template, view)
You might also want to bound the form to model data directly, see the docs for more info.
The form has this hidden field
<input type="hidden" name="dir_type" value="tshirt">
url parameters are
/dir?type=tshirt
/dir?type=books
/dir?type=posters
and so on.
Now I hard coded value="tshirts" but how do I get parameter for the relevant page?
I found several pages like this dealing with similar topics but I did not understand how this is done.
Thanks for your help.
UPDATE
The answer by systempuntoout works perfectly but I decided to solve the problem without using templates. And for anyone who has a similar question, passing the url parameter to the form like this works well:
<form name="submit_form" action="/directorysubmithandler" method="post" onSubmit="return validate_form()">
title: <input type="text" name="title" size=50><br />
url: <input type="text" name="url" size=50><br />
<input type="hidden" name="dir_type" value="%s")>
<input type="submit" value="submit">
</form>""" % self.request.get("type"))
a. pass the type value to the view:
class Directory(webapp.RequestHandler):
def get(self):
....
merchandise_type = self.request.get("type", "")
items = Item.all()
items.filter("type =", merchandise_type)
path = os.path.join(os.path.dirname(__file__), 'dir_details.html')
self.response.out.write(template.render(path,{'type':merchandise_type}))
b. add the type value to the hidden field:
<input type="hidden" name="dir_type" value="{{ type }}">
c. get the dir_type value in your post handler:
class DirectorySubmitHandler(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
merchandise_type = self.request.get("dir_type", "")
dir_type = merchandise_type
if user:
item = Item()
item.title = self.request.get("title")
item.url = self.request.get("url")
item.type = self.request.get("dir_type")
item.user_who_liked_this_item = user
item.put()
self.redirect("/dir?type=%s" %
self.request.get("dir_type"))
else:
self.redirect(users.create_login_url(self.request.uri))