Currently, im trying to make it so that I can complete a question on a page then when it's submitted to the database the next page will load. furthermore, every time I point it towards the templates folder it is piggybacking off the original one meaning that it can't find the new HTML page.
My idea is that when question1 is completed it will link to question2 where the def question2 code will execute and so on. But the forms won't display correctly and I believe it is due to the def question2 not running correctly.
def question1(request):
question_form1 = QuestionForm1()
if request.method == 'POST':
form = QuestionForm1(request.POST)
if form.is_valid():
form.save() # saves to database
return HttpResponse('question2.html')
else:
return render(request, 'music/failed.html')
return render(request, 'music/question1.html', locals())
def question2(request):
question_form2 = QuestionForm2()
if request.method == 'POST':
form2 = QuestionForm2(request.POST)
if form2.is_valid():
form2.save() # Saves to database
return render(request, 'music/question3.html', locals())
else:
return render(request, 'music/failed.html')
return render(request, 'music/question2.html', locals())
Edit:Added Urls.py
from django.conf.urls import url
from . import views
app_name = 'music'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register/$', views.register, name='register'),
url(r'^login_user/$', views.login_user, name='login_user'),
url(r'^logout_user/$', views.logout_user, name='logout_user'),
url(r'^question1/$', views.question1, name='question1'),
url(r'^question2/$', views.question2, name='question2'),
]
from django.http import HttpResponseRedirect
from django.urls import reverse
# delete following line
return HttpResponse('question2.html')`
# replace with this one
return HttpResponseRedirect(reverse('view_name_here'))
# or if you are using any namespaces for your url
return HttpResponseRedirect(reverse('namespace:view_name_here'))
Related
I created a form. I want to when the user fills the form and then sends it, redirect a specific page.
But in my case, the form is saving successfully but does not redirect the page. How can I solve it?
views.py
def setup_wizard(request):
form = SetupForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
setup = form.save()
setup.user = request.user
setup.save()
redirect('dashboard')
else:
form = SetupForm()
context = {
'form': form,
}
return render(request, 'setup_wizard.html', context)
dashboard.urls.py
urlpatterns = [
path('', dashboard, name="dashboard"),
path('setup', setup_wizard, name="setup"),
]
mainproject.urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('dashboard/', include('dashboard.urls')),
... ]
When you're using the redirect method from Django shortcuts you need to return the function result. See this from Django docs
please i need help, no matter how much i try, my site keep returning a
404 error due to fault in urls setup
my views
from django.shortcuts import get_object_or_404, render_to_response
from catalog.models import Category, Product
from django.template import RequestContext
from untitled13.cart import cart
from django.http import HttpResponseRedirect
from untitled13.catalog.forms import ProductAddToCartForm
def index(request, template_name='catalog/index.html'):
page_title = 'online shop for all items'
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
def show_category(request, category_slug, template_name='catalog/category.html'):
c = get_object_or_404(Category, slug=category_slug)
products = c.product_set.all()
page_title = c.name
meta_keywords = c.meta_keywords
meta_description = c.meta_description
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
def show_product(request, product_slug, template_name='catalog/product.html'):
p = get_object_or_404(Product, slug=product_slug)
categories = p.categories.filter(is_active=True)
page_title = p.name
meta_keywords = p.meta_keywords
meta_description = p.meta_description
if request.method == 'POST':
postdata = request.POST.copy()
form = ProductAddToCartForm(request, postdata)
if form.is_valid():
cart.add_to_cart()
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
url = 'show_cart'
return HttpResponseRedirect(url)
else:
form = ProductAddToCartForm(request=request, label_suffix=':')
form.fields['product_slug'].widget.attrs['value'] = product_slug
request.session.set_test_cookie()
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
my urls
"""untitled13 URL Configuration
from django.contrib import admin
from django.urls import path, include
from django.views import static
urlpatterns = [
path('admin/', admin.site.urls),
path('catalog/', include('catalog.urls')),
path('static/', static.serve),
path('cart/', include('cart.urls')),
]
my cart view
from django.shortcuts import render_to_response
from django.template import RequestContext
from untitled13.cart import cart
def show_cart(request, template_name="cart/cart.html"):
cart_item_count = cart.get_cart_items(request)
page_title = 'Shopping Cart'
return render_to_response(template_name, locals(),
context_instanc=RequestContext(request))
the error page
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/site
Using the URLconf defined in untitled13.urls, Django tried these URL patterns, in this order:
admin/
catalog/
static/
cart/
The current path, site, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
You need to add path('site/', views.index) to your urlpatterns if you want '/site' to link to your index view. The error it gives you is really straight forward.
You would also need to import the views.py file containing the index view.
from your_app import views
When I run my server I get a type error message telling me that:
my view must be callable or a list/tuple
and from what I gathered django version differs and for clarity sake, I am using django latest version... Anyways here's my views.py and urls.py for my project:
url.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/$',
'django.contrib.auth.views.login',name='login'),
url(r'^logout/$',
'django.contrib.auth.views.logout',name='logout'),
url(r'^logout-then-login/$',
'django.contrib.auth.views.logout_then_login',name='logout_then_login'),
]
views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
#login_required
def dashboard(request):
return render(request,
'account/dashboard.html',{'section': 'dashboard'})
Try changing your url patterns to below:
urlpatterns = [
url(r'^login/$',
django.contrib.auth.views.login,name='login'),
url(r'^logout/$',
django.contrib.auth.views.logout,name='logout'),
url(r'^logout-then-login/$',
django.contrib.auth.views.logout_then_login,name='logout_then_login'),
]
From the docs for latest django version, the views are function and not strings.
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/register/accounts/register
views.py :
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from custom_user.forms import CustomUserCreationForm
from django.contrib import auth
from django.http import HttpResponseRedirect
#Create your views here
def home(request):
return render(request, "home.html")
def login(request):
c = {}
c.update(csrf(request))
return render(request, "login.html", c)
def about(request):
context = locals()
template = 'about.html'
return render(request,template,context)
#login_required
def userProfile(request):
user = request.user
context = {'user': user}
template = 'profile.html'
return render(request,template,context)
def auth_view(request):
username = request.POST.get['username', '']
password = request.POST.get['password', '']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HTTpResponseRedirect('account/login')
else:
return HTTpResponseRedirect('account/login')
def register(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect ('accounts/register_success.html')
else:
form = CustomUserCreationForm()
args = {'form': form}
return render(request, 'accounts/register.html', args)
def register_success(request):
return render(request, 'accounts/register_success.html')
def logout(request):
auth.logout(request)
return render(request, 'logout.html')
when i try to register a new user this error is raised . i manage to create my own custom registration form. i still cannot register any new user . is this error means that my registration form is not authenticate ? can someone explain why i get this error please ? im confused . help me please :(
urls.py :
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
from profiles import views as profiles_views
from contact import views as contact_views
from checkout import views as checkout_views
from register import views as register_views
urlpatterns = [
url(r'^admin/',include(admin.site.urls)),
url(r'^$', profiles_views.home, name='home'),
url(r'^profile/$', profiles_views.userProfile, name='profile'),
url(r'^about/$', profiles_views.about, name='about'),
url(r'^checkout/$', checkout_views.checkout, name='checkout'),
url(r'^contact/$', contact_views.contact, name='contact'),
url(r'^accounts/register/$', register_views.register, name='register'),
url(r'^accounts/register_success/$', register_views.register_success, name='register_success'),
url(r'^accounts/', include('allauth.urls')),
url(r'^auth/', include('django.contrib.auth.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
Form.valid() should be inside the post indentation
So, I'm trying to create a table filled with contacts in Python/Django. When I attempt to run the program, I get the above error message ("ImportError: Could not import 'edit_contact'. The path must be fully qualified.")
Here is the views.py I'm using:
from contacts.models import Contact
#, Address, Telephone
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, render
from django.template import Context, loader
from django.forms.models import inlineformset_factory
from django.template import loader, Context, RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
#return HttpResponse("Hey! You can see contacts here!")
contact_list = Contact.objects.all().order_by('last_name')
return render_to_response('contacts/index.html', {'contact_list': contact_list},
RequestContext(request))
def detail(request, contact_id):
c = get_object_or_404(Contact, pk=contact_id);
def new_contact(request):
print "new_contact"
#AddressInlineFormSet = inlineformset_factory(Contact,
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
contact = form.save()
return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,)))
else:
form = ContactForm()
return render_to_response("contacts/form.html",{
"form": form,
}, RequestContext(request))
def edit_contact(request, contact_id):
contact = Contact.objects.get(pk=contact_id)
if request.method == "POST":
form = ContactForm(request.POST, instane=contact)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,)))
else:
form = ContactForm(instance = contact)
return render_to_response("contacts/form.html", {
"form": form,
}, RequestContext(request))
This is the urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<contact_id>\d+)/$', 'detail', name='contactdetailsurl'),
url(r'^new/$', 'new_contact', name='newcontacturl'),
url(r'^(?P<contact_id>\d+)/edit/$','edit_contact', name='editcontacturl'),
]
And the error is pointing to this line in my site_base.html file:
<li id="tab_first"><a href="
{% url contacts.views.index %}
"><i class="icon-book"></i> Contacts</a></li>
Let me know if you need any more info. Thanks!
The error is telling you that you should use the full path to the view, for example 'contacts.views.edit_contact' (assuming the app is called contacts).
However, using strings in your URL patterns is deprecated in Django 1.8, and not supported in Django 1.10+. You should using callables instead. You are already using the callable views.index for your index URL pattern.
I would convert the rest of your URL patterns as follows:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<contact_id>\d+)/$', views.detail, name='contactdetailsurl'),
url(r'^new/$', views.new_contact, name='newcontacturl'),
url(r'^(?P<contact_id>\d+)/edit/$', views.edit_contact, name='editcontacturl'),
]