Django: adding model to admin site - django

I dont know what i am doing wrong but i cant add model to my admin .
settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.admindocs',
'RM.cal',
'release',
'south',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django_notify.middleware.NotificationsMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
global_settings.TEMPLATE_CONTEXT_PROCESSORS +
('django.core.context_processors.request','django.contrib.messages.context_processors.messages',)
)
admin.py
from cal.models import *
from django.contrib import admin
admin.site.register(Cos)
urls.py
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^RM/', include('RM.foo.urls')),
(r'^cal/', include('RM.cal.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': 'C:/Users/sg0217297/Desktop/test/tkt_crmt/RM/media'}),
models.py its new field just for testing but i can add it to admin ;/
from django.db import models
from django.contrib import admin
class Cos(models.Model):
name = models.CharField(max_length=400, blank= False , null = True)
def __unicode__(self):
return self.name
Any idea why ??
Thanks for help
E:
Updated urls.py

You need to define an app_label in your class, django only looks 1 level deep for models.py, so:
class YourModel(models.Model):
# whatever
class Meta:
app_label = 'cal'
You can also import the 2nd level models within the init of the module above

try to import indivisual models instead of '*' :
from your_app.models import model1,model2

Related

how to use django markdown in my blog

at first I successfully install django markdown
pip install django-markdown
than I add django-markdown in my setting.py file
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'django-markdown',
]
then, I change my urls.py like as:
from django.conf.urls import include, url
from django.contrib import admin
from resume import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^home/$', views.home, name='home'),
url(r'^blog/', include('blog.urls',namespace='blog',app_name='blog')),
url('^markdown/', include('django_markdown.urls')),
]
I also change my admin.py file like as:
from django.contrib import admin
from .models import Post
from django_markdown.admin import MarkdownModelAdmin
class PostAdmin(admin.ModelAdmin):
list_display = ('title','slug','author','publish','status')
list_filter = ('status','created','publish','author')
search_fields = ('title','body')
prepopulated_fields = {'slug':('title',)}
raw_id_fields = ('author',)
date_hierarchy = 'publish'
ordering = ['status','publish']
# Register your models here.
admin.site.register(Post,MarkdownModelAdmin, PostAdmin)
but, when I start my runserver, django gives me an error like this:
ModuleNotFoundError: No module named 'django-markdown'
how can i solve my problem?
In installed apps you should add django_markdown instead of django-markdown

Resubmitting File in FileField after Validation Error in Django [duplicate]

This question already has answers here:
How to make a Django form retain a file after failing validation
(5 answers)
Closed 6 years ago.
In Django project forms with FileField, ImageField. Everything works great, but when ValidationError is raised, I have to reselect all files and images again. I want to avoid this one by caches concept in django
but I am not getting currect output please correct this code and add if any required
-models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.db import models
from django.db.models import ImageField
# or if you use sorl-thumbnail
# from sorl.thumbnail.fields import ImageField
import os
def resume_path(instance, filename):
fn, ext = os.path.splitext(filename)
return "resumes/{id}{ext}".format(id=instance.title, ext=ext)
class Page(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
image = ImageField(upload_to=resume_path)
-admin.py
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from file_resubmit.admin import AdminResubmitMixin
from .models import Page
from django.forms import ModelForm
from file_resubmit.admin import AdminResubmitImageWidget,
AdminResubmitFileWidget
from .models import Page
class PageModelForm(ModelForm):
class Meta:
model = Page
widgets = {
'picture': AdminResubmitImageWidget,
'file': AdminResubmitFileWidget,
}
fields = '__all__'
class PageAdmin(admin.ModelAdmin,AdminResubmitMixin):
form = PageModelForm
admin.site.register(Page, PageAdmin)
-settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
"file_resubmit": {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
"LOCATION": '/home/xxxxxx/Downloads/Python/Projects_Python/pleasecome/tmp/file_resubmit',
# "LOCATION": os.path.join(BASE_DIR,'tmp/file_resubmit/'),
},
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sub',
'file_resubmit',
]
MIDDLEWARE_CLASSES = [
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
]
The problem might be with the class PageAdmin
class PageAdmin(admin.ModelAdmin,AdminResubmitMixin):
form = PageModelForm
According to the documentation for django-form-resubmit the ModelAdmin should be be created in one of these ways:
class PageAdmin(admin.ModelAdmin):
form = PageModelForm
class PageAdmin(AdminResubmitMixin, admin.ModelAdmin):
pass
The order you declare parent classes is significant, so you should follow the official example. And since you have a custom form, you don't need to use the AdminResubmitMixin at all.

