Django Form Saving, but NOT Redirecting - django

Basis: I am trying to display a forms information with a new unique url as well as view upon submission. The form is currently saving to the database, but not redirection to the new url or view. Below I've posted both the views.py as well as the urls.py. If you need to see anything else please let me know.
Note: This is based off of a ModelForm and I am somewhat of a beginner to Django.
Thanks in advance!
url.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^letter/testing/$', 'letter.views.letter'),
url(r'^letter/testing/(?P<pk>\d+)/$','letter.views.submission'),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
views.py
# Create your views here.
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from letter.forms import LetterForm
from letter.models import Letter
def submission(request, pk):
submission = get_object_or_404(Letter, pk=int(pk))
return render_to_response('post.html', {'submission':submission})
def letter(request):
if request.method == "POST":
letter = LetterForm(request.POST)
if letter.is_valid():
try:
new_letter = letter.save()
return HttpResponseRedirect('/letter/testing/%d/' % new_letter.pk)
except:
pass
else:
letter = LetterForm()
return render_to_response('letter.html',
{'letter':letter},
context_instance=RequestContext(request))
ANSWER:
Needed to remove the try/except parameters under if letter.is_valid()
Thank you #mattg!

Needed to remove the try and except parameters under if letter.is_valid()

Related

Django NoReverseMatch Error

