SyntaxError at /
invalid syntax (forms.py, line 5)
Request Method: POST
Request URL: http://127.0.0.1:8000/
Django Version: 1.6.1
Exception Type: SyntaxError
Exception Value:
invalid syntax (forms.py, line 5)
ExceptionLocation: C:\Users\chiragbagla\Desktop\skillshare\src\signups\views.py in <module>, line 5
Python Executable: C:\Users\chiragbagla\Desktop\skillshare\Scripts\python2.exe
Python Version: 2.7.9
A part of my view.py code is as follows
from django.shortcuts import render, render_to_response, RequestContext
# Create your views here.
from .forms import SignUpForm
def home(request):
form = SignUpForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
return render_to_response("signup.html", locals(), context_instance=RequestContext(request))
A part of my forms.py code is as follows
from django import forms
from .models import SignUp
class SignUpForm(forms.ModelForm):
class meta:
model=SignUp
A part of my url.py code is as follows
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'signups.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
I want to display sign up form on webpage which I have created using signup.html but the form is not displaying on the webpage of my browser.
So, please tell me where the mistake I am making???
Like the error points out:
class meta:
Should be...
class Meta:
Related
I am trying to simply add a new 'blog' page in Django, which should replicate the home page. The home page is working fine, and if I view the URLs for my app, it looks like the following:
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
In my understanding of Django, I could add a 'blog' page by adding the following:
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
path('blog/', views.PostList.as_view(), name='blog'), #ADDED LINE
]
However going to my http://127.0.0.1:8000/blog/ page returns a 404 error. With Django debugging enabled, I get the following message:
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/blog/ Raised
by: main_site_app.views.PostDetail
From what I can observe, there is nothing additional that the index page has that the blog doesn't. Is there a step I'm missing here that is preventing the /blog/ page from showing up?
EDIT:
views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views import generic
from .models import Post
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index_2.html'
class PostListLimited(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')[:2]
template_name = 'index_2.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
The issue started when I added a new app which has a urls.py like the following:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'login/$',
auth_views.LoginView.as_view(template_name='accounts/login.html'),
name='login'),
url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'),
url(r'signup/$',views.SignUp.as_view(), name='signup'),
]
My project urls.py has a line which points to the app and looks like the following code:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^test/$', views.TestPage.as_view(), name='test'),
url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks')
]
My application's view looks like the following:
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
My project's view looks like:
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'test.html'
class ThanksPage(TemplateView):
template_name = 'thanks.html'
class HomePage(TemplateView):
template_name = 'index.html'
Can anyone please help me identify where I could possibly be going wrong.
You are importing auth.urls twice. Remove url(r'^accounts/', include('django.contrib.auth.urls')) from your project's urls.py
I am importing wrong URL configuration, instead of 'reverse' I should import 'reverse_lazy',
change
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
to
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'
I'm currently trying to implement the ability to login and logout into my django site and I'm getting the following error when attempting to use the command python manage.py runserver while in the virtual environment. I'm using django 2.2
my porject:
realtime
|-core
|-nodejs
|-realtime
|-templates
| |-index.html
|-url.py
my code url.py
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
url(r'Home/$', views.Home, name='Home'),
url(r'^node_api$', views.node_api, name='node_api'),
url(r'^accounts/login/$', auth_views.LoginView.as_view(template_name='myapp/login.html')),
url(r'^login/$', views.LogoutView.as_view(template_name=template_name), name='logout'),
]
core\views.py
from core.models import Comments, User
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseServerError
from django.views.decorators.csrf import csrf_exempt
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
import redis
#login_required
def home(request):
comments = Comments.objects.select_related().all()[0:100]
return render(request, 'index.html', locals())
#csrf_exempt
def node_api(request):
try:
#Get User from sessionid
session = Session.objects.get(session_key=request.POST.get('sessionid'))
user_id = session.get_decoded().get('_auth_user_id')
user = User.objects.get(id=user_id)
#Create comment
Comments.objects.create(user=user, text=request.POST.get('comment'))
#Once comment has been created post it to the chat channel
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.publish('chat', user.username + ': ' + request.POST.get('comment'))
return HttpResponse("Everything worked :)")
except Exception as e:
return HttpResponseServerError(str(e))
On the line
url(r'Home/$', views.Home, name='Home'),
the view Home is loaded from module views which refer to this import:
from django.contrib.auth import views
Since django.contrib.auth.views does NOT define any class or function Home, you get your error.
You probably forgot to import your app's views module:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
import core.views as my_app_views
urlpatterns = [
url(r'Home/$', my_app_views.home, name='Home'),
url(r'^node_api$', my_app_views.node_api, name='node_api'),
url(r'^accounts/login/$', auth_views.LoginView.as_view(template_name='myapp/login.html')),
url(r'^login/$', auth_views.LogoutView.as_view(template_name=template_name), name='logout'),
]
Please note that in this new version, django.contrib.auth.views is imported with name auth_views and your custom app's views is imported with name my_app_views. This will prevent any confusion when calling views from one app or another
I am trying to learn about class based views and django in general. The project is notes_project and in it I have created an app notes. Below is the urls.py for both of these and views.py for notes app:
notes_project/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
import notes
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'notes_project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^notes/', include('notes.urls')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
)
notes/urls.py
from django.conf.urls import include, patterns, url
from .views import IndexView
urlpatterns = patterns(r'^$/', IndexView.as_view())
notes/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
class IndexView(View):
def get(request):
return HttpResponse("Welcome to notes index")
However, whenever I access the URL http://127.0.0.1:8000/notes/, I keep getting below error:
Request Method: GET
Request URL: http://127.0.0.1:8000/notes/
Django Version: 1.7.4
Exception Type: AttributeError
Exception Value:
'function' object has no attribute 'resolve'
Exception Location: /path/notes/venv/lib/python3.4/site-packages/django/core/urlresolvers.py in resolve, line 345
Python Executable: /path/notes/venv/bin/python
Python Version: 3.4.2
Python Path:
['/path/notes/notes_project',
'/path/notes/venv/lib/python3.4',
'/path/notes/venv/lib/python3.4/plat-x86_64-linux-gnu',
'/path/notes/venv/lib/python3.4/lib-dynload',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/path/notes/venv/lib/python3.4/site-packages']
The first argument to patterns is a string that acts as prefix to the rest of the patterns. Also each pattern needs to be a tuple of its own. You've done that correctly in the main urls.py but missed it in the notes one. It should be:
urlpatterns = patterns('',
(r'^$', IndexView.as_view()),
)
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,)))