I've installed Django 1.3 with django-cms. All is working correctly.
After that I installed cmsplugin-blog (from the extensions page of the djanog-cms website), version 1.1.1
I can't seem to get my urls working correctly. It looks like the correct urls are being produced by the blog app, but when opening the posts, I get 404 error. I think it might be a mistake in the urls.py of the blog application:
from django.conf import settings
from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
from django.views.generic.date_based import archive_year, archive_month, archive_day, object_detail
from django.views.generic.list_detail import object_list
from tagging.views import tagged_object_list
from menus.utils import set_language_changer
from cms.models import Title
from cms.utils.urlutils import urljoin
from cmsplugin_blog.feeds import EntriesFeed, TaggedEntriesFeed, AuthorEntriesFeed
from cmsplugin_blog.models import Entry
from cmsplugin_blog.views import EntryDateDetailView, EntryArchiveIndexView
blog_info_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
'allow_empty': True,
'paginate_by': 15,
}
blog_info_tagged_dict = {
'queryset_or_model': Entry.objects.all(),
'allow_empty': True,
}
blog_info_author_dict = {
'queryset': Entry.objects.all(),
'allow_empty': True,
'template_name': 'cmsplugin_blog/entry_author_list.html',
}
blog_info_month_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
'month_format': '%m',
'allow_empty': True,
}
blog_info_year_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
'make_object_list': True,
'allow_empty': True,
}
blog_info_detail_dict = dict(blog_info_month_dict, slug_field='entrytitle__slug')
def language_changer(lang):
request = language_changer.request
return request.get_full_path()
blog_archive_index = EntryArchiveIndexView.as_view()
def blog_archive_year(request, **kwargs):
kwargs['queryset'] = kwargs['queryset'].published()
set_language_changer(request, language_changer)
return archive_year(request, **kwargs)
def blog_archive_month(request, **kwargs):
kwargs['queryset'] = kwargs['queryset'].published()
set_language_changer(request, language_changer)
return archive_month(request, **kwargs)
def blog_archive_day(request, **kwargs):
kwargs['queryset'] = kwargs['queryset'].published()
set_language_changer(request, language_changer)
return archive_day(request, **kwargs)
blog_detail = EntryDateDetailView.as_view()
def blog_archive_tagged(request, **kwargs):
kwargs['queryset_or_model'] = kwargs['queryset_or_model'].published()
set_language_changer(request, language_changer)
return tagged_object_list(request, **kwargs)
def blog_archive_author(request, **kwargs):
author = kwargs.pop('author')
kwargs['queryset'] = kwargs['queryset'].published().filter(entrytitle__author__username=author)
kwargs['extra_context'] = {
'author': author,
}
set_language_changer(request, language_changer)
return object_list(request, **kwargs)
urlpatterns = patterns('',
(r'^$', blog_archive_index, blog_info_dict, 'blog_archive_index'),
(r'^(?P<year>\d{4})/$',
blog_archive_year, blog_info_year_dict, 'blog_archive_year'),
(r'^(?P<year>\d{4})/(?P<month>\d{2})/$',
blog_archive_month, blog_info_month_dict, 'blog_archive_month'),
(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$',
blog_archive_day, blog_info_month_dict, 'blog_archive_day'),
(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
blog_detail, blog_info_detail_dict, 'blog_detail'),
(r'^tagged/(?P<tag>[^/]*)/$', blog_archive_tagged, blog_info_tagged_dict, 'blog_archive_tagged'),
(r'^author/(?P<author>[^/]*)/$', blog_archive_author, blog_info_author_dict, 'blog_archive_author'),
(r'^rss/any/tagged/(?P<tag>[^/]*)/$', TaggedEntriesFeed(), {'any_language': True}, 'blog_rss_any_tagged'),
(r'^rss/tagged/(?P<tag>[^/]*)/$', TaggedEntriesFeed(), {}, 'blog_rss_tagged'),
(r'^rss/any/author/(?P<author>[^/]*)/$', AuthorEntriesFeed(), {'any_language': True}, 'blog_rss_any_author'),
(r'^rss/author/(?P<author>[^/]*)/$', AuthorEntriesFeed(), {}, 'blog_rss_author'),
(r'^rss/any/$', EntriesFeed(), {'any_language': True}, 'blog_rss_any'),
(r'^rss/$', EntriesFeed(), {}, 'blog_rss')
)
Any help is appreciated!
If you need more configurations, I can post them.
Thanks
settings.py
# -*- coding: utf-8 -*-
import os
gettext = lambda s: s
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MANAGERS = ADMINS
DEFAULT_LANGUAGE = 0
DATABASES = {
'default': {
'ENGINE': '*******',
'NAME': '*******',
'USER': '*******',
'PASSWORD': '*********',
'HOST': '*******',
'PORT': '*******',
}
}
TIME_ZONE = 'Europe/Amsterdam'
LANGUAGE_CODE = 'nl'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
# Make this unique, and don't share it with anybody.
SECRET_KEY = '**************************'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.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',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.multilingual.MultilingualURLMiddleware',
'cmsplugin_blog.middleware.MultilingualBlogEntriesMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'cms.context_processors.media',
'sekizai.context_processors.sekizai',
)
CMS_TEMPLATES = (
('base.html', 'Main Template'),
)
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
#for cms-blog
JQUERY_JS = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'
JQUERY_UI_JS = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js'
JQUERY_UI_CSS = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.staticfiles',
'debug_toolbar',
'cms',
'menus',
'mptt',
'south',
'cms.plugins.text',
'cms.plugins.picture',
'cms.plugins.link',
'cms.plugins.file',
'cms.plugins.snippet',
'cms.plugins.googlemap',
'sekizai',
'cmsplugin_contact',
'cmsplugin_blog',
'djangocms_utils',
'simple_translation',
'tagging',
'staticfiles',
)
cms_app.py:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class BlogApphook(CMSApp):
name = _("Blog Apphook")
urls = ["cmsplugin_blog.urls"]
apphook_pool.register(BlogApphook)
You need to mount the Apphook of the blog app to a page (see http://readthedocs.org/docs/django-cms/en/latest/extending_cms/extending_examples.html#my-first-app-apphook).
You need to do this for every language.
After you do that, you unfortunately have to restart the server.
Never mind. I've found the solution(s)....
After many hours of debugging I found out it was my mistake after all. I am using wsgi and the settings in the apache.wsgi file were incorrect.
In my sys.path I also appended a path from another django project. Since this append was the first one, it was never possible for any of my apps to read the correct settings files and url.py files.
After that it took me some time searching why the zinnia app (I moved from cmsplugin-blog to zinnia, which has much more options) wasn't working. This post helped in the right direction:
http://groups.google.com/group/django-blog-zinnia/browse_thread/thread/4de2827343fb79e0
After I put my url patterns in the correct order, everything worked fine!
Related
I have a bug and not sure how to fix it, I've been writing an e-comm site and all of a sudden I'm getting a 404 page, Everything was working fine. The bug report tells me that the path matched the last one, but still getting 404. It's not only one app, it's all of them. I just have no clue how to fix this.
Settings:
from pathlib import Path
import environ
import os
import dj_database_url
env = environ.Env()
# read the .env file
environ.Env.read_env()
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = env('SECRET_KEY')
DEBUG = True
ALLOWED_HOSTS = ['*']
TAX_RATE_PERCENTAGE = 23
FREE_DELIVERY_THRESHOLD = 200
# Application definition
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sitemaps',
'django.contrib.sites',
'cloudinary_storage',
'cloudinary',
'allauth',
'allauth.account',
'allauth.socialaccount',
'mathfilters',
'crispy_forms',
'ckeditor',
'home',
'boutique',
'bag',
'checkout',
'profiles'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'IMC.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / "templates"],
'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',
'django.template.context_processors.media',
'bag.contexts.bag_contents',
],
'builtins': [
'crispy_forms.templatetags.crispy_forms_tags',
'crispy_forms.templatetags.crispy_forms_field',
]
},
},
]
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
]
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "None"
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = False
ACCOUNT_USERNAME_MIN_LENGTH = 3
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'
ACCOUNT_LOGOUT_REDIRECT_URL = '/'
SITE_ID = 1
WSGI_APPLICATION = 'IMC.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/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/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = 'static_root'
# WHITENOISE - static storage
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
# CLOUDINARY for media storage
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
},
}
# STRIPE
STRIPE_CURRENCY = 'eur'
if "DEV" in os.environ:
STRIPE_PUBLIC_KEY = env('STRIPE_PUBLIC_KEY')
STRIPE_SECRET_KEY = env('STRIPE_SECRET_KEY')
STRIPE_WH_SECRET = env('STRIPE_WH_SECRET')
else:
STRIPE_PUBLIC_KEY = os.environ.get('STRIPE_PUBLIC_KEY')
STRIPE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY')
STRIPE_WH_SECRET = os.environ.get('STRIPE_WH_SECRET')
# SESSION_COOKIE_SECURE = True
# SECURE_BROWSER_XSS_FILTER = True
# SECURE_CONTENT_TYPE_NOSNIFF = True
# SECURE_HSTS_SECONDS = 3153600
# SECURE_REDIRECT_EXEMPT = []
# SECURE_SSL_REDIRECT = True
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# EMAIL
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
NOTIFY_EMAIL = os.environ.get('NOTIFY_EMAIL')
DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER')
# CLOUDINARY_CONFIG
if "DEV" in os.environ:
CLOUDINARY_STORAGE = {
'CLOUD_NAME': env('CLOUD_NAME'),
'API_KEY': env('API_KEY'),
'API_SECRET': env('API_SECRET'),
}
else:
CLOUDINARY_STORAGE = {
'CLOUD_NAME': os.environ.get('CLOUD_NAME'),
'API_KEY': os.environ.get('API_KEY'),
'API_SECRET': os.environ.get('API_SECRET'),
}
Root-URLS:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.contrib import admin
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import path, include
from django.views.generic.base import RedirectView
from home.views import IndexView
urlpatterns = [
path('', include('home.urls')),
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('boutique/', include('boutique.urls')),
path('bag/', include('bag.urls', namespace='bag')),
path('checkout/', include('checkout.urls', namespace='checkout')),
path('profiles/', include('checkout.urls', namespace='profiles')),
path('favicon.ico', RedirectView.as_view(
url=staticfiles_storage.url('img/favicon.ico'))),
url(r'^.*/$', IndexView.as_view())
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
App-urls:
from django.urls import path
from home.views import (
ContactView, IndexView,
TermsView, GalleryView,
aboutview, PrivacyView
)
urlpatterns = [
path('', IndexView.as_view(), name='home'),
path('about/', aboutview, name='about'),
path('gallery/', GalleryView.as_view(), name='gallery'),
path('contact/', ContactView.as_view(), name='contact'),
path('terms/', TermsView.as_view(), name='terms'),
path('privacy/', PrivacyView.as_view(), name='privacy'),
]
APP-View:
from django.conf import settings
from django.contrib import messages
from django.core.mail import send_mail
from django.shortcuts import reverse, render
from django.views import generic
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from .forms import ContactForm
from boutique.models import Product
from .models import (About, Scarfs, Paintings,
ImageGallery, Home, PrivacyPolicy,
TermsConditions, Comment)
class IndexView(ListView):
model = Home
template_name = "home/index.html"
context_object_name = "home"
def get_context_data(self, **kwargs):
comments = Comment.objects.all()
context = super().get_context_data(**kwargs)
context['comments'] = comments
return context
def aboutview(request):
feat_item = Product.objects.filter(feat_item=True)
about = About.objects.all()
scarfs = Scarfs.objects.all()
paintings = Paintings.objects.all()
context = {
'feat_item': feat_item,
'about': about,
'scarfs': scarfs,
'paintings': paintings,
}
return render(request, "home/about.html", context)
class GalleryView(ListView):
model = ImageGallery
template_name = "home/gallery.html"
context_object_name = "images"
class TermsView(ListView):
model = TermsConditions
template_name = "home/terms.html"
context_object_name = "terms"
class PrivacyView(ListView):
model = PrivacyPolicy
template_name = "home/privacy.html"
context_object_name = "policys"
class ContactView(generic.FormView):
form_class = ContactForm
template_name = "home/contact.html"
def get_success_url(self):
return reverse("contact")
def form_valid(self, form):
""""Getting clean data from the form and creating
a message to get sent to default email."""
messages.success(self.request,
"Thank you for getting in touch with us. We have received your message.")
name = form.cleaned_data.get('name')
email = form.cleaned_data.get('email')
message = form.cleaned_data.get('message')
full_message = f"""
Received Message/Comment below from:
Name: {name}
Email: {email},
___________________________
Message/Comment:
{message}
"""
send_mail(
subject="Message/Comment from Webpage contact form",
message=full_message,
from_email=settings.DEFAULT_FROM_EMAIL,
recipient_list=[settings.NOTIFY_EMAIL]
)
return super(ContactView, self).form_invalid(form)
Django Error page:
All apps error page:
Hi There actually i am creating a notes taking app using django. For better ux i have used django ckeditor for providing a good editor to write beautiful and informative notes. I have used django.ckeditor richtextfield for this purpose. Now i want to encrypt the data of this text field so it can be stored safefly. I have used djanog-cryptography package and used encrypt method.
Problem -: When i am retreiving the note_contents in my template its showing nothing.
I am attaching my views and models and settings.py
views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . models import UserCreatedNote
from . forms import AddNoteForm
# Create your views here.
#login_required
def notes(request):
if request.method=='POST':
form = AddNoteForm(request.POST)
if form.is_valid():
form_data = form.save(commit=False)
form_data.user = request.user
form_data.save()
notes = UserCreatedNote.objects.filter(user=request.user)
form = AddNoteForm()
context = {'notes': notes,'add_note_form':form}
return render(request,'usernotes.html',context)
notes = UserCreatedNote.objects.filter(user=request.user)
form = AddNoteForm()
context = {'notes': notes,'add_note_form':form}
return render(request,'usernotes.html',context)
#login_required
def edit(request,id):
note = get_object_or_404(UserCreatedNote, pk=id)
if request.method == 'POST':
form = AddNoteForm(request.POST, instance=note)
if form.is_valid():
form_data = form.save(commit=False)
form_data.user = request.user
print(form_data.id)
form_data.save()
form = AddNoteForm(instance=note)
context={'note':note,'u_form':form}
return render(request,'edit_note.html',context)
form = AddNoteForm(instance=note)
context={'note':note,'u_form':form}
return render(request,'edit_note.html',context)
#login_required
def delete(request,id):
note = UserCreatedNote(id=id,user=request.user)
note.delete()
return redirect('/user/notes/')
settings.py
"""
Django settings for keepsafe project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = config('DEBUG')
SECRET_KEY = config('SECRET_KEY')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ALLOWED_HOSTS = ['*']
AUTH_USER_MODEL = "useraccounts.keepsafeusermodel"
AUTHENTICATION_BACKENDS = (
'useraccounts.backends.CaseInsensitiveModelBackend',
)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'crispy_forms',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'useraccounts.apps.UseraccountsConfig',
'notes.apps.NotesConfig',
'django_cleanup.apps.CleanupConfig',
'ckeditor',
]
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 = 'keepsafe.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['notes/templates/notes','useraccounts/templates/useraccounts','keepsafe/templates/keepsafe'],
'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 = 'keepsafe.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '',
'USER':'',
'PASSWORD':'',
'HOST':''
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Calcutta'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CRISPY_TEMPLATE_PACK = "bootstrap4"
LOGIN_REDIRECT_URL = 'user_profile'
LOGIN_URL = 'user_login'
if not DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST ='smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = ''
CKEDITOR_CONFIGS = {
'default': {
# 'toolbar': None, You can change this based on your requirements.
'width': 'auto',
},
}
# CRYPTOGRAPHY_BACKEND = 'cryptography.hazmat.backends.default_backend()'
# CRYPTOGRAPHY_DIGEST = 'cryptography.hazmat.primitives.hashes.SHA256'
# CRYPTOGRAPHY_KEY = None
# CRYPTOGRAPHY_SALT = 'django-cryptography'
# SIGNING_BACKEND = 'django_cryptography.core.signing.TimestampSigner'
django_heroku.settings(locals())
https://django-cryptography.readthedocs.io/en/latest/settings.html
when i use this in my settings it throws an error that 'str has no object digest_size' something.
Models.py
from django.db import models
from django.contrib.auth import get_user_model
from ckeditor.fields import RichTextField
from django_cryptography.fields import encrypt
# Create your models here.
class UserCreatedNote(models.Model):
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
note_title = models.CharField(default='',max_length=100,blank=True,null=True)
note_tags = encrypt(models.CharField(default='',max_length=20,blank=True,null=True))
note_contents = RichTextField(default='',max_length=1000,blank=True,null=True)
creation_time = models.DateTimeField(auto_now_add=True)
last_modified_time = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-creation_time',]
def __str__(self):
return str(self.user)
class UserQueries(models.Model):
email = models.TextField(default="",primary_key=True,max_length=80)
name = models.CharField(default="",max_length=80)
subject = models.CharField(default="",max_length=100)
message= models.CharField(default="",max_length=5000)
def __str__(self):
return self.name
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.
I am trying to create a blog using django and mongodb in aws ec2 instance
And in the file models.py, I am making following changes
from datetime import datetime
from mongoengine import *
from mongoengine.django.auth import User
from django.core.urlresolvers import reverse
class Post(Document):
user = ReferenceField(User, reverse_delete_rule=CASCADE)
title = StringField(max_length=200, required=True)
text = StringField(required=True)
text_length = IntField()
date_modified = DateTimeField(default=datetime.now)
is_published = BooleanField()
from django.core.urlresolvers import reverse
class Post(Document):
user = ReferenceField(User, reverse_delete_rule=CASCADE)
title = StringField(max_length=200, required=True)
text = StringField(required=True)
text_length = IntField()
date_modified = DateTimeField(default=datetime.now)
is_published = BooleanField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.text_length = len(self.text)
return super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('detail', args=[self.id])
def get_edit_url(self):
return reverse('update', args=[self.id])
def get_delete_url(self):
return reverse('delete', args=[self.id])
And, I get this error
Traceback (most recent call last):
File "models.py", line 7, in <module>
from mongoengine.django.auth import User
ImportError: No module named django.auth
And, in settings.py file, I am making following changes
import os
from mongoengine import *
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['54.149.63.203', 'localhost', '127.0.0.1']
# 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',
'LJblog',
'django_extensions',
'mongoengine.django.mongo_auth',
)
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',
)
ROOT_URLCONF = 'LJ.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 = 'LJ.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '55.181.26.33', //mongodb ip address
'PORT': '27017',
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = os.path.join(PROJECT_ROOT, '..', 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, '..', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
TEMPLATE = (
os.path.join(PROJECT_ROOT, 'templates'),
)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
MONGO_DATABASE_NAME = 'LJ_blog'
from mongoengine import connect
connect(MONGO_DATABASE_NAME)
So, how can I resolve the import error?
Django support was removed from MongoEngine in 0.10.0. You might be able to get an earlier version to work, but it might not support recent versions of Django.
With mongoengine 0.10 we can see that
/usr/lib/python2.7/site-packages/mongoengine/
will not have django package in it.
Install mongoengine 0.9 using
sudo pip install mongoengine==0.9
and the django package (support or extension) will be available.
When working on REST browsable API the responses work fine but when I started working on postman to integrate with front end on the other side the respond become:
{
"detail": "CSRF Failed: CSRF cookie not set."
}
I tried everything to solve this error but nothing change, and checked every question here on CSRF token but still didn't work
These are my codes:
views.py:
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework import status
from User.serializers import UserDataSerializer, ImageSerializer
from rest_framework.views import APIView
from rest_framework import generics
from User.models import UserData,Image
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from rest_framework.renderers import TemplateHTMLRenderer
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
class Signup(APIView):
def post(self, request, format = None):
serializer = UserDataSerializer(data = request.data)
if(serializer.is_valid()):
user = User.objects.create_user(
username = serializer.data['username'],
first_name = serializer.data['first_name'],
last_name = serializer.data['last_name'],
email = serializer.data['email'],
password = serializer.data['password'],
)
#add the name because it is not with create_user method
# user.name = serializer.data['name']
# user.save()
login(request, user)
print ("logged")
text = {'valid' : True , 'errors' :"ur password"+serializer.data['password']}
return JsonResponse(serializer.data)
else:
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Login(APIView):
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
serializer = UserDataSerializer(user)
return JsonResponse(serializer.data, status=status.HTTP_302_FOUND)
else:
text = {'valid' : False , 'errors' : "Invalid Username or Password"}
return Response(text, status=status.HTTP_401_UNAUTHORIZED)
class Logout(APIView):
def get(self, request):
logout(request)
return Response({"valid": True}, status=status.HTTP_200_OK)
class ImageUpload(generics.CreateAPIView):
queryset = Image.objects.all()
serializer_class = ImageSerializer
settings.py:
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'baz^+ip1ik4_fla*zg$9q#37e(5jg6tmnwzj4btqw#nw=si)+('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CSRF_COOKIE_SECURE = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'User.apps.UserConfig',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'app.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.core.context_processors.csrf',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
}
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ImageSearchDB',
'USER': 'root',
'PASSWORD': '1234',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'init_command': 'SET default_storage_engine=INNODB',
}
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# AUTHENTICATION_BACKENDS = (
# 'app.User.backends.EmailOrUsernameModelBackend',
# 'django.contrib.auth.backends.ModelBackend'
# )
# Internationalization
# https://docs.djangoproject.com/en/1.10/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.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = 'media/'
urls.py
from django.conf.urls import url
from User import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^login/?$', views.Login().as_view()),
url(r'^signup/?$', views.Signup().as_view()),
url(r'^logout/?$', views.Logout().as_view()),
url(r'^trail/?$', views.ImageUpload().as_view())
]
urlpatterns = format_suffix_patterns(urlpatterns) #no need
you have to use ensure_csrf_cookie decorator in the urls like this
from django.views.decorators.csrf import ensure_csrf_cookie
urlpatterns = [
url(r'^login/?$', ensure_csrf_cookie(views.Login().as_view())),
]
Also you need to add all of your CORS settings