Django Admin Site not working - django

I'm hosting a Django site through mod_wsgi and WAMP with Python 2.7. On my admin site the Users, Groups and Sites sections all have Add and Change buttons. While there is a section each for both of my own custom models, Feedpost and Newspost, they have no buttons at all and there is no way to add or change them.
I believe this change came about when I switched from using the Django internal testing server to using WAMP. Does anyone know what's causing this and how to get my Add and Change buttons back?
EDIT:
Here's one of the two models:
from django.db import models
from django.contrib import admin
class FeedPost(models.Model):
title = models.CharField(max_length=50)
text = models.CharField(max_length=5000)
date = models.DateTimeField('Date Published')
def __unicode__(self):
return self.title
admin.site.register(FeedPost)
The other is nearly exactly the same.
It turns out that using the Django development server localhost:8000/admin insists on going to my site's homepage and I can't access the admin site at all.
Also I think this is going to turn out to be the problem because I haven't got an admin.py file anywhere in my project...

These need to be in the admin.py file for starters.
from django.contrib import admin
admin.site.register(FeedPost)

Related

Detect timezone in django admin

I'm working in a project with a Django backend (only backend and a default admin portal, no site) where the admin portal is used by people both in Europe and US.
Because of this, it's important that the datetimes in the admin portal are displayed in the local timezone of whomever is using it.
For example, in some models I display the creation date of instances. I need those dates to be displayed in the timezone of whomever accesses the admin portal.
I've searched for solutions to achieve this (such as suggested in the docs, but also this package) but all the solutions I've found seem to be made for detecting the timezone of end-users accessing a custom website, not the default admin portal.
I'm using Django 2.2 and Python 3.8.
One of the methods to achieve this is by using a custom field in Django ModelAdmin.
References for:
custom_admin_field
get_local_time
from django.contrib import admin
from django.db import models
class AnItem(models.Model):
title = models.CharField(max_length=150)
creation_date = models.DateField()
#admin.display(description='Local Time')
def local_time_of_creation(self):
local_time = write_logic_to_get_the_local_time_here
return local_time
class AnItem(admin.ModelAdmin):
list_display = ('name', 'local_time_of_creation')

Using Django for a very simple website: is it worth it?

