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.
Related
I'm a beginner trying django for the first time trying to map my urls together, but after following the necessary steps the django installation page keeps on showing on my browser.
for my project app
from django import path
from django.urls import path
from . import views
urlpatterns = [
path('',views.index )
]
for my parent app
from xml.etree.ElementInclude import include
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
for my project views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('good sir')
settings.py file is below
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
It looks like you are isung the incorrect include for your parent app urls.
Instead of importing from xml.etree.ElementInclude import from django.urls
Also remove from django import path the path you need to use for the urlpatterns is the one from django.urls
I'm making use of Django haystack for my blog with solr as my search engine. I have also setup my solr(version 6.6.6) properly and all query are showing on the solr website. But when I make use of the SearchQuerySet
it returnss none upon query. I have included code below.
views.py
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views import generic
from blog.views import Post
from django.views.generic.base import TemplateView
from haystack.query import SearchQuerySet
import logging
logger = logging.getLogger(__name__)
class Search(TemplateView):
template_name = 'blog/post_search.html'
def get(self, request, **kwargs):
query = request.GET.get('query', '')
results = SearchQuerySet().models(Post).filter(content='query').load_all()
total = results.count()
return render(request, self.template_name, {'results':results, 'total':total})
search_indexes.py
from haystack import indexes
from blog.models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
publish = indexes.DateTimeField(model_attr='publish_date')
def get_model(self):
return Post
def index_queryset(self, using=None):
return self.get_model().objects.published()
settings.py
"""
Django settings for radd project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
SITE_ID = 1
ALLOWED_HOSTS = ['www.rad.com', '127.0.0.1', 'rad.com', 'localhost', '192.168.43.195']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django_comments',
'django_comments_xtd',
'rest_framework',
'blog',
'mptt',
'haystack',
# third party apps
'crispy_forms',
]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8983/solr/blog',
'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
},
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
I am learning the decoupled Django with Django-rest-framework and React for web development. The database is PostgreSQL.
I have configured API, and when I run http://127.0.0.1:8000/api, it looks fine:
enter image description here
But if I click the link in this API(http://127.0.0.1:8000/api/todos/), it fails:
enter image description here
I can't figure out what is going on.
my backend/urls.py is:
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
from todos import views
router = routers.DefaultRouter()
router.register(r'todos', views.TodoView,'todo')
urlpatterns = [
# url(r'^', include('todos.urls')),
url(r'^api/', include(router.urls)),
url(r'^admin/', include(admin.site.urls)),
]
my backend/settings.py is:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'igphn#&4b(67(*=!u)lr1wr=jtfhvgwc03nl&5+t7m18%-#ttm'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'todos',
'corsheaders',
)
MIDDLEWARE_CLASSES = (
'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.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
)
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'todos',
'USER': 'luyaoye',
'PASSWORD': '1234567',
'HOST': 'localhost',
'PORT':'5432'
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
# whitelist localhost:3000 where frontend will be served
CORS_ORIGIN_WHITELIST = ('localhost:3000/')
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20
}
my todos/serializers.py is:
from rest_framework import serializers
from .models import Todos
class TodoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=Todos
fields=['id','title','notes','created_at','completed',]
my todos/views.py is:
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import TodoSerializer
from .models import Todos
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todos.objects.using('todos').all()
my todos/models.py is:
from django.db import models
class Todos(models.Model):
title = models.CharField(max_length=100,blank=False)
notes = models.CharField(max_length=1000, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
def __str__(self):
# display todos brief
return self.title
My PostgreSQL database is running locally as well, and having data:
enter image description here
Anyone can help??
In queryset property of your TodoView, you don't have to write using('todos') part.
using() is meant for applications with multiple databases and tells django to use different DB connection (it uses DATABASES['default'] by default).
https://docs.djangoproject.com/en/2.2/topics/db/multi-db/#manually-selecting-a-database-for-a-queryset
So if you remove using part - everything should be working.
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
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