Django Cannot Add Model to Admin Site

I can't add new model to django's admin site. There is only one app can display its models and the other apps cannot add their models to admin site.
Here is my settings.py:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'Home',
'Scope',
'Trend',
'Log',
'Lab',
'Club',
'Article',
'Search',
'page_test',
Here is the urls.py:
from django.conf.urls import patterns, include, url
from cretus import views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'cretus.views.home', name='home'),
# url(r'^cretus/', include('cretus.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'^$', include('Home.urls')),
url(r'^$', include('page_test.urls')),
url(r'^page/', include('Home.urls')),
url(r'^search/', include('Search.urls')),
url(r'^test/', include('page_test.urls')),
#url(r'artistsearch/', include('Search.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^artscopes/', include('Scope.urls')),
url(r'^trend/', include('Trend.urls')),
url(r'^log/', include('Log.urls')),
url(r'^lab/', include('Lab.urls')),
url(r'^club/', include('Club.urls')),
url(r'^privacy/$', views.privacy, name='privacy'),
url(r'thanks/$', views.thanks, name='thanks'),
url(r'^contest/$', views.contestForm, name='contest'),
url(r'^terms/$', views.terms, name='terms'),
#url(r'^test/$', views.test, name='test'),
#url(r'^(?P<title>[a-zA-Z0-9_-]{0,100})/$', views.getArticleByTitle, name='test'),
#url(r'^article/', include('Article.urls')),
url(r'^article/', include('page_test.urls')),
# Apps
url(r'^tinymce/', include('tinymce.urls')),
url(r'^ckeditor/', include('ckeditor.urls')),
url(r'^sitemap.xml$', views.sitemap, name='sitemap'),
url(r'^googlesearch/$', views.googlesearch, name='googlesearch'),
url(r'^legal/$', views.legal, name='legal'),
url(r'^', views.error, name='error'),
)
Here is one of the admin.py:
from django.contrib import admin
from Lab.models import AttendeeInfo
class AttendeeInfoAdmin(admin.ModelAdmin):
list_display = ('fname', 'lname', 'email', 'video_url', 'package_name')
admin.site.register(AttendeeInfo, AttendeeInfoAdmin)
This problem has been solved. It is because the permission has not been granted to this user. So next time when you found you have done all of the procedures but still cannot find your model in the admin console, you may need to check this user's permission.

TemplateDoesNotExist at /join/home.html (Django)

I've went through the other answers here but can't grasp how to fix my version of this problem since this is my first project. I can get 127.0.0.1:8000/admin to show up just fine.
I'm getting this error:
TemplateDoesNotExist at /join/home.html.
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.5.1
Exception Type: TemplateDoesNotExist
Exception Value: /join/home.html.
home.html is located in /Users/user/Desktop/mvp_landing/static/templates/join
In my views.py I have this:
from django.shortcuts import render_to_response, RequestContext
from .models import Join
from .forms import JoinForm
def home(request):
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
new_join.save()
return render_to_response('/join/home.html.', locals(), context_instance=RequestContext(request))
so I should be ok with what I have here in settings.py for TEMPLATE_DIRS, right?:
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(os.path.dirname(__file__)), "static", "templates"),
)
Here is the entire settings.py(with db info, etc removed):
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static", "media")
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static", "static-only")
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(os.path.dirname(__file__)), "static", "static"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
SECRET_KEY = 'xxxxxxxxxxx'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mvp_landing.urls'
WSGI_APPLICATION = 'mvp_landing.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(os.path.dirname(__file__)), "static", "templates"),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'south',
'join',
)
and urls.py is this:
from django.conf.urls import patterns, include, url
from django.conf import settings
# 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'^$', 'join.views.home', name='home'),
# 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)),
)
Any help is appreciated, thanks.
You should fix the path here:
return render_to_response('join/home.html', locals(), context_instance=RequestContext(request))
Notice how I removed the / at the beginning and also the trailing .
Hope this helps
Remove the first slash in the view template string.