Hello everyone how is it going?
I've just started using Django recently, and I've started getting my head around it; I need to build a website about cars, with two major APPS:
CarsCatalogue;
News Section;
I find the fact that I can manage the news from the admin panel extremely useful. I have created the typical model:
class Post(models.Model):
title = models.CharField(max_length = 140)
date = models.DateTimeField()
body = models.TextField()
def __str__(self):
return self.title
With the urls.py as follows
url(r'^(?P<pk>\d+)$', DetailView.as_view(
model = Post,
template_name="news/post.html"))
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
template_name="news/news.html")),
This is great! I can manage the News app Extremely easyly from the admin panel. Now I have a page for each news: news/1; news/2 etc etc;
But when i go down to the CarsCatalogue, and I would really need to simplify my life because I have plenty of cars with a personal page each to add, I am instead finding myself needing to modify the urls.py for each car I need to add, and it seems I have to modify the views.py for each car -I am using render- am I right?
I mean, does it make sense to have a Views.py with one hundred different functions calling one hundred pages?
And then if I want to create a list with all the urls of the CarCatalogue, having to write every link one by one?
Is this the way to use Django in this case?
I would create another "news-style" APP for CarsCatalogue, that would be so much more easy for me to manage through the Admin Panel, but I need each url to show the car name, like: CarsCatalogue/Seat-Ibiza and not like CarsCatalogue/1.
Maybe I can do something like the news APP, but changing the way urls are generated and shown?
I am asking you all of this after I read the documentation and several Google topics and other resources;
I hope you guys will be able to clear the fog around my head;
With all the Respect such a community deserves,
Sincerely,
-oKi
EDIT n*1
It's been 3 hours of reading, trying, modifying, erasing, trying again.
I read a lot of stuff, but at the same time I got pheraps even more confused, because I found so many things while looking for how to "slug"ify the urls (that is indeed what I was looking for [now I can indeed use the admin panel to do what I wanted!] thanks) that I ended up mixing a lot of stuff. So, using the NEWS application, what I have done so far:
python3.5 manage.py flush, makemigrations, migrate, createsuperuser
I modified the news/models.py, so that it now looks like this:
from django.db import models
from django.template.defaultfilters import slugify
class Post(models.Model):
title = models.CharField(max_length = 140)
date = models.DateTimeField()
body = models.TextField()
slug = models.SlugField(title, max_length=100, unique=True)
def __str__(self):
return self.title
def slug(self):
return slugify(self.title)
I modified the news/admin.py, so that it now looks like this:
from django.contrib import admin
from news.models import Post
admin.site.register(Post)
class NewsAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": (Post.slug)} <!-- that seems makes sense looking at the Model - I also tryed {"slug": (title,)}, {"slug": (Post.title)}-->
I modified the news/urls.py, so that it now looks like this:
from django.conf.urls import url
from django.views.generic import ListView, DetailView
from news.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
template_name="news/news.html")),
url(r'^(?P<slug>[\w-]+)$', DetailView.as_view(
model = Post,
template_name="news/post.html")),
]
then I give:
python3.5 manage.py runserver
and it runs with no problem.
So I go to /admin, I create a new post, it creates it...
But then what happens?
It still uses the old "paradigm" to generate the url, including the old keys(id's) it was using before I erased the client... so... what I expected to be something like mysite/news/new-human-level-urld-news
turns out to be mysite/news/11.
LOL :D and, luckily, the browser gives me also an error...
"FieldError at /news/11
Cannot resolve keyword 'slug' into field. Choices are: body, date, id, title"
at the moment I can't find an answer, I find so much stuff that I just don't know how to mix things up. I will keep searching. Help is appreciated! Thanks for now!!! :D
According to my understanding to your problem, what you need is not to create a view function for every car you have.
Indeed, you need to create 1 template (html page) that describes your CarsCatalogue, where all the CarsCatalogues have the same structure with different information. Then the user chooses one CarsCatalogue, let's say from a dropdown control and then you load the data from your database and show your results in the template.
In order to achieve this, have a look on the following topics:
Django forms. And in order to get your data from the database, you need the the id for example to be passed in the url, you can see this answer how to pass an id in django url or from the official website URL Dispatcher.
In few words, django is a simple way to do your website and definitely no need to rewrite your code several times.
NO THERE IS NO NEED TO CREATE MULTIPLE URLS.
From what I understood, you want a catalogue for each car.
Just create a view from where you display the names of all your cars.
Then when you click on a car, make a get request to another view function in the get request pass your selected car details. Now comes the use on Django Templates. Create a Django template for your catalogue, pass the car specific data to it.
You need to read about Django Templates , I think Django templates is something that will solve your problem.
I think the thing you're missing is that the parameter in the URL can be anything, not just a numeric URL. If it's a string, we call that a slug, and the Django admin will automatically create a slug from the fields in your model if you set the prepopulated_fields option.
Then, you can use that slug in the URL:
url(r'^(?P<slug>[\w-]+)$', DetailView.as_view(
model = Car,
template_name="news/car.html"))
and Django will use that field instead of the ID to find the right content to display.
I found a way to fix my problem.
Even though I started off by asking about the CARS Catalogue, I will explain what I did using the NEWS APP instead, as the logic is the same and as that is the APP I have modified in the first EDIT of my post.
Inside the Templates, have a "news.html" page to render the list of all the Post, and a "post.html" to render every single Post.
The following is part of the procedure on how to set an APP that you can manage directly from the ADMIN PANEL, and that uses the SLUG field as URL.
models.py:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length = 140)
body = models.TextField()
slug = models.SlugField(unique=True)
def __str__(self):
return self.title
admin.py:
from django.contrib import admin
from news.models import Post
class PostAdmin(admin.ModelAdmin):
model = Post
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Post, PostAdmin)
urls.py:
from django.conf.urls import url
from django.views.generic import ListView, DetailView
from news.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all(),
template_name="news/news.html")),
url(r'^(?P<slug>[\w-]+)$', DetailView.as_view(
queryset=Post.objects.all(),
model = Post,
template_name="news/post.html")),
]
I hope that can be useful to somebody.
Jeez you gotta study hard to use this Framework :D
Thanks everybody for the support, c ya :)

Django: New class added in model.py not showing in admin site

