Django first app - python

I have some problems with my first django app (its name is magghy). I'm at the start of development. So, I have:
magghy/urls.py:
from django.conf.urls import *
from magghy import views
from . import views
app_name = 'magghy'
urlpatterns = [
# esempio: /magghy/
url(r'^$', views.index, name='index'),
#esempio: /magghy/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /magghy/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /magghy/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
In magghy/views.py:
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Choice, Question
from django.template import loader
from django.urls import reverse
#visualizzare domande e argomento specifico - collegare con modulo magghy.urls
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
#visualizzare pagina html secondo schema index.html oppure html 404 (eccezione)
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('magghy/index.html')
context = RequestContext (request, {
'latest_question_list': latest_question_list,
})
return HttpResponse(template.render(context))
#visualizzare pagina 404
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
In mysite/urls.py:
from django.conf.urls import *
from django.contrib import admin
from magghy import views
urlpatterns = [
url(r'^magghy/', views.detail),
url(r'^admin/', include (admin.site.urls)),
]
The page http://127.0.0.1:8000/admin/ works perfectly!
The page http://127.0.0.1:8000/magghy/ doesn't work
The page http://127.0.0.1:8000/magghy/5 doesn't work
In both case the terminal logs are:
Internal Server Error: /magghy/
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: detail() takes exactly 2 arguments (1 given)
Please, can you help me? Thanks a lot!
Adri

mysite/urls.py is linking directly to the detail view, rather than including the app URLs. It should be:
urlpatterns = [
url(r'^magghy/', include('magghy.urls')),
url(r'^admin/', include (admin.site.urls)),
]

Related

Django Http404 message not showing up

I am currently on Django documentation part 3 where I have to create the polls app. However, when I make a request to the url having path like http://127.0.0.1:8000/polls/3/, I was supposed to get the message 'Question does not exist.' But I don't.
Here is my code
polls/views.py
from django.http import HttpResponse, HttpResponseNotFound, Http404
from django.shortcuts import render
from .models import Question
# Create your views here.
def index(request):
# - sign to get more recent, list is ordered from 0 to 4
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {
'latest_question_list': latest_question_list,
}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
return HttpResponseNotFound("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
The error is
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/3/
Raised by: polls.views.detail
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
polls/ [name='index']
polls/ <int:question_id>/ [name='detail']
The current path, polls/3/, matched the last one.
Try changing raise Http404("Question does not exist") to return HttpResponseNotFound("Question does not exist")
You can set debug=false , provide a message to Http404 and then it will appear in the standard 404 debug template. Find more details here.

AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method

I am writing a simple Django web application and I am trying implement REST API. I use django-rest-framework package. I use Python 3.x on Debian sid GNU/Linux. However, when I try access REST API through browser I'm getting error:
Traceback (most recent call last):
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 471, in dispatch
self.initial(request, *args, **kwargs)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 389, in initial
self.check_permissions(request)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 322, in check_permissions
if not permission.has_permission(request, self):
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/permissions.py", line 141, in has_permission
queryset = self._queryset(view)
File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/permissions.py", line 121, in _queryset
).format(self.__class__.__name__)
AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method.
[24/Jun/2018 14:34:41] "GET /articles/ HTTP/1.1" 500 101619
Here's my code:
news/serializers.py:
from rest_framework import serializers
from .models import Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
news/views.py:
from django.shortcuts import get_object_or_404, render
from django.views import generic
from rest_framework.response import Response
from rest_framework.views import APIView
from .forms import ArticleForm, CommentForm, GuestForm
from .models import Article, Guest
from .serializers import ArticleSerializer
# Create your views here.
class ArticleList(generic.ListView):
template_name = 'news/article/list.html'
model = Article
context_object_name = 'articles'
def get_queryset(self):
return Article.objects.filter(status='published')
class ArticleDetail(generic.View):
template_name = 'news/article/detail.html'
comment_form = CommentForm
def get(self, request, pk):
article = get_object_or_404(Article,
pk=pk)
comments = article.comments
return render(request, self.template_name,
{'article': article,
'comments': comments,
'comment_form': self.comment_form})
def post(self, request, pk):
article = get_object_or_404(Article,
pk=pk)
comments = article.comments.filter(status='published')
form = self.comment_form(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.article = article
comment.save()
return render(request, self.template_name,
{'article': article,
'comments': comments,
'comment_form': self.comment_form})
class GuestBook(generic.View):
template_name = 'news/guestbook/list.html'
guest_form = GuestForm
def get(self, request):
guests = Guest.objects.filter(status='published')
return render(request, self.template_name,
{'guests': guests,
'guest_form': self.guest_form})
def post(self, request):
guests = Guest.objects.filter(status='published')
form = self.guest_form(request.POST)
if form.is_valid():
form.save()
return render(request, self.template_name,
{'guests': guests,
'guest_form': self.guest_form})
class ArticleCreate(generic.View):
template_name = 'news/article_form.html'
article_form = ArticleForm
def get(self, request):
return render(request, self.template_name,
{'form': self.article_form})
class RESTArticleList(APIView):
def get(self, request):
articles = Article.objects.filter(status='published').all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data)
def post(self):
pass
hello_world/urls.py:
"""hello_world URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from news import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('admin/', admin.site.urls),
path('news/', include('news.urls')),
path('tinymce/', include('tinymce.urls')),
path('articles/', views.RESTArticleList.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am counting for help!
From the docs:
This permission must only be applied to views that have a .queryset property set.
So try to add queryset attribute to your RESTArticleList view:
class RESTArticleList(APIView):
queryset = Article.objects.filter(status='published')
def get(self, request):
articles = Article.objects.filter(status='published').all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data)
def post(self):
pass

'tuple' object has no attribute 'get'

I am new to Django framework and I am trying to perform the Django authentication views but i keep on getting this error
C:\Users\Harsley\bookmarks>python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
March 21, 2017 - 21:11:56
Django version 1.10.6, using settings 'bookmarks.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /
Traceback (most recent call last):
File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
response = get_response(request)
File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\deprecation.py", line 138, in __call__
response = self.process_response(request, response)
File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\middleware\clickjacking.py", line 32, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'tuple' object has no attribute 'get'
[21/Mar/2017 21:11:58] "GET / HTTP/1.1" 500 57044
This is my url.py file
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^login$', auth_views.login, name='login'),
url(r'^logout$', auth_views.logout, name='logout'),
url(r'^logout_then_login$', auth_views.logout_then_login, `name='logout_then_login'),`
url(r'^$', views.dashboard, name='dashboard'),
]
Here is my views
from django.contrib.auth.decorators import login_required
#login_required()
def dashboard(request):
return (request, 'dashboard.html', {'section': 'dashboard'})
This is wrong:
return (request, 'dashboard.html', {'section': 'dashboard'})
You are returning a tuple where you have to return a Response.
Instead of directly returning a response you can use the render-shortcut:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#login_required()
def dashboard(request):
return render(request, 'dashboard.html', {'section': 'dashboard'})

NoReverseMatch at /accounts/home_page/

#Reverse for 'user_profile_view' with arguments '(u'Emmanuel',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] :
#project/urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'', include('app.urls', namespace='app')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#app/urls.py
from .views import *
from . import views
from django.conf import settings
from django.conf.urls import url
from django.views.generic import TemplateView
from django.conf.urls.static import static
app_name = 'app'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^accounts/home_page/$', home_page),
url(r'^accounts/home_page/(?P<username>[\w-]+)/$', UserProfileView.as_view(), name='user_profile_view'),
# url(r'^accounts/profile/$', views.user_profile, name='user_profile'),
# url(r'^accounts/profile/edit/$', views.edit_user_profile,
# name='edit_user_profile'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#views.py
class UserProfileView(View):
#method_decorator(login_required)
def get(self, request, user):
if request.user.username == user:
profile = get_object_or_404(User, user=request.user)
return render(request, 'registration/home.html', {'profile': profile})
else:
raise Http404
#login_required
def home_page(request):
return HttpResponseRedirect(
reverse('user_profile_view', args=[request.user.username], current_app='app'))
So what I'm actually trying to do is allow a user login with is name appearing in the url but since the LOGIN_REDIRECT_URL = '/accounts/home_page' cannot take a dynamic parameter like I am using a redirect. But I get this error please what am I doing wrong.
Thanks in advance!!!
#views.py
class UserProfileView(View):
#method_decorator(login_required)
def get(self, request, username):
if request.user.username == username:
profile = get_object_or_404(UserExtended, user=request.user)
return render(request, 'registration/home.html', {'profile': profile})
else:
raise Http404
#login_required
def home_page(request):
return HttpResponseRedirect(
reverse('app:user_profile_view',
args=[request.user.username], current_app='app'))
So I changed the when Followed what #ShanWang said I got the error:
TypeError Exception Value: get() got an unexpected keyword argument 'username'
that as because my def get(self, request, username): was def get(self, request, user): so I changed that and
if request.user.username == user:
to
if request.user.username == username:
That did the trick

Django couldn't find urlpath

I tried to go 127.0.0.1:8000/poll/ it doesn't open, but I can go to /poll/20/result.
I just add other urls of poll and base url-> /poll/ stop to be opened.
Before I add to detail,result,vote function/url there were no problem to open index of poll.
Here are my codes:
In view.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, World. You are at the poll index.")
def detail(request, poll_id):
return HttpResponse("You are looking at poll %s" %poll_id)
def results(request, poll_id):
return HttpResponse("You are looing at the results of poll %s" % poll_id)
def vote(request, poll_id):
return HttpResponse("You are voting on poll %s" %poll_id)
In Polls/urls.py
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns( '',
url(r'^Ş', views.index, name='index'),
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<poll_id>\d+)/results/$', views.results,name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
In mysite/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'sign_ups.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
In your MySite.urls,
you have mentioned the polls url as polls and given the url as poll.
Change any one of those to get the app working.

Categories