Why is Django loading the same page, but with different URL? - python

I'm studying Django and doing a course to guide me in this process. Now I'm building some forms and I got this problem: when I access http://127.0.0.1:8000/ the main page is loaded correctly, but when I click in the SignUp link, the page doesn't change, just the URL changes (now http://127.0.0.1:8000/signup) with the same content of the homepage. I expected that the form was loaded and the template correspondent for this view as well.
I've checked if my code could be different from the original course code, but I found nothing wrong.
Here is my views.py file:
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from .forms import SubscriberForm
def subscriber_new(request, template='subscribers/subscriber_new.html'):
if request.method == 'POST':
form = SubscriberForm(request.POST)
if form.is_valid():
# Unpack form values
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
email = form.cleaned_data['email']
# Create the User record
user = User(username=username, email=email)
user.set_password(password)
user.save()
# Create Subscriber Record
# Process payment (via Stripe)
# Auto login the user
return HttpResponseRedirect('/success/')
else:
form = SubscriberForm()
return render(request, template, {'form':form})
This is my urls.py file:
from django.conf.urls import patterns, include, url
from marketing.views import HomePage
from django.contrib import admin
urlpatterns = patterns('',
#url(r'^admin/', include(admin.site.urls)),
# Marketing pages
url(r'$', HomePage.as_view(), name="home"),
# Subscriber related URLs
url(r'^signup/$',
'crmapp.subscribers.views.subscriber_new', name='sub_new'),
)
This is my forms.py file:
from django import forms
from django.contrib.auth.forms import UserCreationForm
class SubscriberForm(UserCreationForm):
email = forms.EmailField(
required=True, widget=forms.TextInput(attrs={'class':'form-control'})
)
username = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control'})
)
password1 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
password2 = forms.CharField(
widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})
)
In my templates, the forms are called with this syntax:
<li>Sign Up</li>
I'm using Django version 1.8.4 and Python 2.7.10.
Can someone help me to understand what is happen, please?

You are missing ^ in "home" url:
url(r'^$', HomePage.as_view(), name="home"),

Related

The current path, accounts/<int:id>/, didn’t match any of these ( for django application)

