I am very puzzled as to why the URL dispatcher is try to look for an empty path although a url was specified for it? Does it imply that it is unable to find the specified url and therefore trying to find the default.
This happens when I try to POST and HttpResponseRedirect searches for an empty path instead of following the specified path. Assume that the other.
Using Django version: 2.0
Thanks in advance!
main/urls.py (ROOT_URLCONF)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/', include('shorterner.urls'))
]
shorterner/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('request/', views.RequestView.as_view(), name="request"),
path('list/', views.IndexView.as_view(), name="list")
]
shorterner/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.conf import settings
from django.urls import reverse
from django.views import View, generic
from .models import Urls
import requests
import json
from .forms import SubmitUrlForm
class RequestView(View):
form_class = SubmitUrlForm
initial = { 'url': ''}
template_name = "shorterner/request.html"
context_object_name = 'url'
def form_valid(self, form):
return super().form_valid(form)
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
input_url = form.cleaned_data['url']
short_url = google_url_shorten(input_url)
print(input_url)
print(short_url)
new_url = Urls.create(short_url, input_url)
new_url.save()
return HttpResponseRedirect('/app/request/')
return render(request, self.template_name, {'form': form})
shorterner/templates/shorterner/request.html
{% extends 'shorterner/base.html' %}
{% block content %}
<form action="/" method="POST">
{% csrf_token %}
<input type="text" name="url" placeholder="Url..." required/>
<input type="submit" value="Submit"/>
</form>
{% endblock %}
Screenshot of the problem
Error Page
Looks like you're sending form data to this path /. But you've not defined that route in main/urls.py.
Related
trying to create an edit profile for users and i keep getting this error what should i add or change ? is my models right for UserEditView
this is my views.py (all of it edited)
maybe the vendor its not compatitable with User edit view
anything elses needs to be added or should i just change something
all imports are for vendor and UserEditView
from tkinter import Entry
from django.contrib.auth.models import User
from xml.dom.minidom import Entity
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth.forms import UserCreationForm , UserChangeForm
from django.utils.text import slugify
from django.shortcuts import render, redirect
from .models import Profile, Vendor
from products.models import Product
from .forms import ProductForm
# Create your views here.
def become_vendor(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
vendor = Vendor.objects.create(name=user.username, created_by=user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'vendor/become_vendor.html', {'form': form})
#login_required
def vendor_admin(request):
context = {
'user':request.user
}
vendor = request.user.vendor
products = vendor.products.all()
return render(request,'vendor/vendor_admin.html',{'vendor': vendor , 'products': products ,'context':context})
#login_required
def add_house(request):
if request.method == 'POST':
form = ProductForm (request.POST, request.FILES)
if form.is_valid():
product = form.save(commit=False)
product.vendor = request.user.vendor
product.slug = slugify(product.عنوان)
product.save()
return redirect('vendor_admin')
else:
form = ProductForm()
return render(request,'vendor/add_house.html',{'form': form})
class UserEditView(generic.UpdateView):
models = User
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
seccess_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
urls.py
from django.urls import path
from .import views
from .views import UserEditView
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpattern =[
path('signup/', views.become_vendor, name='become_vendor'),
path('profile/', views.vendor_admin, name='vendor_admin'),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path('login/', auth_views.LoginView.as_view(template_name='vendor/login.html'), name='login'),
path('edit_profile/', UserEditView.as_view(template_name='vendor/edit_profile.html'), name='edit_profile'),
]
edit_profile.html
(where the error pops up)
{% extends "base.html"%}
{% load static %}
{% block content %}
<title>title</title>
<div class="section pt-9 pb-9">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-title">
<div class="wrap-title">
<h3 class="title">
<span class="first-word"></span>
</h3>
<br>
<form method="post" >
{% csrf_token %}
<table>
{{ form.as_p }}
</table>
<button class='button'>Update</button>
</form>
</div>
<hr>
{% endblock content %}
I think that you didn't declare your model correctly:
class UserEditView(generic.UpdateView):
# models = UserChangeForm #That has no sense.
model = User #The name of your model (Probably the default one: User).
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
success_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
Other thing. You have declared your template name twice. According to your views.py you can delete the template_name on your urls.py:
path('edit_profile/', UserEditView.as_view(), name='edit_profile'),
I want to create a register and login but when I create account in http://127.0.0.1:8000/register/ it doesn't show in admin (http://127.0.0.1:8000/admin/auth/user/)
views.py
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import authenticate, login
def register(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'user/register.html', context)
def login(request):
context = { }
return render(request, 'user/login.html', context)
urls.py
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('register/', views.register, name = "register"),
path('login/', views.login, name="login"),
]
user/register.html
<form method="POST" action=" ">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="Create User">
</form>
I need help, Thank you!
I would like to know how a GET OR POST requests can be handled from a FormView class to render a unbound form for GET and POST the form to database for POST and subsequently redirect to success page (info message).
What template to use for GET and POST methods and how to include message after redirect to success URL?
views.py:
from django.shortcuts import render,redirect,render_to_response,get_object_or_404
from django.forms import ModelForm
from django.views import View
from django.views.generic.edit import CreateView
from .forms import MyPlaceForm
from .models import Place
from django.urls.base import reverse_lazy
from django.contrib import messages
#Ceate your class-based views here.
class MapView(View):
def get(self, request):
'Display map'
return render(request,template_name='index.html')
# Handling forms with class-based view
class PlaceFormView(View):
form_class = MyPlaceForm
initial = {'key': 'value'}
template_name = 'name.html'
# Provide Blank Form if GET request
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
# Provide a message if POST request
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
success_url=reverse_lazy('success')
if form.is_valid():
# <process form cleaned data>
messages.add_message(request, messages.INFO, 'Hello world.')
return reverse_lazy(success_url)
return render(request, self.template_name, {'form': form})
urls.py:
from django.contrib import admin
from django.http import HttpResponse
from django.urls import path
from addismap.views import MapView,PlaceFormView
urlpatterns=[
path('map/',MapView.as_view()),
path('place/', PlaceFormView.as_view(), name='post-place'),
path('place/success/',PlaceFormView.as_view(), name='success')
]
Following the documentation, you can do something like this:
# views.py
if request.method == "POST":
if form.is_valid():
# <process form cleaned data>
messages.success(request, 'Form updated with success.')
return redirect('/success-page')
else:
messages.error(request, 'Ops! Something went wrong')
return redirect('/error-page')
In your template page you can get the message using a for loop code:
{% if messages %}
{% for message in messages %}
<div {% if message.tags %} class="alert alert-{{ message.tags }} alert-dismissible fade show" {% endif %}>
<span>{{ message }}</span>
</div>
{% endfor %}
{% endif %}
Edit1: Make sure you've imported the message tag and redirect in your views.py
from django.contrib import messages
from django.shortcuts import render, redirect
i am just a beginner and starting with some tutorials on web, i can not understand why this isn't working for me:
my views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
class MainPage(View):
def get(self, request):
return render_to_response("helloworld.html")
class TestHandler(View):
def post(self, request):
q = {}
q.update(csrf(request))
#return render_to_response('test.html', q)
return render_to_response('test.html', {'q':q}, context_instance=RequestContext(self.request))
def get(self, request):
q = self.request.GET.get('q')
return HttpResponse(q)
and my urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from views import MainPage, TestHandler
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^hello$', MainPage.as_view(), name='home'),
url(r'^testform/', TestHandler.as_view()),
url(r'^admin/', include(admin.site.urls)),
helloworld.html
>->-<html>
>->->-<head>
>->->->-<title>Hello, World!</title>
>->->-</head>
>->->-<body>
>->->->-<form method="post" action="/testform/" >
{% csrf_token %}
>->->-<input name="q">
<input type="submit">
</form>
>->->-</body>
>->-</html>
test.html
>-<body>
>-Hello {{q}}
>-</body>
This is running on django 1.6, I read most of post and still can't figure it out.
Unfortunately what you have pasted is a bit of a mess, you are using Class Based Views but yet you have mixed them with function based views (also half of the declarations are missing).
Enable the CSRF Middlware in your settings.py
MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
...
)
Fix your views to proper Class Based Views, what you have pasted is totally wrong:
from django.views.generic import CreateView, TemplateView
from django.core.urlresolvers import reverse_lazy
# Create the form in your forms.py
from .forms import (
MyTestForm,
)
class MainPage(TemplateView):
template_name = "test.html"
class TestHandler(CreateView):
form_class = MyTestForm
template_name = "helloworld.html"
success_url = reverse_lazy('home')
Create your form template:
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<form method="post" action="/testform/">
{% csrf_token %}
<input name="q">
<input type="submit">
</form>
</body>
</html>
I'm a beginner and i have been stuck on this for two days.Here is what i presently have in my views files.
from django.contrib.auth import logout
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.core.context_processors import csrf
def registration(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/successful/')
# args = {}
# args.update(csrf(request))
# args['form'] = UserCreationForm()
# return render_to_response('registration/register.html', args)
else:
form = UserCreationForm()
return render(request, "registration/register.html", {'form': form,})
def main_page(request):
return render(request, 'index.html')
def logout_page(request):
"""
Log users out and re-direct them to the main page.
"""
logout(request)
return HttpResponseRedirect('/')# Create your views here.
def success(request):
return render(request, 'success.html')
In my urls file
from django.conf.urls import patterns, include, url
from django.contrib import admin
from mysiteII.views import *
admin.autodiscover()
# Examples:
# url(r'^$', 'mysiteII.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
urlpatterns = patterns('',
url(r'^$', main_page),
# Login / logout.
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^logout/$', logout_page),
# Web portal.
url(r'^portal/', include('portalapp.urls')),
#Serve static content.
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': 'static'}),
url(r'^register/$', registration),
url(r'^admin/', include(admin.site.urls)),
url(r'^successful/$', success),
)
register.html
{% extends "base.html" %}
<!-- # {% block title %}Create an account{% endblock %} -->
{% block content %}
<h2>Create an account</h2>
<form action = "/register/" method = "post">{% csrf_token %}
{{form}}
<input type="submit" value="Create Account" />
</form>
{% endblock %}
Looks as if the register.html doesnt render forms.ProbAbaly i missed out on something.Please someone to point the right direction.Thank you, lot of Appreciation.
The first step to debug this is to make sure you are rendering the proper template, usually this can be done with django debug toolbar. In this case the register.html template is indeed being loaded. From there check your blocks. It's possible that you don't have a "content" block in your base.html.