I've been trying for days now to use get_absolute_url and whenever I click on the view on site button in the admin page or click submit on my add form page, I get this error:
NoReverseMatch at /admin/r/14/3/ (or NoReverseMatch at /blogs/add/)
Reverse for 'blog_detail' with arguments '()' and keyword arguments '{'pk': 3}' not found. 0 pattern(s) tried: []
If I go to mysite/blog/3 I do get the blog details page just fine as I have it set up. So I know the page works, but it seems like its not trying to find it since it says zero patterns tried.
Docs I'm looking at are:
https://docs.djangoproject.com/en/1.7/topics/class-based-views/generic-editing/
https://docs.djangoproject.com/en/1.7/ref/models/instances/#get-absolute-url
My code (what I think is relevant at least. If more info is needed let me know please)
blogs.models.py
from django.contrib.auth.models import User
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from audit_log.models.fields import CreatingUserField, CreatingSessionKeyField
class Blog(models.Model):
created_by = CreatingUserField(related_name = "created_categories")
created_with_session_key = CreatingSessionKeyField()
created_time = models.DateTimeField(auto_now_add=True)
blog_title = models.CharField('Blog Title', max_length=200)
short_description = models.TextField('Short Description', max_length=140)
blog_image = models.CharField('Image', max_length=200)
youtube_link = models.URLField('YouTube', max_length=200)
external_site_link = models.URLField('Website', max_length=200)
full_blog = models.TextField(max_length=10000)
def get_absolute_url(self):
return reverse('blog_detail', kwargs={'pk': self.pk})
def __unicode__(self):
return self.blog_name
urls.py
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^blogs/', include('blogs.urls', namespace='blogs')),
)
blogs.urls.py
from django.conf.urls import patterns, url
from blogs import views
urlpatterns = patterns('',
url(
regex=r'^$',
view=views.BlogListView.as_view(),
name='blog_list'
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BlogDetailView.as_view(),
name='blog_detail'
),
url(
regex=r'^add/$',
view=views.BlogCreate.as_view(),
name='blog_add'
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BlogUpdate.as_view(),
name='blog_update'
),
url(
regex=r'^(?P<pk>\d+)/delete/$',
view=views.BlogDelete.as_view(),
name='blog_delete'
),
)
blogs.views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
# Only authenticated users can access views using this.
from braces.views import LoginRequiredMixin
from .models import Blog
class BlogDetailView(DetailView):
model = Blog
class BlogListView(ListView):
model = Blog
class BlogCreate(LoginRequiredMixin, CreateView):
model = Blog
fields = ['blog title', 'short_description', 'blog_image',
'youtube_link', 'external_site_link', 'full_blog']
class BlogUpdate(LoginRequiredMixin, UpdateView):
model = Blog
fields = ['blog title', 'short_description', 'blog_image',
'youtube_link', 'external_site_link', 'full_blog']
class BlogDelete(LoginRequiredMixin, DeleteView):
model = Blog
success_url = reverse_lazy('blog_list')
you need to address url with namespace blogs like this:
return reverse('blogs:blog_detail', kwargs={'pk': self.pk})
Related
I am not getting redirected back to the homepage for some reason. I checked the creds to make sure it was correct and it was. I am not sure what's going on. I am not sure if I have to make it a button but I did the same thing before and it worked.
urls.py
from django.urls import path
from .views import pplCreate, pplCreate, pplList, pplDetail,pplUpdate,pplDelete,authView
urlpatterns = [
path('login/', authView.as_view(),name='login'),
path('', pplList.as_view(), name='pplLst'),
path('people/<int:pk>', pplDetail.as_view(), name='pplDet'),
path('people-update/<int:pk>', pplUpdate.as_view(), name='pplUpd'),
path('people-create/', pplCreate.as_view(), name='pplCre'),
path('people-delete/<int:pk>', pplDelete.as_view(), name='pplDel'),
]
views.py
from distutils.log import Log
import imp
from .models import People
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView
# Create your views here.
class authView(LoginView):
template_name = 'base/login.html'
fields = '__all__'
redirect_authenticated_user = True
def get_success_url(self):
return reverse_lazy('pplLst')
class pplList(ListView):
model = People
context_object_name = 'people'
class pplDetail(DetailView):
model = People
context_object_name ='cnd'
template_name = 'base/people.html'
class pplCreate(CreateView):
model = People
fields = '__all__'
success_url = reverse_lazy('pplLst')
class pplUpdate(UpdateView):
model = People
fields = '__all__'
success_url = reverse_lazy('pplLst')
class pplDelete(DeleteView):
model = People
context_object_name = 'cnd'
success_url = reverse_lazy('pplLst')
login.html
<h1>Login</h1>
<from method="POST">
{%csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</from>
In settings.py file, simply you can add this.
LOGIN_REDIRECT_URL = 'pplLst' #This is path name from urls
Add this in settings.py file, then you will get redirected to home page
Just remove auth view from views and do following way:
In urls.py:
from django.contrib.auth import views as auth_views
path('login/',auth_views.LoginView.as_view(template_name='base/login.html'),name='login'),
In my app I want a user to upload an image and the image's file name will become same as the title of the form.
For example,
user uploads image xyz.jpg, while `title = newfile. After that the image will now be newfile.jpg.
This is my code below:
#forms
class PostForm(forms.modelForm):
class Meta:
model = Post
fields = ['title', 'cover']
#urls
from django.urls import path
from .views import HomePageView, CreatePostView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('post/', CreatePostView.as_view(), name='add_post')
]
#views
from django.shortcuts import render
from django.views.generic import ListView, CreateView
from django.urls import reverse_lazy
from .forms import PostForm
from .models import Post
class HomePageView(ListView):
model = Post
template_name = 'home.html'
class CreatePostView(CreateView): # new
model = Post
form_class = PostForm
template_name = 'post.html'
success_url = reverse_lazy('home')
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'
How do you use Django Rest Framework to create an API when the data model has a composite key consisting of two fields? Background: I am trying to make a REST api for a data model (sample data row below- first two entries make the composite key). I am able call upon my data with date field but am getting errors when I try to use the second string field to return a single record.
'2015-05-06','INTC','31.93','32.79','32.50','32.22','31737537'
I am trying to make the api url structure like so:
localhost/api/v1/yyyy-mm-dd/'char'
localhost/api/v1/2015-05-07/AAPL
serializers.py
from rest_framework import serializers
from .models import Stocksusa, Optionsusa
from rest_framework.reverse import reverse
class StocksUsaSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField('get_stock_usa_url')
def get_stock_usa_url(self, obj):
values = [obj.Trade_Date, obj.Ticker]
composite_key_url = "http://0.0.0.0:9978/api/v1/stocksusa/{}/{}".format(*values)
return composite_key_url
class Meta:
model = Stocksusa
fields = ('Trade_Date', 'Ticker', 'PxMin', 'PxMax', 'PxOpen', 'PxClose', 'Volume', 'url')
views.py
from django.shortcuts import render
from rest_framework import authentication, permissions, viewsets, filters
from .models import Stocksusa
from .serializers import StocksUsaSerializer
from django.contrib.auth import get_user_model
User = get_user_model()
class DefaultsMixin(object):
authentication_classes = (
authentication.BasicAuthentication,
authentication.TokenAuthentication,
)
permission_classes = (
permissions.IsAuthenticated,
)
paginate_by = 25
paginate_by_param = 'page_size'
max_paginate_by = 100
filter_backends = (
filters.DjangoFilterBackend,
filters.SearchFilter,
filters.OrderingFilter,
)
class StocksUsaViewSet(DefaultsMixin, viewsets.ReadOnlyModelViewSet):
queryset = Stocksusa.objects.all()
serializer_class = StocksUsaSerializer
app/urls.py
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter(trailing_slash=False)
router = DefaultRouter()
router.register(r'stocksusa', views.StocksUsaViewSet)
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls import include, url
from rest_framework.authtoken.views import obtain_auth_token
from FinDataUsa.urls import router
from FinDataUsa.views import StocksUsaViewSet as stockview
urlpatterns = patterns('',
url(r'^api/token/', obtain_auth_token, name='api-token'),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v2/', include(router.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^docs/', include('rest_framework_swagger.urls')),
)
The problem lies into the fact that the DefaultRouter uses the id lookup_field of your model for getting the object you want: For example this works:
GET localhost/api/v1/stocksusa/1
In order to provide extra parameters you need to hand-craft the urls like this:
url(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})/(?P<code>\w+)$',
StocksUsaViewSet.as_view(),
name='stocks_detail'
),
The year month day code parameters are passed into your view with the kwargs dictionary:
self.kwargs['year']
self.kwargs['month']
self.kwargs['day']
self.kwargs['code']
On your get_object method you need to do something like that:
def get_object(self, queryset=None):
try:
date= datetime.date(
year=int(self.kwargs['year']),
month=int(self.kwargs['month']),
day=int(self.kwargs['day']),
)
except ValueError:
raise Http404
stock= get_object_or_404(Stocksusa, Ticker=self.kwargs['code'], Trade_Date=date)
return stock
Then you will have access to your object:
when i acess to my url i only get: <django.forms.fields.ChoiceField object at 0x026D1CD0>
i want the number Choicefield
i have the folowing models.py in my app:
from django.db import models
from django.forms import ModelForm
class Zonas(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class ZonasForm(ModelForm):
class Meta:
model = Zonas
I guess the problem is in my views.py:
from django import forms
from testApp.models import Zonas
from django.shortcuts import render_to_response
def menuForm (request):
z = list (Zonas.objects.all())
numbers = forms.ChoiceField(z)
return render_to_response('hello.html', {'numbers':numbers})
menuForm is used on my urls.py as:
from django.conf.urls import patterns, include, url
from testApp.views import menuForm
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^hello/$', menuForm ),
)
my html page, is as simple as it can be:
<html>
<body>
{{numbers}}
</body>
</html>
Any help appreciated
Your url for the page is not correct, change it to
url(r'^hello/$', menuForm),
As mentioned in the doc, it is of the form
(regular expression, Python callback function [, optional_dictionary [, optional_name]])
Also, change definition of the view function as
def menuForm (request):
....