Django - Pillow - Create and Save Image - django-models

I would like to generate an image and write to the database from the person's name from a Model.
from django.db import models
from uuid import uuid4
from PIL import Image, ImageDraw, ImageFont, ImageColor
def generateImage(text='A'):
imagem = Image.new("RGB", (30, 30))
pixel_set = imagem.load()
for row in range(30):
for col in range(30):
pixel_set[col, row] = ImageColor.getcolor("#FFFFFF", "RGB")
imagemText = ImageDraw.Draw(imagem)
imagemText.text((10, 10), text, font=ImageFont.truetype('arial.ttf', 20),
fill=ImageColor.getcolor("#000000", "RGB"), stroke_width=1)
# imagem.show()
return imagem
def upload_image_name(instance):
return f"{instance.id}-generated"
# Create your models here.
class Name_Image(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
name = models.CharField(max_length=255)
image = models.ImageField(upload_to=upload_image_name, blank=True, null=True, default=generateImage)
on settings.py I pass:
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
on urls.py:
route = routers.DefaultRouter()
route.register('name_image', name_imageviewsets.Name_ImageViewSet, basename="Name_Image")
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(route.urls))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
just passing the name, i get null on image.
HTTP 201 Created
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"id": "edf347b7-b0fa-4c9e-b73c-41e6aa12cec2",
"name": "Test",
"image": null
}
How can I use created image write to database and configured folder

Related

not able register my model to wagtail admin using wagtail_hooks.py

