so i'm following the Django project in the textbook "Python crash course 2nd ed" and i'm into the mapping URLS section for those who know, and when i try my system cant seem to runserver anymore, i'm encountering the following error: AttributeError: module 'django.db.models' has no attribute 'BigAutoField'
if anyone can help, it would be great, thanks already. i'm fairly new to django and trying my way around it but i don't really know what or where to find the error..
it worked actually fine before i added the two urls.py:
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('learning_logs.urls'), name='learning_logs'),
]
and
"""Defines url patterns for learning_logs."""
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# Home page.
path('', views.index, name='index'),
]
the models.py is
from django.db import models
# Create your models here.
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""return a string representation of the model"""
return self.text
class Entry(models.Model):
"""something specific learned about a topic"""
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""return a string representation of the model"""
if len(self.text) >= 50:
return f"{self.text[:50]}..."
else:
return "..."
It is the version you have to change.
Django 1.8 does not have BigAutoField.
Here's url to Django 1.8 doc
Related
Hi I am trying to create a blog using the Django webframework.
I get the error,
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
The urls.py is given below,
from django.urls import path
from .views import (
BlogListView,
BlogDetailView,
BlogCreateView,
BlogUpdateView,
)
urlpatterns = [
path('post/<int:pk>/edit', BlogUpdateView.as_view(), name='post_edit'),
path('post/new/', BlogCreateView.as_view(), name='post_new'),
path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'),
path('', BlogListView.as_view(), name='home'),
]
The models.py is given below,
from django.db import models
from django.urls import reverse
# Create your models here.
MAX_LENGTH = 500
class Post(models.Model):
title = models.CharField(max_length=MAX_LENGTH)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE,)
body = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.id)])
Where am I going wrong?
From your indentation it looks as if your methods on the Post class are instead in the global scope. They should have the same indendation as the title, author and body field (i.e. 4 spaces/1 tab).
I am following this tutorial to create a video uploader in my Django project and have run into this error:
..src/video/views.py", line 9, in showvideo
videofile= lastvideo.videofile
AttributeError: 'NoneType' object has no attribute 'videofile'
I'm sure I am missing something obvious and have been looking for the answer for a while now. Would be grateful for any help.
views.py
from django.shortcuts import render
from .models import VideoUpload
from .forms import VideoForm
def showvideo(request):
lastvideo= VideoUpload.objects.last()
videofile= lastvideo.videofile
form= VideoForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
context= {'videofile': videofile,
'form': form
}
return render(request, 'video.html', context)
forms.py
from django import forms
from .models import VideoUpload
class VideoForm(forms.ModelForm):
class Meta:
model = VideoUpload
fields = ["name", "videofile"]
models.py
from django.db import models
class VideoUpload(models.Model):
name= models.CharField(max_length=500)
videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")
def __str__(self):
return self.name + ": " + str(self.videofile)
from django.conf import settings
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from video.views import (
showvideo,
)
urlpatterns = [
path('showvideo', showvideo, name='showvideo'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
FYI I updated the name of the model to 'VideoUpload' vs the tutorial.
There is no last_video record in your database. To prevent this from erroring out in such and instance, you could change the line: videofile= lastvideo.videofile into
videofile = lastvideo.videofile if lastvideo else None
This will prevent an error from being thrown. Alternatively you could put the whole bit in a try/except block.
I followed the qblog tutorial, using python 2.7.10 and django 1.9.5.
When i enter the admin's blog interface, and clicked add blog entry, then it shown me below:
TemplateDoesNotExist at /admin/blog/entry/add/
django_markdown/editor_init.html
but i have installed django-markdown already. I would like to show the code below:
models.py:
class Entry(models.Model):
title = models.CharField(max_length=200)
body = MarkdownField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("entry_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
admin.py:
from django.contrib import admin
from . import models
from django_markdown.admin import MarkdownModelAdmin
from django_markdown.widgets import AdminMarkdownWidget
from django.db.models import TextField
class EntryAdmin(MarkdownModelAdmin):
list_display = ("title", "created")
prepopulated_fields = {"slug": ("title",)}
# Next line is a workaround for Python 2.x
formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}
admin.site.register(models.Entry, EntryAdmin)
admin.site.register(models.Tag)
qblog/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
import settings
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include("django_markdown.urls")),
url(r'^', include('blog.urls')),
)
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
You need to add the editor_init.html file in your project.
If your project root is project/ there should be a directory called templates in there. If that directory does not exist, create it (so the path would be project/templates).
Place the editor_init.html file in this directory and everything should work.
You can find more information about setting up templates here and in the django docs.
I currently cannot log into my admin in Django, I get a 404 page.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
No Blog entry found matching the query
UPDATE #3
Last Updated: Dec 17, 10 AM
Status: Still unresolved, could use some help
I've updated the error message at the top of this post, and yes, the error message is short.
I've included the url.py for the actual project, in addition to the app called blog.
Fixed the migrations being out of sync
There is no longer an error in the Terminal
The problem might lie somewhere in models, views or urls.py
THE SUSPECTS
This code snippet relates to "startproject takehome"
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include("django_markdown.urls")),
url(r'^', include('blog.urls')),
)
settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'django_markdown',
)
These three code snippets relate to the app called "Blog"
Urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.BlogIndex.as_view(), name="list"),
url(r'^(?P<slug>\S+)$', views.BlogDetail.as_view(), name="detailed"),
)
Models.py
from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
class FullArticleQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class FullArticle(models.Model):
title = models.CharField(max_length=150)
author = models.CharField(max_length=150)
slug = models.SlugField(max_length=200, unique=True)
pubDate = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
category = models.CharField(max_length=150)
heroImage = models.CharField(max_length=250, blank=True)
relatedImage = models.CharField(max_length=250, blank=True)
body = models.TextField()
publish = models.BooleanField(default=True)
gameRank = models.CharField(max_length=150, blank=True, null=True)
objects = FullArticleQuerySet.as_manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("FullArticle_detailed", kwargs={"slug": self.slug})
# def random(self):
# return self.get_queryset().order_by('?').values('title','author','heroImage','body').first()
class Meta:
verbose_name = "Blog entry"
verbose_name_plural = "Blog Entries"
ordering = ["-pubDate"]
views.py
from django.views import generic
from . import models
# Create your views here.
class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"
# paginate_by = 2
class BlogDetail(generic.DetailView):
model = models.FullArticle
template_name = "detailed.html"
# random = models.FullArticle.objects.order_by('?').values('title','author','heroImage','body').first()
There is definitely a problem with your schema as a result of migrations. There are a few things you can try.
Edit: Since I don't see the field order in your current models.py, it is probably best to go with option 1.
Option 1: Flush and resync your database. (Or even better, delete your database and resync - easy if using SQLite3). Find db.sqlite3 in your blog/ directory and delete it. Warning: You will lose all data if you do this. Once that is done, run ./manage.py syncdb and don't worry about migrations (especially if running Django 1.7, which you are).
Option 2: Remove the field causing the error (if possible), run a migration, then add it back and re-run the migration.
Option 3: Find all orders and delete whichever two are not unique, then re-run the migration.
Update: ok the migration problem has been moved out of the way.
Update 2: ok so it isn´t lacking the admin url pattern
What is the case with your importing the blog urls in your main urls.py? You match everything that falls through the patterns r'^admin/' and r'^markdown/' as a blog entry.
Now your request is "/admin", and because of the lacking of a "/" (slash) at the end, in stead of being matched against the first pattern, it is matched against the last one: r'^(?P\S+)$'. So now it looks for blog entry with a slug called "admin", and fails to find one, and hence returns 404 with a very clear discription. (next time don´t hesitate to include that in the question :)
I expect also that requesting "/admin/" will result in an admin page, because it would get matched against r'^admin/', because of the trailing /
better practice is to avoid conflicts between main urls and app specific urls by sub-url'ing your blogposts somewhat like this:
url(r'^blog/', include('blog.urls', namespace="blog")),
https://docs.djangoproject.com/en/dev/intro/tutorial03/#namespacing-url-names
before update:
Maybe you tried to make the order field unique after having non-unique values in it. Have you tried removing the whole database and rebuilding it? That would be my first suggestion.
It seems like there are some quirks in sqlite, I never use it basically. I would suggest also to try using something more mature like postgresql or mysql.
I think I done everything correct but I don't know why it doesn't work. When I try to reach a page I get error "Page not found (404)".
So, this all products page works 127.0.0.1:8000/products/ but when I try to visit single product page 127.0.0.1:8000/products/audi I get error that it's not found...
So, maybe you what's wrong here?
Thank you.
Page not found (404)
Request Method: GET
Request URL: http://link/products/audi
Using the URLconf defined in ecommerce.urls, Django tried these URL patterns, in this order:
^static/(?P<path>.*)$
^media/(?P<path>.*)$
^admin/doc/
^admin/
^products/ ^$ [name='products']
^products/ ^$(?P<slug>.*)/$
^contact/ [name='contact_us']
The current URL, products/audi, didn't match any of these.
Main project urls.py:
from django.conf import settings
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT
}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT
}),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^products/', include('products.urls')),
url(r'^contact/', 'contact.views.contact_us', name='contact_us'),
)
Products app urls.py:
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('products.views',
url(r'^$', 'all_products', name='products'),
url(r'^$(?P<slug>.*)/$', 'single_product'),
)
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, get_object_or_404
from .models import Product
def all_products(request):
products = Product.objects.filter(active=True)
return render_to_response('products/all.html', locals(), context_instance=RequestContext(request))
def single_product(request, slug):
product = get_object_or_404(Product, slug=slug)
return render_to_response('products/single.html', locals(), context_instance=RequestContext(request))
models.py
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=220)
description = models.CharField(max_length=3000, null=True, blank=True)
price = models.DecimalField(max_digits=1000, decimal_places=2, null=True, blank=True)
slug = models.SlugField()
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return self.title
class Meta:
ordering = ['title',]
class ProductImage(models.Model):
product = models.ForeignKey(Product)
description = models.CharField(max_length=3000, null=True, blank=True)
image = models.ImageField(upload_to='product/images/')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return self.image
Your URL pattern has an extra $ at the beginning, so it can never match anything:
url(r'^$(?P<slug>.*)/$', 'single_product')
This should be:
url(r'^(?P<slug>.*)/$', 'single_product')
This still requires a trailing slash, which is the normal pattern. With that corrected, your URL should be /products/audi/. You don't show the context in which that URL is created, but this is one example of why it's a good idea to use Django's url reversal to build URLs if at all possible. That would look something like this, in Python code (for instance, possibly in a get_absolute_url method on the model:
reverse('single_product', kwargs={'slug': someproduct.slug})
Or like this, in a template:
Django 1.5:
{% url 'single_product' someproduct.slug %}
Django 1.4 and earlier:
{% url single_product someproduct.slug %}
You have a typo:
url(r'^$(?P<slug>.*)/$', 'single_product'),
Note this $ just after ^, in regexp it states for a string end. Replace with
url(r'^(?P<slug>.*)/$', 'single_product'),