I'm trying to develop a blog script with Django. But when I want to show post links, I get NoReverseMatch error.
My views.py
# -*- coding: utf-8 -*-
# Create your views here.
from .models import Yazi, Yorum, Kategori
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.contrib.sites.models import Site
def Home(request):
try:
posts = Yazi.objects.filter(yayinlanmis=True).order_by('-yayinlanma_tarihi')
except Yazi.DoesNotExist:
raise Http404
site = Site.objects.get_current()
c = RequestContext(request,{
'posts':posts,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_list.html', c)
def Detail(request, slug):
post = Yazi.objects.get(slug=slug)
site = Site.objects.get_current()
c= RequestContext(request,{
'posts':post,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_detail.html',c)
Urls.py in application folder.
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.Home,name='index'),
url(r'^/makale/(?P<slug>[0-9A-Za-z._%+-]+)$', views.Detail,name='detail'),
)
Urls.py in project folder
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('Penguencik_Yazilar.urls',namespace='blog')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
And template code. What am I doing wrong?
{% load url from future %}
...
Read
Try to change this:
Read
to:
Read
Cause your view expect slug keyword here (?P<slug>[0-9A-Za-z._%+-]+).

How to redirect users to a specific url after registration in django registration?

So I am using django-registration app to implement a user registration page for my site. I used Django's backends.simple views which allows the users to immediately login after registration. My question is how do I redirect them to my other app's page located in the same directory as the project.
Here is what my main urls.py looks like:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^upload/', include('mysite.fileupload.urls')),
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
import os
urlpatterns += patterns('',
(r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)
fileupload is the name of the other app I have in the project directory mysite.
This is what the backends.simple.urls looks like:
"""
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.
If you'd like to customize registration behavior, feel free to set up
your own URL patterns for these views instead.
"""
from django.conf.urls import include
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import TemplateView
from registration.backends.simple.views import RegistrationView
urlpatterns = patterns('',
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'),
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
)
And here is the backends.simple.views:
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User
from registration import signals
from registration.views import RegistrationView as BaseRegistrationView
class RegistrationView(BaseRegistrationView):
"""
A registration backend which implements the simplest possible
workflow: a user supplies a username, email address and password
(the bare minimum for a useful account), and is immediately signed
up and logged in).
"""
def register(self, request, **cleaned_data):
username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1']
User.objects.create_user(username, email, password)
new_user = authenticate(username=username, password=password)
login(request, new_user)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:
* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.
* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.
"""
return getattr(settings, 'REGISTRATION_OPEN', True)
def get_success_url(self, request, user):
return (user.get_absolute_url(), (), {})
I tried the changing the get_success_url function to just return the url I want which is /upload/new but it still redirected me to users/insert username page and gave an error. How do I redirect the user to the upload/new page where the other app resides after registration?
Don't change the code in the registration module. Instead, subclass the RegistrationView, and override the get_success_url method to return the url you want.
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
return "/upload/new"
Then include your custom registration view in your main urls.py, instead of including the simple backend urls.
urlpatterns = [
# your custom registration view
url(r'^register/$', MyRegistrationView.as_view(), name='registration_register'),
# the rest of the views from the simple backend
url(r'^register/closed/$', TemplateView.as_view(template_name='registration/registration_closed.html'),
name='registration_disallowed'),
url(r'', include('registration.auth_urls')),
]
I am using django_registration 3.1 package. I have posted all 3 files (views.py urls.py forms.py) that are needed to use this package.
To redirect user to a custom url on successfull registration, create a view that subclasses RegistrationView. Pass in a success_url of your choice.
Views.py:
from django_registration.backends.one_step.views import RegistrationView
from django.urls import reverse_lazy
class MyRegistrationView(RegistrationView):
success_url = reverse_lazy('homepage:homepage') # using reverse() will give error
urls.py:
from django.urls import path, include
from django_registration.backends.one_step.views import RegistrationView
from core.forms import CustomUserForm
from .views import MyRegistrationView
app_name = 'core'
urlpatterns = [
# login using rest api
path('api/', include('core.api.urls')),
# register for our custom class
path('auth/register/', MyRegistrationView.as_view(
form_class=CustomUserForm
), name='django_registration_register'),
path('auth/', include('django_registration.backends.one_step.urls')),
path('auth/', include('django.contrib.auth.urls'))
]
forms.py:
from django_registration.forms import RegistrationForm
from core.models import CustomUser
class CustomUserForm(RegistrationForm):
class Meta(RegistrationForm.Meta):
model = CustomUser
You can set SIMPLE_BACKEND_REDIRECT_URL in settings.py.
settings.py
SIMPLE_BACKEND_REDIRECT_URL = '/upload/new'
If you wish, you can modify the following file /usr/local/lib/python2.7/dist-packages/registration/backends/simple/urls.py, changing the path, for example:
Before modifying:
success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/'),
After modifying:
success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/upload/new'),
Regards.
Diego

ViewDoesNotExist django

I've been working my way through the tutorials and thought that I'd understood the MVC framework. I have three models, two of which (Guests, Bookings) are populated. I can call data from Guests no problem. I tried to call data from Bookings and get ViewDoesNotExist at /bookings Tried booked_dates in module views. Error was: 'module' object has no attribute 'booked_dates'.
My urls are:
from django.conf.urls.defaults import *
#from views import current_datetime, people, detail, booked_dates
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('views',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^time/$','current_datetime'),
url(r'^mariners/$','people'),
url(r'^mariners/(?P<guest_id>\d+)/$','detail'),
url(r'^bookings/$','booked_dates'),
)
The views are:
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from guests.models import Guest, Booking, Price
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return render_to_response('current_datetime.html', {'current_date': now})
def people(request):
guests_all = Guest.objects.all().order_by('last_name')
return render_to_response('guests_all.html', {'guests_all': guests_all})
def detail(request, guest_id):
g = get_object_or_404(Guest, pk=guest_id)
return render_to_response('guest_detail.html', {'detail' : g})
def booked_dates(request):
dates_all = Booking.objects.all().order_by('start_date')
return render_to_response('bookings.html', {'dates_all' : dates_all})
I haven't included the Models, but Booking is the correct class name, and start_date and end_date are correct.
I can't see an exact replica of this problem, and have tried numerous things to correct it, including a simple 'hello world' view, but I get the same error message.
I must be doing something wrong, but can't see what it might be. I've tried calling the views in a shell, which works.
Thanks for your help.
try including the app name with the view not just the view function
url(r'^bookings/$','guests.views.booked_dates'),

Django - Why doesn't reverse work?

I'm trying to make a view redirect to another view so user's can't access it without a condition being met. In this case, a successful password change. I also want to achieve this using HttpResponseRedirect.
Now, I've never used reverse before, but I figured that this is the way to do that. Problem is that I can't get reverse to work. I get the following error:
ViewDoesNotExist at /account/password/
Could not import findadownload.main.views.foo. View does not exist in module findadownload.main.views.
# URLS
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
#SANDY
from findadownload.sandy.views import *
#TRIVIARIA
from findadownload.trivia.views import *
from findadownload.accounts.views import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'findadownload.main.views.presidium_home', name='presidium_home'),
(r'^web/$', 'findadownload.main.views.web'),
(r'^web/developers/$', sandy_developers),
#SANDY (for findadownload!)
(r'^get/sandy/$', get_sandy),
(r'^get/sandy/download/$', get_sandy_download),
(r'^sandy/register/$', sandy_registration),
(r'^sandy/complete/$', sandy_complete),
(r'^web/shared/$', sandy_shared_files),
(r'^web/remove/all/$', sandy_remove_all),
(r'^web/remove/(?P<file_id>\w+)/$', sandy_remove_file),
(r'^about/$', 'findadownload.main.views.about'),
(r'^pytech/$', 'findadownload.main.views.pytech'),
(r'^pytech/aboutus$', 'findadownload.main.views.pytech_about'),
(r'^pytech/services$', 'findadownload.main.views.pytech_services'),
(r'^pytech/support$', 'findadownload.main.views.pytech_support'),
(r'^pytech/contactus$', 'findadownload.main.views.pytech_contact'),
(r'^pytech/sitemap$', 'findadownload.main.views.pytech_sitemap'),
(r'^pytech/search/$', 'findadownload.main.views.pytech_search'),
(r'^presidium', 'findadownload.main.views.presidium_home'),
#TRIVIARIA
(r'^register/$', register),
(r'^login/$', login_view, {'template': 'trivia/registration/login.html'}),
(r'^logout/$', logout_view),
(r'^trivia/$', submit_question, {'template': 'trivia/trivia_questions.html'}),
(r'^challenges/$', submit_question, {'template': 'trivia/trivia_challenges.html'}),
(r'^question/thanks/$', question_thanks),
(r'^question/answer/$', submit_answer),
(r'^question/answer/result/(\d+)/(.*)/$', answer_result),
(r'^question/answer/challenge/$', challenge_answer),
(r'^account/$', upload_avatar),
(r'^account/password/$', password_change),
url(r'^account/password/success/$', 'findadownload.accounts.views.password_success'),
(r'^(?P<username>\w+)/$', view_user_profile, {'template': 'trivia/trivia_view_user_questions.html'}),
(r'^(?P<username>\w+)/trivia/$', view_user_profile, {'template': 'trivia/trivia_view_user_questions.html'}),
(r'^(?P<username>\w+)/challenges/$', view_user_profile, {'template': 'trivia/trivia_view_user_challenges.html'}),
#FILE SHARING
(r'^web/share/(?P<file_id>\w+)/$', sandy_download),
(r'^web/report/(?P<file_id>\w+)/$', sandy_file_report),
(r'^web/like/(?P<file_id>\w+)/$', like_download),
#OTHER
(r'^web/profile/$', 'findadownload.main.views.web_profile'),
(r'^web/edit/$', 'findadownload.main.views.web_edit'),
(r'^trivia/$', 'findadownload.main.views.trivia_home', {'template': 'trivia/registration/index.html'}),
(r'^web/get/$', 'findadownload.main.views.web_get'),
(r'^web/progress/$', 'findadownload.main.views.web_progress'),
(r'^web/foo/$', 'findadownload.main.views.foo'),
(r'^web/search/$', 'findadownload.main.views.web_search'),
(r'^web/logout/$', 'findadownload.main.views.web_logout'),
(r'^web/resend/$', 'findadownload.main.views.web_resend'),
(r'^web/home/$', 'findadownload.main.views.web_home'),
(r'^web/history/$', 'findadownload.main.views.web_history'),
(r'^web/verify/(?P<link>\w+)/$', 'findadownload.main.views.web_activate'),
(r'^web/help/(?P<username>\w+)/$', 'findadownload.main.views.web_help'),
(r'^web/welcome/(?P<username>\w+)/$', 'findadownload.main.views.welcome'),
(r'^web/terms/$', 'findadownload.main.views.web_terms'),
(r'^web/privacy/$', 'findadownload.main.views.web_privacy'),
(r'^web/signup/$', 'findadownload.main.views.web_signup'),
(r'^web/login/$', 'findadownload.main.views.web_login'),
(r'^test$', 'findadownload.main.views.test'),
# url(r'^findadownload/', include('findadownload.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
if 1:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
'show_indexes': True,
}),
)
urlpatterns += staticfiles_urlpatterns()
# VIEWS
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from findadownload.accounts.forms import *
from django.contrib.auth.models import User
from django.contrib import auth
from findadownload.accounts.models import *
from django.core.urlresolvers import reverse
from findadownload.trivia.models import *
def password_success(request):
return render_to_response('trivia/trivia_password_success.html')
def password_change(request):
if request.user.is_authenticated():
# if for is submitted
if request.method == 'POST':
form = PasswordForm(user=request.user, data=request.POST)
# for the avatar part
if form.is_valid():
cd = form.cleaned_data
request.user.set_password(cd['confirm_password'])
request.user.save()`enter code here`
# redirect to profile page after POST
return HttpResponseRedirect(reverse('findadownload.accounts.views.password_success'))
else:
form = PasswordForm(user=request.user)
# render empty form
return render_to_response('trivia/trivia_password_change.html', {'form': form},
context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/login/?next=%s' % request.path)
You have to specify name kwargs in you url, in this case :
url(r'^account/password/success/$', 'findadownload.accounts.views.password_success', name = 'password_success')
Then use reverse like this :
return HttpResponseRedirect(reverse('password_success'))
What you pass in reverse is the name kwarg on urlpatterns.
EDIT:
Can i see the rest of your urls.py. I think the problem is not on reverse, because Django can't find view named foo.

The included urlconf manager.urls doesn't have any patterns in it

A solution: Found the following django snippet that seems to work fine
(http://djangosnippets.org/snippets/2445/)
from django.utils.functional import lazy
from django.core.urlresolvers import reverse
#Workaround for using reverse with success_url in class based generic views
#because direct usage of it throws an exception.
reverse_lazy = lambda name=None, *args : lazy(reverse, str)(name, args=args)
Apparently, there is now a reverse_lazy function in django trunk.
Update: This error has something to do with me making a call to reverse inside a generic view:
class AddObjView(CreateView):
form_class = ObjForm
template_name = 'manager/obj_add.html'
success_url = reverse('manager-personal_objs')
Is this not valid?
If I instead of generic write something like this, it works:
def add_obj(request, pk):
a=reverse('manager-personal-objs')
return HttpResponse(a)
I have a project with 2 apps in it. Each app has its urls and views. They both work fine, but on the manager app, as soon as I reference the reverse function in the views(any view), I get the following error:
Exception Type: ImproperlyConfigured
Exception Value: The included urlconf manager.urls doesn't have any patterns in it
The urls file:
urlpatterns = patterns('',
url(r'^$', ObjView.as_view(), name='manager-obj'),
url(r'^add/$', AddObjView.as_view(), name='manager-add_obj'),
url(r'^personal/$', PersonalObjsView.as_view(), name='manager-personal_objs'),
)
Exception Location: ...site-packages\django\core\urlresolvers.py in _get_url_patterns, line 283
I get this error in the entire site(edit: this apparently happens because an attempt to import the manager.urls will result in the error). If I remove the include manager.urls, everything goes back to work; if I remove the call to reverse, everything is fine; if I try to rewrite manager.urls to a simpler version, it continues with the error.
I've been over this many times, can't seem to find anything wrong.
edit:root urls.py
# coding=utf8
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# Home Page
url(r'^$', direct_to_template, {'template': 'home.html'}, name="home"),
# manager
url(r'^manager/', include('manager.urls')),
# writing
url(r'^writing/', include('writing.urls')),
)
urlpatterns += staticfiles_urlpatterns()
edit2: Should also be noted that the url template tag works fine in the manager app and the reverse call works if I do it on the other app.
Also, every url has a written working view.
The problem is that your URLConf hasn't finished loading before your class based view attempts to reverse the URL (AddObjView.success_url). You have two options if you want to continue using reverse in your class based views:
a) You can create a get_success_url() method to your class and do the reverse from there
class AddObjView(CreateView):
form_class = ObjForm
template_name = 'manager/obj_add.html'
def get_success_url():
return reverse('manager-personal_objs')
b) If you are running on the trunk/dev version of Django, then you can use reverse_lazy https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
from django.core.urlresolvers import reverse_lazy
class AddObjView(CreateView):
form_class = ObjForm
template_name = 'manager/obj_add.html'
success_url = reverse_lazy('manager-personal_objs')
Option "b" is the preferred method of doing this in future versions of Django.