This is a book exchange system I'm trying to create. The challlenge I'm having is trying to redirect the user to a dynamic url consisting of there personal details after log in.
Here is my urs.py for my project
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('exchange/',include('exchange.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
]
Here is my urs.py for my app
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('', views.base, name='base'),
path('register/', views.register_request, name='register'),
path('accounts/<int:id>/', views.user_view, name='userview'),
#path('login/', views.login_request, name='login'),
path('login/', auth_views.LoginView.as_view(template_name='exchange/login.html', redirect_field_name='user_view')),
]
Here is my views.py for my app
from django.shortcuts import render, redirect
from exchange.forms import user_login_form, user_register_form
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib import messages
# Create your views here.
#Base index view
def base(request):
return render(request, 'exchange/base.html',{})
#registration view
def register_request(request):
if request.method=='POST':
form = user_register_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = User.objects.create_user(username=username, email=email, password=password)
user.save()
return redirect('login')
else:
messages.error(request, 'Invalid form')
render(request, 'exchange/register.html',{'form':form})
else:
form = user_register_form()
return render(request, 'exchange/register.html',{'form':form})
#login view
def login_request(request):
if request.method=='POST':
form = user_login_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('user_view', id=user.id)
else:
messages.error(request, 'Invalid username or password')
render(request, 'exchange/login.html',{'form':form})
else:
messages.error(request, 'Invalid form')
render(request, 'exchange/login.html',{'form':form})
form = user_login_form()
return render(request, 'exchange/login.html',{'form':form})
#userview
def user_view(request, id):
user = User.objects.get(id=id)
return render(request, 'exchange/user_view.html',{'user':user})
I have also added LOGIN_REDIRECT_URL = '/accounts/int:id/' to my settings.py.
I presume your app is called exchange
because you've put this 'accounts/<int:id>' inside your exchange app's urls, it's actually trying to match for 'exchange/accounts/<int:id>'
path('exchange/',include('exchange.urls')),
# Link App's Urls -> 'exchange/{x}'.format(pattern)
# exchange.urls (prepend 'exchange')
# url: exchange
path('', views.base, name='base'),
# url: exchange/register
path('register/', views.register_request, name='register'),
# url: exchange/accounts/<int:id>
path('accounts/<int:id>/', views.user_view, name='userview'),
# etc
There's really no way around this prepending, so i think your best bet would be to put it in the main urls and just explicitly say what app + view
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
from exchange.views import user_view
urlpatterns = [
path('exchange/',include('exchange.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('accounts/<int:id>', user_view, name='userview'),
path('admin/', admin.site.urls),
]
I do not see your models but are you sure that you use user_id like
<int:id>
Normally I use pk like this
<int:pk>
You have the following name in your URLs.py
path('accounts/<int:id>/', views.user_view, ***name='userview'***),
But you are using a different name (with an underscore) in your redirect
return redirect(***'user_view'***, id=user.id)
They will need to match for the redirect to work

Please why is there a circular import error

I am working on a django project, but it returns the included urlconf "myapp.urls"does not appear to have any patterns in it.
I tried checking my views to ensure I imported everything correctly
from django.contrib import admin
from django.urls import path
from .views import home
from accounts.views import login_view
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path('accounts/login/', login_view),
]
I expect the site to run and redirect me to the login page
This is my views in the same directory with the urls.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#login_required
def home(request):
return render(request,"home.html")
This is the views.py for the accounts.
from django.shortcuts import render,redirect
from django.contrib.auth import(
authenticate,
get_user_model,
login,
logout
)
from .forms import UserLoginForm, UserRegisterForm
def login_view(request):
next = request.GET.get('next')
form = UserLoginForm()
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
login(request,user)
if next:
return redirect(next)
return redirect("/")
context = {
'form': form,
}
return render(request, "login.html",context)
When I run your project on Django 2.2, I don't see a circular import. Instead I see the error:
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form UserRegisterForm needs updating.
Looking at your form, you haven't set fields, you have model = Userfields = [...] instead.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
model = Userfields = [
'username',
'email',
'password',
"c_password"
]
Change it so that you set fields. You can remove 'password' and 'c_password' since you define these on your form separately.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
fields = [
'username',
'email',
]

Login Django not working

I just created a login with Django, but it doesn't want to work. The script should redirect to start.html if the user login correctly. But Django just reload the page writing the username and the passwort in the url.
view.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.views.generic import View
class Index(View):
def get(self, request):
return render(request, "index.html")
def user_login(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('^start/')
else:
return HttpResponseRedirect('^err/')
else:
print ("Invalid login details")
return HttpResponseRedirect('^impressum/')
urls.py of the project:
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from alarm.views import *
from impressum.views import *
from login.views import *
urlpatterns = [
url(r'^$', Index.as_view()),
url(r'^admin/', admin.site.urls),
url(r'^start/', start.as_view()),
url(r'^terms/', impressum.as_view()),
url(r'^err/', error404.as_view())
]
Whats wrong with this?
Full code: https://github.com/Croghs/stuport
Thanks for every help and sorry for bad english
Croghs
Change <form type="post"> to <form method="post"> in index.html.
Class-based views don't recognise a "user_login" method. It should be called just "post".

Problems with Django ImageField upload

I have a question, I wrote peace of Djnago code, to upload profile picture for user, from admin area model works fine, but from website itself image cannot be uploaded, it seems that code is not even being called. Here is my code, could you check and tell me what might be wrong?
models.py:
from django.conf import settings
from django.db import models
from django.core.files import File
def upload_location(instance, filename):
location = str(instance.user.id)
return "%s/%s" %(location, filename)
class ProfilePicture(models.Model):
user = models.ForeignKey(User)
profile_picture = models.ImageField(upload_to=upload_location, null=True, blank=True)
def __unicode__(self):
return unicode(self.user.id)
forms.py:
from django import forms
from .models import ProfilePicture
class ProfileEditPicture(forms.ModelForm):
class Meta:
model = ProfilePicture
fields = [
"profile_picture"
]
views.py:
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404, render_to_response
rom .forms import ProfileEditPicture
from .models import ProfilePicture
#login_required()
def profile_picture(request, id):
user = get_object_or_404(User, id=id)
title = "Profile Edit"
profile, created = Profile.objects.get_or_create(user=user)
form = ProfileEditPicture(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
context = {
"form":form,
"title":title,
"profile":profile
}
return render(request, "profile/form.html", context)
urls.py:
urlpatterns = [
...
url(r'^profile_picture/(?P<id>[\w.#+-]+)/', 'profiles.views.profile_picture', name='profile_picture'),
...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
HTML code in template is default django form.
Thanks in advance :)
A useful piece of documentation is "Binding uploaded files to a form". Possibly if you follow this you will overcome your issue.
Among other things, it is important that include this attribute in your forms element:
<form method="post" action="..." enctype="multipart/form-data">

Django-reverse URL's

I'm experimenting with Django forms. I'm trying to create a form which will accept the name of a city as input and output coordinates as output. My apps name is rango. I'm having a lot of trouble in URL reverse after accepting the input of the form..
My project/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
import os
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^rango/',include('rango.urls', namespace="rango")),
)
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
My rango/urls.py (rango is the name of the app):
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^welcome/$', views.index, name='index'),
url(r'^about/$', views.about, name='about_page'),
url(r'^categories/(?P<name_dir>\w+)/$',views.cats,name='cats'),
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
url(r'^disp_page/$', views.disp_page, name='disp_page')
My forms.py:
from django import forms
from rango.models import Page, Category
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the name of the city.")
#url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
#views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
exclude = ('category','url','views')
My views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category,Page
from pygeocoder import Geocoder
from rango.forms import PageForm
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import operator
# Create your views here.
def geo(request,city):
context = RequestContext(request)
citydata=Geocoder.geocode(city)
codtuple=citydata[0].coordinates
codtuple=list(codtuple)
context_dict = {'cood':codtuple}
return render_to_response('coods.html',context_dict,context)
def disp_page(request):
# A HTTP POST?
if request.method == 'POST':
form = PageForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
#form.save(commit=True)
city = form.cleaned_data['title']
# context = RequestContext(request)
#citydata=Geocoder.geocode(cityname)
#codtuple=citydata[0].coordinates
#codtuple=list(codtuple)
#context_dict = {'cood':codtuple}
return HttpResponseRedirect(reverse('rango:geo', args=(request,city)))
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = PageForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'disp_page.html', {'form': form})
Basically the disp_page displays the form. I type the name of a city in the form(EX:NEWYORK) and then it has to redirect to the "geo" function in my views.py which would output the coordinates in a different view. This redirection doesn't seem to be happening. Any help is appreciated!!
change this line
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
in rango/urls.py to :
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='geo'),
and use :
return HttpResponseRedirect(reverse('rango:geo', args=(city,)))

Categories