wagtail 4.1 It seems that I did everything as stated in the documentation, but my models do not appear in the admin panel.path
my model:
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
cover_photo = models.ForeignKey(
'wagtailimages.Image',
null=True, blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
panels = [
FieldPanel('title'),
FieldPanel('author'),
FieldPanel('cover_photo')
]
my wagtail_hooks.py
class BookAdmin(ModelAdmin):
model = Book
menu_label = 'Book' # ditch this to use verbose_name_plural from model
menu_icon = 'pilcrow' # change as required
menu_order = 201 # will put in 3rd place (000 being 1st, 100 2nd)
add_to_settings_menu = True # or True to add your model to the Settings sub-menu
exclude_from_explorer = True # or True to exclude pages of this type from Wagtail's explorer view
list_display = ('title', 'author')
list_filter = ('author',)
search_fields = ('title', 'author')
# Now you just need to register your customised ModelAdmin class with Wagtail
modeladmin_register(BookAdmin)
I also registered my applications
INSTALLED_APPS = [
...
"news",
"app",
"wagtail.contrib.modeladmin",
]
what can i miss?

AttributeError at admin: 'NoneType' object has no attribute 'startswith'

Below is my error:
AttributeError at /admin/r/31/3/
'NoneType' object has no attribute 'startswith'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/r/31/3/
Django Version: 3.2.13
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'startswith'
Exception Location: C:\github\project\venv\lib\site-packages\django\contrib\contenttypes\views.py, line 41, in shortcut
Python Executable: C:\github\project\venv\Scripts\python.exe
Python Version: 3.7.1
This occurs when I'm trying to access certain type of model via admin, since I cannot access it through the tag related to get_absolute_url function of the model. The template appears, but never let me access the get_absolute_url.
The thing is, there is another model in another app which is almost identical in views.py, urls.py and models.py but only difference is 'permission_required' decorator which I can't sure if it's outdated.
views.py of error model.
from django.urls import reverse_lazy
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.decorators import login_required, permission_required
from .models import *
def landing(request):
return render(
request,
'instructor/landing.html'
)
def paymentrequired(request):
return render(
request,
'instructor/paymentrequired.html'
)
def lecture_in_category(request, category_slug=None):
current_category = get_object_or_404(Category, slug=category_slug)
categories = Category.objects.all()
lectures = Lecture.objects.filter(category=current_category)
return render(request, 'instructor/lecture_list.html',
{'current_category': current_category, 'categories': categories, 'lectures': lectures})
class LectureDetail(DetailView):
model = Lecture
def lecture_detail(request, id):
lecture = get_object_or_404(Lecture, id=id)
return render(request, 'instructor/lecture_detail.html', {'lecture':lecture})
# Create your views here.
models.py of the error page
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
import os
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
meta_description = models.TextField(blank=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True, allow_unicode=True)
class Meta:
ordering = ['name']
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('instructor:lecture_in_category', args=[self.slug])
class Lecture(models.Model):
title = models.CharField(max_length=40)
description = models.CharField(max_length=200, blank=True)
video_key = models.CharField(max_length=20, blank=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True, allow_unicode=True)
video_upload = models.FileField(upload_to='instructor/files/%Y/%m/%d', blank=True)
head_image = models.ImageField(upload_to='instructor/images/%Y/%m/%d', blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
available_display = models.BooleanField('Display', default=True)
author = models.CharField(max_length=40)
category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL)
class Meta:
ordering = ['-created_at']
index_together = [['id', 'slug']]
def __str__(self):
return self.title
def get_absolute_url(self):
reverse('instructor:lecture_detail', args=[self.id, self.slug])
# Create your models here.
urls.py of the error page
from django.urls import path
from . import views
from .views import *
app_name = 'instructor'
urlpatterns = [
path('', landing, name='landing'),
path('<slug:category_slug>/', lecture_in_category, name='lecture_list_category'),
path('<int:id>/<lecture_slug>/', LectureDetail.lecture_detail, name="lecture_detail"),
path('payment_required/', paymentrequired, name="paymentrequired"),
]
this is my database setting
DATABASES = {
'default': {
'ENGINE': os.environ.get("SQL_ENGINE", 'django.db.backends.sqlite3'),
'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')),
'USER': os.environ.get('SQL_USER', 'user'),
'PASSWORD': os.environ.get('SQL_PASSWORD', 'password'),
'HOST': os.environ.get('SQL_HOST', 'localhost'),
'PORT': os.environ.get("SQL_PORT", '5432'),
}
}
This is the traceback.
Traceback (most recent call last):
File "C:\github\rhizomeedu\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\contrib\admin\sites.py", line 250, in wrapper
return self.admin_view(view, cacheable)(*args, **kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "C:\github\rhizomeedu\venv\lib\site-packages\django\contrib\contenttypes\views.py", line 41, in shortcut
if absurl.startswith(('http://', 'https://', '//')):
AttributeError: 'NoneType' object has no attribute 'startswith'
With that model, the error doesn't appear so I once deleted the decorator but the result was same.
So I assume it's about settings.py ..?
Help me.

AbstractBaseUser.get_username() missing 1 required positional argument: 'self' | Error while accessing current user's username

I am trying to access the Id of current logged in User. but i am getting the below error.
models.py of derived model
from django.db import models
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from accounts.models import CustomUser
# Create your models here.
class PostProblem(models.Model):
problem_type_choices = (
('c','Confidential'),
('sc','Semi-confidential'),
('p','Public')
)
problem_category_choices = (
('agriculture','Agriculture'),
('computer_science','Computer Science'),
('social_studies','Social Studies'),
('environment','Environmental Science'),
('mathematics','Mathematics'),
('engineering','Engineering'),
('physics','physics'),
('chemistry','chemistry'),
('other','Other')
)
author = models.ForeignKey("accounts.CustomUser", verbose_name= "Creater", default = CustomUser.get_username ,on_delete=models.CASCADE)
problem_title = models.CharField(max_length=200, verbose_name="Problem's title")
problem_type = models.CharField(choices=problem_type_choices,max_length=5, verbose_name='Confidentiality of the problem ')
problem_category = models.CharField(choices=problem_category_choices, max_length=50, verbose_name="Catrgory of the problem")
problem_brief = models.CharField(max_length=1000, verbose_name='Breif description of the problem ')
problem_description = models.TextField(verbose_name='Problem complete description ')
problem_reward = models.IntegerField(verbose_name='Prize money for providing the solution ')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now
self.save()
def __str__(self):
return self.problem_title
def get_absolute_url(self):
return reverse("problem_detail", kwargs={"pk": self.pk})
def approve_solutions(self):
return self.solutions.filter(approved_solutions = True)
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
from problems.models import PostProblem, Solutions
from problems.forms import PostProblemForm, SolutionsForm
from django.views.generic import TemplateView, CreateView, DetailView, DeleteView, UpdateView, ListView
# Create your views here.
class PostProblemCreateView(CreateView, LoginRequiredMixin):
login_url = 'login/'
redirect_field_name = 'problems/problem_detail.html'
form_class = PostProblemForm
model = PostProblem
forms.py
from django import forms
from problems.models import PostProblem, Solutions
class PostProblemForm(forms.ModelForm):
class Meta:
model = PostProblem
fields = ("problem_title","problem_type","problem_category","problem_brief","problem_description","problem_reward")
widgets = {
'problem_title':forms.TextInput(attrs={'class':'textinputclass'}),
'problem_type': forms.TextInput(attrs={'class':'choice_input'}),
'problem_category':forms.TextInput(attrs={'class':'choice_input'}),
'problem_brief': forms.Textarea(attrs={'class':'editable medium-editor-textarea post_brief'}),
'problem_description': forms.Textarea(attrs={'class':'editable medium-editor-textarea post_complete'}),
'problem_reward': forms.TextInput(attrs={'class':'textinputclass'})
}
model.py of base model
from django.db import models
from django.contrib import auth
from django.urls import reverse
# Create your models here.
# for custom user
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, User
from .managers import CustomUserManager
class CustomUser(AbstractBaseUser, PermissionsMixin):
'''Model representation for user'''
user_type_choices = (
('ps','Problem Solver'),
('pp','Problem Provider')
)
account_type_choices = (
('o','Organization'),
('i','Individual')
)
user_type = models.CharField(max_length=5, choices=user_type_choices, default='pp', verbose_name="Who you are? ")
account_type = models.CharField(max_length=5, choices= account_type_choices, default='o', verbose_name="Account Type ")
email = models.EmailField(max_length=50, unique=True, blank=False, verbose_name="Your Email ")
is_active = models.BooleanField(default=True) # anyone who signs up for thsi application is by default an active user
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False) # the person who has highest level of control over database
# need to specify manager class for this user
objects = CustomUserManager()
# we are not placing password field here because the password field will always be required
REQUIRED_FIELDS = ['user_type', 'account_type']
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
I searched the web for answers but they have mentioned only about accessing current user id in function based views. How can I resolve this kind of error? I am new to Django.

