whenever I create a new object in one of my models, they exist for around five minutes and then disappear. I checked in both my admin view and the queryset in the shell and they just disappear. I don't understand what's happening so if anyone has any idea, that'd be very useful.
These are the models:
class Character(models.Model):
image = models.ImageField()
name = models.CharField(max_length=100)
age = models.IntegerField()
story = models.CharField(max_length=500)
def __str__(self):
return self.name
class Movie(models.Model):
image = models.ImageField()
title = models.CharField(max_length=100)
creation_date = models.DateField(auto_now=True)
rating = models.IntegerField()
characters = models.ManyToManyField(Character, blank=True, related_name='movies')
def __str__(self):
return self.title
These are the views:
class CharacterCreateAPI(generics.CreateAPIView):
queryset = Character.objects.all()
serializer_class = CharacterSerializer
permission_classes = (AllowAny,)
class MovieCreateAPI(generics.CreateAPIView):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
permission_classes = (AllowAny,)
These are the serializers:
class CharacterSerializer(serializers.ModelSerializer):
movies = serializers.PrimaryKeyRelatedField(queryset=Movie.objects.all())
class Meta:
model = Character
fields = ['name', 'age', 'image', 'movies', 'story']
extra_kwargs = {'image': {'required': False, 'allow_null': True}}
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = ('title', 'image', 'rating', 'characters')
extra_kwargs = {'image': {'required': False, 'allow_null': True}}
def create(self, validated_data):
characters = validated_data.pop('characters')
movie = Movie.objects.create(**validated_data)
if characters:
movie.set(characters)
movie.save()
return movie
Settings:
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# 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',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
'rest_framework.authtoken',
'core'
]
SITE_ID = 1
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 = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
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/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.IsAdminUser',
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
Related
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
In django admin database I am not getting expected view. I am following the tutorials to make a quiz app in Django. I did exactly as shown in video but still I am not getting same output. I have attached the picture of expected view and picture of what I am getting.
Getting This:
Expecting This:
models.py (in quiz):
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class Quiz(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=70)
slug = models.SlugField(blank=True)
roll_out = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['timestamp',]
verbose_name_plural = 'Quizzes'
def __str__(self):
return self.name
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions')
label = models.CharField('Question', max_length=255)
order = models.IntegerField(default=0)
def __str__(self):
return self.label
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers')
label = models.CharField('Answer', max_length=255)
is_correct = models.BooleanField('Correct answer', default=False)
def __str__(self):
return self.label
class QuizTaker(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
score = models.IntegerField(default=0)
completed = models.BooleanField(default=False)
date_finished = models.DateTimeField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
class UserAnswer(models.Model):
quiz_taker = models.ForeignKey(QuizTaker,on_delete=models.CASCADE)
quistion = models.ForeignKey(Question,on_delete=models.CASCADE)
answer = models.ForeignKey(Answer,on_delete=models.CASCADE)
def __str__(self):
return self.question.label
In admin.py
from django.contrib import admin
import nested_admin
from .models import Quiz, Question, Answer, QuizTaker, UserAnswer
# Register your models here.
class AnswerInline(nested_admin.NestedTabularInline):
model = Answer
extra = 4
max_num = 4
class QuestionInline(nested_admin.NestedTabularInline):
model = Question
inline = [AnswerInline]
extra = 5
class QuizAdmin(nested_admin.NestedModelAdmin):
inline = [QuestionInline,]
class UserAnswerInline(admin.TabularInline):
model = UserAnswer
class QuizTakerAdmin(admin.ModelAdmin):
inline = [UserAnswerInline,]
admin.site.register(Quiz,QuizAdmin)
admin.site.register(Question)
admin.site.register(Answer)
admin.site.register(QuizTaker,QuizTakerAdmin)
admin.site.register(UserAnswer)
In settings.py
"""
Django settings for assignment2 project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u1e72cel3t20c3m5wvetnl*7w6x8srf4f#ncx6x=7*0k-w^#%x'
# 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',
'django.contrib.humanize',
'bootstrap4',
'accounts.apps.AccountsConfig',
'quiz',
'nested_admin',
]
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 = 'assignment2.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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 = 'assignment2.wsgi.application'
ASGI_APPLICATION = 'assignment.routing.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/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/2.1/howto/static-files/
LOGIN_REDIRECT_URL = 'test'
LOGOUT_REDIRECT_URL = 'thanks'
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/
I am learning django but i am stuck at Imagefield. I am trying to rename the file and save the image to my media directory where exactly i am going wrong i am not able to understand. It was working fine till worked with filefield. after changing the filefield to imagefield i am getting an page not found.
Not Found: /media/products/926045120/926045120.jpg
above is the error
from django.db import models
import random
import os
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
def upload_image_path(instance, filename):
# print(instance)
#print(filename)
new_filename = random.randint(1,3910209312)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext)
return "products/{new_filename}/{final_filename}".format(
new_filename=new_filename,
final_filename=final_filename
)
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
def __str__(self):
return self.title
def __unicode__(self):
return self.title
model.py of product
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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z45+z23#cgk-fem6x&6i9_n#tz8p3)f^l+f1#8$e^n7(hv&dgz'
# 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',
'products',
]
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 = 'ecommerce.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
WSGI_APPLICATION = 'ecommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/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.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static_my_proj"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root")
products/views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
# Create your views here.
from .models import Product
class ProductListView(ListView):
queryset = Product.objects.all()
template_name = "products/list.html"
# def get_context_data(self, *args, **kwargs):
# context = super(ProductListView, self).get_context_data(*args, **kwargs)
# print(context)
# return context
def product_list_view(request):
queryset = Product.objects.all()
context = {
'object_list': queryset
}
return render(request, "products/list.html", context)
class ProductDetailView(DetailView):
queryset = Product.objects.all()
template_name = "products/detail.html"
def get_context_data(self, *args, **kwargs):
context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
print(context)
#context['abc'] = 123
return context
def product_detail_view(request, pk=None, *args, **kwargs):
#instance = Product.objects.get(pk=pk)
instance = get_object_or_404(Product, pk=pk)
context = {
'object': instance
}
return render(request, "products/detail.html", context)
details.html
{{ object.title }}<br/>
{{ object.description }}<br/>
<img src="{{ object.image.url }}" class="img-fluid"/>
I am able see my images in media directory but it is not able view on page
I have installed Django and able to run the server and access the Django home page. But when I add the model class I am getting the following error in terminal.
RuntimeError: Model class myproject.urls.Board doesn't declare an
explicit app_label and isn't in an application in INSTALLED_APPS.
This is my code in settings.py
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'boards',
]
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': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'pythondb',
'USER' : 'root',
'PASSWORD' : 'calpine',
'HOST' : 'localhost',
'PORT' : '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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.11/howto/static-files/
STATIC_URL = '/static/'
Model Class
from django.db import models
from django.contrib.auth.models import User
class Board(models.Model):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=100)
class Topic(models.Model):
subject = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
board = models.ForeignKey(Board,
related_name='topics',
on_delete=models.DO_NOTHING)
starter = models.ForeignKey(User, related_name='topics', on_delete=models.DO_NOTHING)
class Post(models.Model):
message = models.TextField(max_length=4000)
topic = models.ForeignKey(Topic, related_name='posts', on_delete=models.DO_NOTHING)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True)
created_by = models.ForeignKey(User, related_name='posts',on_delete=models.DO_NOTHING)
updated_by = models.ForeignKey(User, null=True, related_name='+', on_delete=models.DO_NOTHING)
Accidentally removed the urlpatterns from urls.py file. Got the issue fixed and making the urlpatterns proper
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'),
url(r'^admin/', admin.site.urls),
]
Thanks
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
checked all INSTALLED_APPS in settings.py
registered models,apps.py.
Earlier this error was not coming when i was working with core and users applications under the same project.
settings.py
"""
Django settings for jam project.
Generated by 'django-admin startproject' using Django 2.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'bj))qqcyggizpqmxp9zru$pb%m#bt0--_z%$#z6!xz^$ij3#^#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
#All applications are working
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home.apps.HomeConfig',
'core.apps.CoreConfig',
'users.apps.UsersConfig',
'crispy_forms',
]
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 = 'jam.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
WSGI_APPLICATION = 'jam.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.2/howto/static-files/
from home import views
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL = views.index
CRISPY_TEMPLATE_PACK= 'bootstrap4'
#managing media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
home/models.py
from django.db import models
class OurPicks(models.Model):
title = models.CharField(max_length=150)
pro_id = models.AutoField
pro_desc = models.TextField()
size = models.CharField(max_length=200)
quantity = models.CharField(max_length=200)
slug = models.SlugField()
sleeves_length = models.CharField(max_length=15)
neck_style = models.CharField(max_length=20)
updated = models.DateTimeField(auto_now=True)
availability = models.BooleanField(default=True)
orignal_price = models.FloatField(blank=True)
discounted_price = models.FloatField(blank=True)
image1 = models.ImageField(upload_to='media', default='')
image2 = models.ImageField(upload_to='media', default='')
image3 = models.ImageField(upload_to='media', default='')
image4 = models.ImageField(upload_to='media', default='')
color = models.CharField(max_length=200)
JEWELLERY = 'JEWELLERY'
KURTIS = 'KURTIS'
LADIES_SUIT = 'LADIES_SUIT'
CATEGORIES = [
(JEWELLERY, 'jewellery'),
(KURTIS, 'kurtis'),
(LADIES_SUIT, 'ladies_suit'),
]
categories = models.CharField(
max_length=11,
choices=CATEGORIES,
default=None,
)
def __str__(self):
return self.title
home/admin.py
from django.contrib import admin
from .models import OurPicks
from core.apps import CoreConfig,AppConfig
from core.models import Orders
# from .modelv1 import Productcolor
#class PicksAdmin(admin.ModelAdmin):
admin.site.register(OurPicks)
home/apps.py
from django.apps import AppConfig
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.