I am working through this tutorial on rapid site development with Django.
I have followed it exactly (as far as I can see), but get the following error when I try to view the index page:
NameError at /name 'views' is not defined
Exception location: \tuts\urls.py in <module>, line 12
Here's urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name='index'),
)
Here's views.py:
from django.shortcuts import render
# Create your views here.
def index(request):
items = Item.objects.order_by("-publish_date")
now = datetime.datetime.now()
return render(request,'portfolio/index.html', {"items": items, "year": now.year})
And here's models.py:
from django.db import models
# Create your models here.
class Item(models.Model):
publish_date = models.DateField(max_length=200)
name = models.CharField(max_length=200)
detail = models.CharField(max_length=1000)
url = models.URLField()
thumbnail = models.CharField(max_length=200)
I also have a basic index.html template in place. From looking around I think I need to import my view somewhere.
But I'm completely new to Django so I have no clue. Any ideas?
The error line is
url(r'^$', views.index, name='index'),
#----------^
Here views is not defined, hence the error. You need to import it from your app.
in urls.py add line
from <your_app> import views
# replace <your_app> with your application name.
from .views import index
here we have to import views model classes on urls model so above sentence import your view model class on urls model.
add this code in urls.py
If you are using rest_framework in django then import:
from rest_framework import views
Related
I'm on this page: Filling the details
The link to the orange image is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg
When I'm pressing 'save' it gives me this: Error message
Couldn't understand the issues I tried various ways to solve them like take another picture and re-run the server. From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20
I do not know what this double space between 'user' and 'old' means and I really need help with this, I'm stuck on this from Sunday:
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=2083)
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello World')
def new(request):
return HttpResponse('New Products')
admin.py
from django.contrib import admin
from .models import Product
admin.site.register(Product)
pyshop - urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("products/", include('products.urls'))
]
products - urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('new', views.new)
]
Hey dont use Charfield with specific length in image field. Use either UrlField or an ImageField in models.
Then try to add from admin panel.
And also run makemigrations and migrate command.
I'm in this page:
Filling the details
The ling is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg
When I'm pressing 'save' it gives me this: Error message
Couldn't understand the issues I tried various ways to solve it like take another picture and re-run the server.
From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20
edit: adding code.
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=2083)
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello World')
def new(request):
return HttpResponse('New Products')
admin.py
from django.contrib import admin
from .models import Product
admin.site.register(Product)
pyshop - urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("products/", include('products.urls'))
]
products - urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('new', views.new)
]
Django is not able to find the table
main.auth_user__old
observe the double underscore between user and old. Are you sure it is correct?
Also, please upload your code.
I am following this video trying to learn Django. I have completed this tutorial and I had the same problem even when I followed the code to a T.
I am trying to get information about a model object displayed on the web-page when entering the id of the object directly in the url like http://localhost:8000/app/item/1/ or http://localhost:8000/app/item/2/ as the video shows (7:30 into the video). But when I try, I get this error:
Original code from video:
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Book
def index(request):
return HttpResponse('Hello, world!')
def book_by_id(request, book_id):
book = Book.objects.get(pk=book_id)
return HttpResponse(f"Book: {book.title}, published on {book.pub_date}")
models.py:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
urls.py:
from django.utils import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('book/<int:book_id>', views.book_by_id, name='book_by_id'),
]
My code:
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Item
def index(request):
return HttpResponse('Hello, world!')
def item_by_id(request, item_id):
item = Item.objects.get(pk=item_id)
return HttpResponse(f"Item: {item.title}, published on {item.datetime_found}")
models.py:
from django.db import models
from django.utils.timezone import now
class Item(models.Model):
title = models.CharField(max_length=200) # Short description of the item
datetime_found = models.DateTimeField(default=now, blank=True) # Date and time of when the item was found
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('item/<int:item_id>', views.item_by_id, name='item_by_id'),
]
Project-level urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('myapp.urls')),
path('admin/', admin.site.urls),
]
What am I not getting right about the GET-request? I feel like the changes I've made are minimal. And I have migrated everything correctly. (I think)
Use this
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('app/', include('myapp.urls')),
path('admin/', admin.site.urls),
]
or you can remove 'app' from your url and make it look like this http://127.0.0.1:8000/item/1
look at url pattern of yours and the original.
path('item/<int:item_id>', views.item_by_id, name='item_by_id'),
is yours
path('book/<int:book_id>', views.book_by_id, name='book_by_id'),
is the original
I got an error.
And i have no ideia how to fix it, take a look, this is the error:
TypeError: as_view() takes 1 positional argument but 2 were given
This as you can see is the code of my "model.py" page.
from django.db import models
from django.contrib.gis.db import models
class RoadsLines(models.Model):
gid = models.IntegerField()
geom = models.MultiLineStringField()
def __str__(self): # __unicode__ on Python 2
return '%s %s' % (self.gid, self.geom)
This as you can see is the code of my "views.py" page.
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from rest_framework import generics
from world.models import RoadsLines
from world.serializers import RoadsLinesSerializer
class ListCreateRoadsLines(generics.ListCreateAPIView):
queryset = RoadsLines.objects.all()
serializer_class = RoadsLinesSerializer
This as you can see is the code of my "urls.py" page.
from django.conf.urls import url, include
from rest_framework import routers, serializers, viewsets
from world import views
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'Roads', views.ListCreateRoadsLines)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api/', include('rest_framework.urls', namespace='rest_framework'))
]
What am I doing wrong?
Thank you in advance!
ListCreateRoadsLines is a view, not a viewset. You should include it in your url patterns, instead of trying to register it:
urlpatterns = [
url(r'^Roads$', views.ListCreateRoadsLines.as_view()),
url(r'^', include(router.urls)),
url(r'^api/', include('rest_framework.urls',
namespace='rest_framework'))
]
I have chrono/chrono/templates/requests_app/request_list.html which gets loaded when url(r'^$', BookListView.as_view()), gets hit. BookListView.as_view() is class BookListView(ListView): model = Request. When in Django is it being told to look for chrono/chrono/templates/requests_app/request_list.html?
For instance, I can change the name request_list.html to foo_request_list.html and it will say error request_list.html not found. So I am trying to find where it is coded to look for request_list.html. I looked in settings/base.py and there was no mention of request_list.html.
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView, ListView
from requests_app.views import BookListView
from django.contrib.auth.views import login
from requests_app.forms import LoginForm
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# url(r'^$', TemplateView.as_view(template_name='base.html')),
url(r'^$', BookListView.as_view()),
url(r'^login/$', login, {'authentication_form': LoginForm}, name='login'),
# Examples:
# url(r'^$', 'chrono.views.home', name='home'),
# url(r'^chrono/', include('chrono.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
from django.views.generic.base import TemplateView, RedirectView
from django.http import HttpResponse
from django.views.generic import ListView
from requests_app.models import Request, Region
from django.core.urlresolvers import reverse
class BookListView(ListView):
model = Request
This happens somewhere in code that is included by the import of django.views.generic.ListView. In generic/list.py, MultipleObjectTemplateResponseMixin is where the filename is finally put together.
The code builds the template like so
Folder prefix is the app name that this ListView is in
The part before _list.html is inferred by checking model.__name__, which is Request.__name__ in your example and will be Request by default and then lowercasing that.
_list is specified by ListView
.html is in MultipleObjectTemplateResponseMixin
If you don't like the file name it is giving you and you want to keep your app name as well as the name of the class you are specifying as your model you can override the above behavior in your BookListView
class BookListView(ListView):
model = Request
template_name = "books/foo_request_list.html"
https://docs.djangoproject.com/en/1.6/topics/class-based-views/generic-display/#viewing-subsets-of-objects
This section deals with other things but they show overriding the template name in their example.