Cannot access database instances with id=pk

Here is my views.py file. I input the required fields through form like this:
from django.shortcuts import render, redirect
from .models import nekor_Table
from .forms import user_form
def home(request):
user_form_obj = user_form()
if request.method == "POST":
form = user_form(request.POST)
if form.is_valid():
form.save()
else:
form = user_form_obj()
context = {'user_form_obj': user_form_obj}
return render(request, 'polls/home.html', context )
def nav(request):
return render(request, 'navbar.html')
def display(request, pk):
display_table_obj = nekor_Table.objects.get(id=pk)
context = {'display_table_obj': display_table_obj}
return render(request, 'polls/display_page.html', context)
i have two tables and when i try to get individual instance with id=pk, and running http://127.0.0.1:8000/display/1/ in my browser it gives me: nekor_Table matching query does not exist, error. what am i missing here? this was working just fine in my previous project but doesnt work in this one.
here is my urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('index/', views.home, name='home'),
path('navbar/', views.nav, name='navbar'),
path('display/<int:pk>/', views.display, name='display')
]
and here is my models.py
from django.db import models
from django.contrib.auth.models import User
class nekor_Table(models.Model):
title = models.CharField(max_length=200, null=True, blank=False)
place = models.CharField(max_length=200, null=True, blank=False)
deity = models.CharField(max_length=200, null=True, blank=False)
description = models.TextField(null=True, blank=False)
teachers = models.CharField(max_length=200, null=True, blank=False)
architecture = models.CharField(max_length=200, null=True, blank=False)
def __str__(self):
return self.title

serializer.is_valid() = false when posting an object from AngularJS frontend to Django backend

I have an AngularJS front-end and a Django backend.
The front-end calls the backend using the following two $http calls:
athleticsApp.controller('athletesListController', ['$scope', '$http', function($scope, $http) {
$scope.athletes = [];
$scope.getAthletes = function(){
$http
.get('http://serverip:8666/athletics/athletes/')
.success(function(result) {
$scope.athletes = result;
})
.error(function(data, status) {
console.log(data);
console.log(status);
});
}
$scope.init = function() {
$scope.getAthletes();
}
$scope.init();
}]);
athleticsApp.controller('athleteNewController', ['$scope', '$http', function($scope, $http) {
$scope.athlete = {
firstName : '',
lastName : ''
};
$scope.postNewAthlete = function(){
$http
.post('http://serverip:8666/athletics/athletes/', $scope.athlete)
.success(function(result) {
// set url fraction identifier to list athletes
})
}
}]);
The GET call is a success. The POST call generates the following error:
400 (BAD REQUEST)
When I run the Python debugger I can see that serializer.is_valid() is false.
(Pdb) serializer = AthleteSerializer(data=request.data)
(Pdb) serializer
AthleteSerializer(data={u'lastName': u'Smith', u'firstName': u'John'}):
first_name = CharField(max_length=30)
last_name = CharField(max_length=30)
(Pdb) serializer.is_valid()
False
The Django code looks like this:
urls.py
from django.conf.urls import patterns, url
from views import Athletes
urlpatterns = [
url(r'^athletes/', Athletes.as_view()),
]
views.py
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Athlete
from django.shortcuts import get_object_or_404, render
from athletics.serializers import AthleteSerializer
class Athletes(APIView):
def get(self, request, format=None):
import pdb; pdb.set_trace()
all_athletes = Athlete.objects.all()
serializer = AthleteSerializer(all_athletes, many=True)
return Response(serializer.data)
def post(self, request, format=None):
import pdb; pdb.set_trace()
serializer = AthleteSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
creation_data = serializer.save()
return Response()
def index(request):
return render(request, 'athletics/index.html')
serializers.py
from rest_framework import serializers
from .models import Athlete
class AthleteSerializer(serializers.ModelSerializer):
class Meta:
model = Athlete
fields = (
'first_name',
'last_name'
)
settings.py
"""
Django settings for mysitedjango project.
Generated by 'django-admin startproject' using Django 1.8.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# 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 = 'secretkey'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
INTERNAL_IPS = (
'myip'
)
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = []
# Application definition
REQUIRED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third party apps
'rest_framework',
)
PROJECT_APPS = (
# This project
'athletics',
'testetics',
)
INSTALLED_APPS = REQUIRED_APPS + PROJECT_APPS
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',
'django.contrib.messages.middleware.MessageMiddleware',
'corsheaders.middleware.CorsMiddleware',
)
ROOT_URLCONF = 'mysitedjango.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 = 'mysitedjango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Stockholm'
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/'

Resources