I am trying to make a customer and employee login and register page...however whenever I try to go to localhost:8000/customer register, I get a page not found error not found error. this is my
urls.py file:
from django.contrib import admin
from django.urls import path
from accounts import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.register, name = 'register'),
path('customer_resgister', views.customer_register.as_view(), name = 'customer_register'),
]
views.py:
from django.shortcuts import render
from django.views.generic import CreateView
from .models import User, Customer, Employee
from .forms import CustomerSignupForm, EmployeeSignupForm
# Create your views here.
def register(request):
return render(request, 'accounts/register.html')
class customer_register(CreateView):
model = User
form_class = CustomerSignupForm
template_name = 'accounts/customer_register.html'
#def customer_register(request):
models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
first_name = models.CharField(max_length = 150)
last_name = models.CharField(max_length = 150)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
Phone_no = models.CharField(max_length = 10)
location = models.CharField(max_length = 150)
class Employee(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
Phone_no = models.CharField(max_length = 10)
designation = models.CharField(max_length = 150)
forms.py:
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from .models import Customer, Employee, User
from django import forms
class CustomerSignupForm(UserCreationForm):
first_name = forms.CharField(required = True)
last_name = forms.CharField(required = True)
phone_no = forms.CharField(required = True)
class Meta(UserCreationForm.Meta):
model = User
#transaction.atomic
def data_save(self):
user = super().save(commit = False)
user.first_name = self.cleaned_data.get('first_name')
user.last_name = self.cleaned_data.get('last_name')
user.save()
customer = Customer.objects.create(user = user)
customer.phone_no = self.cleaned_data.get('phone_no')
customer.save()
return user
class EmployeeSignupForm(UserCreationForm):
first_name = forms.CharField(required = True)
last_name = forms.CharField(required = True)
designation = forms.CharField(required = True)
class Meta(UserCreationForm.Meta):
model = User
#transaction.atomic
def data_save(self):
user = super().save(commit = False)
user.first_name = self.cleaned_data.get('first_name')
user.last_name = self.cleaned_data.get('last_name')
user.save()
employee = Employee.objects.create(user = user)
employee.phone_no = self.cleaned_data.get('phone_no')
employee.designation = self.cleaned_data.get('designation')
customer.save()
return user
settings.py:
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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'apk-h*1!*f-=^6zw^_q0q!z6att9f+exfr+k(!awfvybu^x(l%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'accounts.User'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts'
]
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 = 'demo_register.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 = 'demo_register.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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 = 'UTC'
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/'
All my templates are stored in accounts/templates/accounts
I don't know what am I doing wrong here...please help.
I don’t think the issue is with your templates. A 404 error shows when the url cannot map to the correct view.
You can share the error page snippet and you can also try and add a slash to your url path for customer_register
You have a typo in the third path in url_patterns, it should be register instead of 'resgister'.
Use space instead of underscore
url_patterns = [
path('customer register', views.customer_register.as_view(), name = 'customer_register')
]
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I got stock with writing custom user in Django an rest framework.I've written custom user and custom serializer, I've added every necessaries in settings.py.
When I try to go to user app I get this error:
ImproperlyConfigured at /api/user/
Field name ia_superuser is not valid for model CustomUser.
Request Method: GET
Request URL: http://127.0.0.1:8000/api/user/
Django Version: 3.0.8
Exception Type: ImproperlyConfigured
Exception Value:
Field name ia_superuser is not valid for model CustomUser.
Exception Location: C:\Users\Aireza.virtualenvs\lcodev-lF6rFvWb\lib\site-packages\rest_framework\serializers.py in build_unknown_field, line 1340
Python Executable: C:\Users\Aireza.virtualenvs\lcodev-lF6rFvWb\Scripts\python.exe
Python Version: 3.10.2
Python Path:
['F:\Python\lcodev\ecom',
'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\python310.zip',
'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\DLLs',
'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\lib',
'C:\Users\Aireza\AppData\Local\Programs\Python\Python310',
'C:\Users\Aireza\.virtualenvs\lcodev-lF6rFvWb',
'C:\Users\Aireza\.virtualenvs\lcodev-lF6rFvWb\lib\site-packages']
Server time: Tue, 22 Mar 2022 11:34:45 +0000
I have an api app in the project and the user app is in the api app.
anyone can help?
thanks
here's everything:
user serializer.py:
from rest_framework import serializers
from .models import CustomUser
from django.contrib.auth.hashers import make_password
from rest_framework.decorators import authentication_classes,permission_classes
class UserSerializer(serializers.HyperlinkedModelSerializer):
def create(self,validated_data):
password = validated_data.pop('password',None) # pop method removes the given index from the list and returns it
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
def update(self,instance , validated_data):
for attr,value in validated_data.item():
if attr == 'password':
instance.set_password(value)
else:
setattr(instance,attr,value)
instance.save()
return instance
class Meta:
model = CustomUser
extra_kwargs = {'password':{'write_only':True}}
fields = ('name' , 'email' , 'phone' ,'password','is_active' , 'is_staff', 'ia_superuser',)
read_only_fields = ('email',)
user model.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
name = models.CharField(max_length=50,default='user')
email = models.EmailField(max_length=200 , unique=True)
phone = models.CharField(max_length=20,blank=True,null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
username = None # we dont want the user to be logged in by username
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
session_token = models.CharField(max_length=10,default=0)
user views.py:
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from .models import CustomUser
from .serializers import UserSerializer
from django.http import JsonResponse
from django.contrib.auth import get_user_model,login,logout
from django.views.decorators.csrf import csrf_exempt
import random , re
# Create your views here.
def generate_session_token(length = 10):
return ''.join(random.SystemRandom().choice(
[chr(i) for i in range(97,123)] + [str(j) for j in range(10)]
) for k in range(length))
#csrf_exempt
def signin(request):
if not request.method == 'POST':
return JsonResponse({'error': 'Send a post request with valid paramenter only'})
# print(request.POST.get('email', None)) - if you will not get email, None will be printed
username = request.POST['email']
password = request.POST['password']
print(username)
print(password)
# validation part
if not re.match("^[\w\.\+\-]+\#[\w]+\.[a-z]{2,3}$", username):
return JsonResponse({'error': 'Enter a valid email'})
if len(password) < 3:
return JsonResponse({'error': 'Password needs to be at least of 3 char'})
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
if user.check_password(password):
usr_dict = UserModel.objects.filter(
email=username).values().first()
usr_dict.pop('password')
if user.session_token != "0":
user.session_token = "0"
user.save()
return JsonResponse({'error': "Previous session exists!"})
token = generate_session_token()
user.session_token = token
user.save()
login(request, user)
return JsonResponse({'token': token, 'user': usr_dict})
else:
return JsonResponse({'error': 'Invalid password'})
except UserModel.DoesNotExist:
return JsonResponse({'error': 'Invalid Email'})
def signout(request, id):
logout(request)
UserModel = get_user_model()
try:
user = UserModel.objects.get(pk=id)
user.session_token = "0"
user.save()
except UserModel.DoesNotExist:
return JsonResponse({'error': 'Invalid user ID'})
return JsonResponse({'success': 'Logout success'})
class UserViewSet(viewsets.ModelViewSet):
permission_classes_by_action = {'create' : [AllowAny]}
queryset = CustomUser.objects.all().order_by('id')
serializer_class = UserSerializer
def get_permissions(self):
try:
return [permission() for permission in self.permission_classes_by_action[self.action]]
except KeyError:
return [permission() for permission in self.permission_classes]
api migrations 0001_initial.py:
from django.db import migrations
from api.user.models import CustomUser
class Migration(migrations.Migration):
def seed_data(apps, schema_editor):
user = CustomUser(name="hitesh",
email="hitesh#lco.dev",
is_staff=True,
is_superuser=True,
phone="987654321",
)
user.set_password("12345")
user.save()
dependencies = [
]
operations = [
migrations.RunPython(seed_data),
]
user urls.py:
from django.urls import path,include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('',views.UserViewSet)
urlpatterns = [
path('login/',views.signin, name = 'signin'),
path('logout/<int:id>/',views.signout, name = 'signout'),
path('user/',views.UserViewSet),
path('',include(router.urls)),
]
settings.py:
"""
Django settings for ecom project.
Generated by 'django-admin startproject' using Django 3.0.8.
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__)))
# 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 = 'iqlfys_luymme_hqvp-+!iy#xnk2)(m(k=4!_tl4xpr9gqmofs'
# 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',
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'api',
'api.category',
'api.product',
'api.user',
'api.order',
'api.payment'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'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 = 'ecom.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 = 'ecom.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/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
AUTH_USER_MODEL = "user.CustomUser"
CORS_ORIGIN_ALLOW_ALL = True
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication'
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
perhaps you are looking for is_superuser?
ref: https://docs.djangoproject.com/en/4.0/ref/contrib/auth/#django.contrib.auth.models.User.is_superuser
Edited:
I think you'll just need to update the UserSerializer class as such:
class UserSerializer(serializers.HyperlinkedModelSerializer):
def create(self,validated_data):
...
return instance
def update(self,instance , validated_data):
...
return instance
class Meta:
model = CustomUser
extra_kwargs = {'password':{'write_only':True}}
fields = (
'name' ,
'email',
'phone',
'password',
'is_active',
'is_staff',
'is_superuser',)
# note: it's changed from "ia_superuser" to "issuperuser"
read_only_fields = ('email',)
I have a piece of code throwing an error:
TypeError: 'ModelSignal' object is not callable.
While I'm gonna add signals in my project, this error is occuring.
Why this type of error is occured? What you need to know to give my answer?
Please help me someone. I'm a newbie to Django. Thanks in advance.
Here is my views.py file:
def registerPage(request):
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
user =form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account successfully created for ' + username)
return redirect ('login')
context = {'form': form}
return render(request, 'accounts/register.html', context)
My models.py file:
from django.db import models
from django.contrib.auth.models import User
class Student(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
profile_pic = models.ImageField(default= 'default-picture.jpg', null= True, blank= True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return str(self.name)
My signals.py file:
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from .models import Student
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
)
post_save(student_profile, sender= User)
My apps.py file:
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'accounts'
def ready(self):
import accounts.signals
And my settings.py file:
from pathlib import Path
import os
# 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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1dcgsc#63l$2w_%+90xqra#z=&(q!8sdxf*dg7k6=ptxi&k8o*'
# 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',
'accounts.apps.AccountsConfig',
'django_filters',
]
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 = 'cmp.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 = 'cmp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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/Dhaka'
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/'
MEDIA_URL = '/images/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
You are calling the post_save object which is not callable. Try post_save.connect().
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from .models import Student
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
)
post_save.connect(student_profile, sender= User)
Or you can also try using receiver decorator:
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from django.dispatch import receiver
from .models import Student
#receiver(post_save, sender=User)
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
).save()
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 trying to store the questions tag in sqlite3 of Django but whenever I am trying to click on Question in /admin/ it shows error :
error image
in case image is not displayed, this is error
{
OperationalError at /admin/userinfo/question/
no such table: userinfo_question
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/userinfo/question/
Django Version: 3.0.5
Exception Type: OperationalError
Exception Value:
no such table: userinfo_question
}
I have already tried
changing sqlite3 path in settings (error not resolved same error)
python manage.py migrate --run-syncdb (after applying makemigrations)(migrations apply error not resolved)
this was written while doing migrations
Creating tables...
Running deferred SQL...
so I am thinking that the table is creating but not displaying( might be)
this is my models.py
'''
from django.db import models
# Create your models here.
class Question(models.Model):
prob_link = models.CharField(max_length=500, default='')
prob_level = models.CharField(max_length=1)
prob_rating = models.IntegerField()
expression_parsing = models.BooleanField(default=False)
fft = models.BooleanField(default=False)
two_pointers = models.BooleanField(default=False)
binary_search = models.BooleanField(default=False)
dsu = models.BooleanField(default=False)
strings = models.BooleanField(default=False)
number_theory = models.BooleanField(default=False)
data_structures = models.BooleanField(default=False)
hashing = models.BooleanField(default=False)
shortest_paths = models.BooleanField(default=False)
matrices = models.BooleanField(default=False)
string_suffix_structures = models.BooleanField(default=False)
graph_matchings = models.BooleanField(default=False)
dp = models.BooleanField(default=False)
dfs_and_similar = models.BooleanField(default=False)
meet_in_the_middle = models.BooleanField(default=False)
games = models.BooleanField(default=False)
schedules = models.BooleanField(default=False)
constructive_algorithms = models.BooleanField(default=False)
greedy = models.BooleanField(default=False)
bitmasks = models.BooleanField(default=False)
divide_and_conquer = models.BooleanField(default=False)
flows = models.BooleanField(default=False)
geometry = models.BooleanField(default=False)
math = models.BooleanField(default=False)
sortings = models.BooleanField(default=False)
ternary_search = models.BooleanField(default=False)
combinatorics = models.BooleanField(default=False)
brute_force = models.BooleanField(default=False)
implementation = models.BooleanField(default=False)
sat_2 = models.BooleanField(default=False)
trees = models.BooleanField(default=False)
probabilities = models.BooleanField(default=False)
graphs = models.BooleanField(default=False)
chinese_remainder_theorem = models.BooleanField(default=False)
interactive = models.BooleanField(default=False)
other_tag = models.BooleanField(default=False)
special_problem = models.BooleanField(default=False)
'''
here is settings.py
"""
Django settings for codeforces_crawler project.
Generated by 'django-admin startproject' using Django 3.0.2.
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__)))
# 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 = 'sp_$b%e_g1v)eam^rqlef5v8##&6qhxw1&2f6me^c!b^v+rkwl'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'userinfo.apps.UserinfoConfig',
'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 = 'codeforces_crawler.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 = 'codeforces_crawler.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/'
this is views.py
from django.shortcuts import render
from .scraping import scrape
def index(request):
return render(request, 'userinfo/index.html')
def detail(request):
user = request.POST['user'] # user is the name of the input
# rank,color,ar,institute,ac,wa,tle,rte,mle,challenged,cpe,skipped,ile,other = scrape(user)
verdict = scrape(user)
if verdict == False:
exists = verdict
return render(request, 'userinfo/detail.html', {'exists': exists})
else:
exists = verdict[0]
rank = verdict[1]
color = verdict[2]
ar = verdict[3]
institute = verdict[4]
ac = verdict[5]
wa = verdict[6]
tle = verdict[7]
rte = verdict[8]
mle = verdict[9]
challenged = verdict[10]
cpe = verdict[11]
skipped = verdict[12]
ile = verdict[13]
other = verdict[14]
rating = verdict[15]
return render(request, 'userinfo/detail.html',
{'exists': exists, 'user': user, 'rank': rank, 'color': color, 'ar': ar, 'institute': institute,
'ac': ac, 'wa': wa, 'tle': tle, 'rte': rte, 'mle': mle, 'challenged': challenged
, 'cpe': cpe, 'skipped': skipped, 'ile': ile, 'other': other, 'rating': rating})
# return render(request, 'userinfo/detail.html', {'user': user, 'verdict':verdict,})
this is admin.py
'''
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)
'''
this is url.py
from django.urls import path
from . import views
app_name = 'userinfo'
urlpatterns = [
path('',views.index, name='index'),
path('detail/',views.detail,name='detail'),
]
or if there is any other method to see what questions had been added in my database.
Not able to resolve this error for the last 3 days.Thanks in advance for your help.
The error message "no such table: userinfo_question" indicates that Django has not turned your model representation into tables within your database.
Check that your app userinfo is listed under INSTALLED_APPS in settings.py.
You should also run makemigrations before running migrate
python manage.py makemigrations