I'm a front-end dev struggling along with Django. I have the basics pretty much down but I've hit at wall at the following point.
I have a site running locally and also on a dev machine. Locally I've added an extra class model to an already existing app, registered it in the relevant admin.py and checked it in the settings. Locally the new class and relevant fields appear in admin but when I move this all to dev they're not appearing. The app is called 'publish'.
My method was as follows:
Created the new class in the publish > models.py file:
class Whitepaper(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=100, blank=True)
pub_date = models.DateField('date published')
section = models.ForeignKey('Section', related_name='whitepapers', blank=True, null=True)
description = models.CharField(max_length=1000)
docfile = models.FileField(upload_to="whitepapers/%Y/%m/%d", null=True, blank=True)
Updated and migrated the model with South using:
python manage.py schemamigration publish --auto
and
python manage.py migrate publish
Registered the class in the admin.py file:
from models import Section, Tag, Post, Whitepaper
from django.contrib import admin
from django import forms
admin.site.register(Whitepaper)
The app is listed in the settings.py file:
INSTALLED_APPS = (
...,
...,
'publish',
...,
)
As this is running on a dev server that's hosting a few other testing areas, restarting the whole thing is out of the question so I've been 'touching' the .wsgi file.
On my local version this got the model and fields showing up in the admin but on the dev server they are nowhere to be seen.
What am I missing?
Thanks ye brainy ones.
I figured out the problem. Turns out the login I was using to get into the admin didn't have superuser privileges. So I made a new one with:
python manage.py createsuperuser
After logging in with the new username and password I could see all my new shiny tables!
Are you sure touching .wsgi file does restart your app?
It looks like it doesn't.
Make sure the app is restarted. Find the evidence touching .wsgi file restarts the app maybe.
Since you don't provide any insight about how the dev server runs the apps, we won't be able to help you any further.

How do you create a class using (admin.ModelAdmin) for a polling app

I am working through a Django tutorial at http://lightbird.net/dbe/todo_list.html . I completed Django's official tutorial. When I attempted to sync
from django.db import models
from django.contrib import admin
class Item(models.Model):
name = models.CharField(max_length=60)
created = models.DateTimeField(auto_now_add=True)
priority = models.IntegerField(default=0)
difficult = models.IntegerField(default=0)
class ItemAdmin(admin.ModelAdmin):
list_display = ["name", "priority", "difficult", "created", "done"]
search_fields = ["name"]
admin.site.register(Item, ItemAdmin)
The terminal came back with an error that said admin was not defined. What am I doing wrong? How do I define admin?
Update: I added the whole models file as it looks now
The Django documentation lists multiple steps that need to be done to activate the admin site:
Add 'django.contrib.admin' to your INSTALLED_APPS setting.
The admin has four dependencies - django.contrib.auth, django.contrib.contenttypes, django.contrib.messages and
django.contrib.sessions. If these applications are not in your
INSTALLED_APPS list, add them.
Add django.contrib.messages.context_processors.messages to TEMPLATE_CONTEXT_PROCESSORS and MessageMiddleware to
MIDDLEWARE_CLASSES. (These are both active by default, so you only
need to do this if you’ve manually tweaked the settings.)
Determine which of your application’s models should be editable in the admin interface.
For each of those models, optionally create a ModelAdmin class that encapsulates the customized admin functionality and options for
that particular model.
Instantiate an AdminSite and tell it about each of your models and ModelAdmin classes.
Hook the AdminSite instance into your URLconf. lists a couple of things that you must do the enable Django's admin site.
If you haven't done the first two items, syncdb might complain because it can't find the admin app itself.

Django admin multiple photo upload

I have to create a blog posting system and I need to make it possible to upload multiple photos in Django Admin and select it via Django TinyMCE. One of the solutions is Filebrowser, but I have already spent a few days and haven't got it worked. Are there any alternatives?
I'm trying to do something similar, but not with Tinymce, I choose wmd.
I created two models, one for the blog post, and one for the images, and in the admin interface I included the images as inlines. here's some example.
in your model.py file:
class Project(models.Model):
...
#TinyMce field.
description = models.TextField()
class ProjectImage(models.Model):
image = models.ImageField(upload_to='prjimages/%Y/%m/%d/%H/%M/%S/')
project = models.ForeignKey(Project)
than in your admin.py file, you can have the PostImage as inline.
from django.contrib import admin
from models import *
class ProjectImageAdmin(admin.ModelAdmin):
pass
class ProjectImageInline(admin.StackedInline):
model = ProjectImage
max_num=10
extra=0
class ProjectAdmin(admin.ModelAdmin):
inlines = [ProjectImageInline,]
admin.site.register(ProjectImage, ProjectImageAdmin)
admin.site.register(Project, ProjectAdmin)
you can change the ImageField Widget to show the url, and maybe a preview for each image (I have no example code for this at the moment). And if the user want to include the image in the post, he can just copy paste the url to Tinymce.
It's not a complete solution, but maybe you can extend it with some work to fit your needs.
You should take look at Dropzone.js which you can easily drag and drop multiple images to admin page.