django-social-auth facebook login keeps overwriting same user

I implemented django-social-auth and got it to authenticate me with Facebook.
I would like it to also create a new user in the system, and write the email, name, and phone number if possible.
However, each time i log in with a user, it keeps overwriting the root user and not creating a new user?
I am also using a custom authentication module, and it's not creating a user in the custom model.
Settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'something.urls'
WSGI_APPLICATION = 'something.wsgi.application'
TEMPLATE_DIRS = (
templatedir
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'frontpage',
'social_auth',
'django.contrib.admin'
)
AUTHENTICATION_BACKENDS = (
'something.auth_backends.CustomUserModelBackend',
'social_auth.backends.twitter.TwitterBackend',
'social_auth.backends.facebook.FacebookBackend',
)
CUSTOM_USER_MODEL = 'accounts.CustomUser'
SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/newuser/'
SOCIAL_AUTH_DISCONNECT_REDIRECT_URL = '/disconnected/'
SOCUAL_AUTH_USER_MODEL = 'accounts.CustomUser'
SOCIAL_AUTH_CREATE_USERS = True
FACEBOOK_APP_ID = 'XXX'
FACEBOOK_API_SECRET = 'XXX'
FACEBOOK_EXTENDED_PERMISSIONS = ['email','user_birthday','user_hometown','user_location','user_about_me']
LOGIN_URL = '/'
LOGIN_REDIRECT_URL = '/home/'
LOGIN_ERROR_URL = '/login-error/'
SOCIAL_AUTH_DEFAULT_USERNAME = 'social_auth_user'
SOCIAL_AUTH_ENABLED_BACKENDS = ('twitter','facebook','google')
TWITTER_CONSUMER_KEY = 'XXX'
TWITTER_CONSUMER_SECRET = 'XXX'
URL's.py
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login, logout
from frontpage.views import LoginPage, FrontPageView
from frontpage import views
from django.contrib import admin
from social_auth import __version__ as version
from social_auth.utils import setting
admin.autodiscover()
urlpatterns = patterns('',
url(r'', include('social_auth.urls')),
url(r'^$', views.LoginPage, name='LoginPage'),
url(r'^login/$', views.loginreq, name='loginreq'),
url(r'^newuser/$', views.newuser, name='newuser'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^home/$', views.HomePage, name='HomePage'),
url(r'^jobs/offers$', views.jobsoffers, name='jobsoffers'),
url(r'^jobs/view$', views.jobsview, name='jobsview'),
#url(r'^home/$', FrontPageView.as_view(), name='front_list'),
(r'^admin/jsi18n/$', 'django.views.i18n.javascript_catalog'),
# Examples:
# url(r'^$', 'something.views.home', name='home'),
# url(r'^something/', include('something.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)),
)
Views.py
class FrontPageView(ListView):
context_object_name = 'front_list'
template_name = 'homepage.html'
queryset = classifield.objects.all()
def get_context_data(self, **kwargs):
context = super(FrontPageView, self).get_context_data(**kwargs)
context['offers'] = offers.objects.all()
return context
def logout(request):
auth_logout(request)
return HttpResponseRedirect('/')
def LoginPage(request):
classifield_list = classifield.objects.all()
offers_list = offers.objects.all()
return render_to_response("login.html", {'classifield_list': classifield_list,'offers_list':offers_list}, context_instance=RequestContext(request))
#login_required
def HomePage(request):
classifield_list = classifield.objects.all()
ctx = {'last_login':request.session.get('social_auth_login_backend')}
return render_to_response("homepage.html", {'classifield_list': classifield_list, 'ctx':ctx}, context_instance=RequestContext(request))
Ok, to anyone else who gest stuck with this:
DONT LOG IN TO THE ADMIN!
Since you're logged in to the admin, it keeps overwriting your admin user.
Log out of the admin, and it will work!
Yeeey!