I have been doing a project but I can't post a request to the edit.html and details.html.
This is my code:
dog_app/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index),
url(r'^create$',views.create),
url(r'^edit/(?P<id>\d+)$', views.edit),
url(r'^(?P<id>\d+)/details/$', views.details),
]
views.py
from django.shortcuts import render,redirect
from models import Dog
def edit(request, id):
dog=Dog.objects.get(id=id)
context={'dog': dog}
return render(request,'dog_app/edit.html',context)
def details(request, id):
dog=Dog.objects.get(pk=id)
context={"dog": dog}
return render(request,'dog_app/details.html',context)
The error:
Related
I have two apps in my Django project:basket and store. In root url files I configured the urls.py like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
store/urls.py:
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.all_products, name='all_products'),
path('<slug:slug>/', views.product_detail, name='product_detail'),
path('category/<slug:category_slug>/',
views.category_list, name='category_list')
]
basket/urls.py:
from django.urls import path
from . import views
app_name = 'basket'
urlpatterns = [
path('', views.basket_summary, name='basket_summary'),
path('add/', views.basket_add, name='basket_add'),
]
I am getting an error:
Page not found(404)
Request Method:GET
Request URL:http://127.0.0.1:8000/basket/
Raised by:store.views.product_detail
this is my store/views.py:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
context = {
'product': product,
}
return render(request, 'store/products/detail.html', context)
please help me solve this problem i've been stuck on this for a long time.
Try this way if you want to avoid 404 error:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
try:
product = Product.objects.get(slug=slug, in_stock=True)
context = {
'product': product,
}
except Product.DoesNotExist:
raise ValidationError('Product Does not exist ')
return render(request, 'store/products/detail.html', context
)
In Django REST Framework, I'm trying to add an API root to a views.py that has class based views.
Error:
$ http http://127.0.0.1:8000/api/
Error - django.urls.exceptions.NoReverseMatch: Reverse for 'SnippetListView' not found. 'SnippetList' is not a valid view function or pattern name.
backend/views.py
from backend.models import *
from backend.serializers import *
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
#api_view(['GET'])
def api_root(request, format=None):
return Response({
'snippets': reverse('SnippetList')
# 'snippets': reverse('SnippetListView')
# 'snippets': reverse('snippet-list')
# 'snippets': reverse('snippet_list')
})
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
backend/urls.py
from backend import views
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('', views.api_root),
path('snippets/', views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
]
Docs:
https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/#creating-an-endpoint-for-the-highlighted-snippets
You need to name the view url in order to use the reverse.
#urls.py
path('snippets/', views.SnippetList.as_view(), name='snippet-list'),
#views.py
'snippets': reverse('snippet-list', request=request, format=format)
The tutorial did not originally give names to the urls of the class based views.
This is my views.py :
from django.http import Http404
from django.shortcuts import render
from .models import Album
def index(request):
all_albums = Album.objects.all()
return render(request, 'music/index.html', {'all_albums': all_albums})
def detail(request, album_id):
try:
album = Album.objects.get(pk=album_id)
except Album.DoesNotExist:
raise Http404("Album does not exist")
return render(request, '/music/detail.html', {'album': album})
This is my music\urls.py :
from django.conf.urls import url
from . import views
urlpatterns = (
url(r'^$', views.index, name='index'),
url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'),
)
When I am running this code, I am getting the error as :
As stacktrace said you are trying to open http://127.0.0.1/music/id/1 page not http://127.0.0.1/music/1 but there is no such urp pattern in your urls.py. You need try to open http://127.0.0.1/music/1 or add new pattern:
url(r'^id/(?P<album_id>[0-9]+)/$', views.detail, name='detail')
to see http://127.0.0.1/music/id/1 page.
I am following this tutorial. At the moment I am at this point but when I start my server with python manage.py runserver 0.0.0.0:8000 and open the url in my browser, I receive following Error:
name 'IndexView' is not defined
This is my urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls import patterns
from rest_framework_nested import routers
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
I don't know how to solve this problem, since I never saw myself even declaring this IndexView somewhere. It would be awesome if you guys could give me some suggestions on this one.
Edit:
my views.py
from django.shortcuts import render
# Create your views here.
from rest_framework import permissions, viewsets
from authentication.models import Account
from authentication.permissions import IsAccountOwner
from authentication.serializers import AccountSerializer
class AccountViewSet(viewsets.ModelViewSet):
lookup_field = 'username'
queryset = Account.objects.all()
serializer_class = AccountSerializer
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
if self.request.method == 'POST':
return (permissions.AllowAny(),)
return (permissions.IsAuthenticated(), IsAccountOwner(),)
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
Account.objects.create_user(**serializer.validated_data)
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
return Response({
'status': 'Bad request',
'message': 'Account could not be created with received data.'
}, status = status.HTTP_400_BAD_REQUEST)
You have to create that IndexView and import it in your urls.py.
Currently the interpreter complains since in the urls.py IndexView is unknown.
To create a new view you should create a new class in views.py, something like:
from django.views.generic.base import TemplateView
class IndexView(TemplateView):
template_name = 'index.html'
ps: please read the official Django docs, which is very good!
The IndexView class is in the boilerplate project's views file.
C:\...\thinkster-django-angular-boilerplate-release\thinkster_django_angular_boilerplate\views
Copy and paste that content into your project's views file.
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic.base import TemplateView
from django.utils.decorators import method_decorator
class IndexView(TemplateView):
template_name = 'index.html'
#method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(IndexView, self).dispatch(*args, **kwargs)
in your urls.py
from .views import IndexView
url('^.*$', IndexView.as_view(), name='index'),
(.views or yourProject.views)
in your views.py
do what daveoncode wrote
I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.