Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error not found url while making post request to specific url with htmx in Django
I am making like function to my blog without page refreshing. But getting error [06/Apr/2022 20:48:26] "POST /like/post/4/ HTTP/1.1" 404 3945 Here what I do base.html with htmx settings <!-- Load from unpkg --> <script src="https://unpkg.com/htmx.org@1.7.0"></script> <script> document.body.addEventListener('htmx:configRequest', (e) => { e.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) </script> views.py def add_like_post(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return HttpResponseRedirect(post.get_absolute_url()) urls.py urlpatterns += [ path('like/post/<int:pk>/', add_like_post, name='like-post'), ] post-detail.html {#<form method="post" action="{% url 'like-post post.id %}">{% csrf_token %}#} <button hx-post="{% url 'like-post' post.id %}" hx-target="#likes" id="likes" hx-swap="outerHTML" class="btn btn-block btn-outline-secondary btn-lg mb-2 mx-auto" name="post_id" value="{{ post.id }}"><i class="fa fa-thumbs-up"> L i k e - {{ post.number_of_likes }}</i></button> {# </form>#} It works fine when I remove htmx settings from button and adding type='submit' and also uncommenting form. Is there are anything which I did wrong -
How to get all field details in a django LogEntry()
I have a LogEntry items I'dlike to call one by one to make a table. So far I have managed to get it working partially with this. <table class="layout"> <thead> <th>User</th> <th>Date</th> <th>Log</th> <th>Item Affected</th> <th>Item ID</th> </thead> {% for log in logs %} <tr> <td>{{ log.user}} - {{ log.user_id }}</td> <td>{{ log.action_time|date:"d/m/Y - g:ia" }}</td> <td>{{ log }}</td> <td>{{ log.object_repr }}</td> <td>{{ log.object_id }}</td> <td>{{ log.change_message }}</td> </tr> {% endfor %} </table> <td>{{ log.change_message }}</td> Gives me data in this format. [{"changed": {"fields": ["Borrower id"]}}] When I try {% for log in logs %} {{ log }} {% endfor %} I get data in this format. Changed “Smart Maths:-MAT/1663/21” — Changed Borrower id. What would I call in my template in order to get this last part only???? Changed Borrower id -
Django/Python - overwrite initial loaded values
I'm quiet new to Django, and I've been struggling with the following: I have a view that initially has set1=0(False) and set2=1(True). A user can swap this,so to set set1=1(True) and set2=0(False). The user can do this by pushing the 'Update' button. My problem is, that it does change in the backend, but the frontend/view/html is not updated. And I have no idea why.. I created a small example, which, if this works, I'll also get my Django case working.. I have the following: views.py So first this view is used, and the initial values for set1 and set2 are set: class MainSettingsView(generic.TemplateView): extra_context = {"main_page": "active"} context_object_name = 'main' template_name = 'index.html' set1 = int(model.set1 == True) set2 = int(model.set2 == True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) model = Setting12.objects.get(pk=1) context['set1'] = int(model.set1 == True) context['set2'] = int(model.set2 == True) return context And then, based on the chosen option in the radio buttons, it changes the model/db and therefore also the set1 and set2: class UpdateButton(generic.TemplateView): extra_context = {"main_page": "active"} context_object_name = 'setting12' template_name = 'index.html' def post(self, request, queryset=None, *args, **kwargs): if update_type == "set1": model = Setting12.objects.get(pk=1) model.set1 = True model.set2 = False return redirect(reverse("main")) elif … -
Can there be two celery instances in a django application?
I have a use case of using two celery instances in a same django application. One celery instance is used for incoming events to the app and the other is to publish an event to an external django application. Doing this is making connections to the celery workers timeout and blocking both the instances. -
Problem with adding objects to manytomany fields
I have a User model: class User(AbstractUser): followers_num = models.IntegerField(default=0) followings_num = models.IntegerField(default=0) followers = models.ManyToManyField('self', null=True, blank=True) followings = models.ManyToManyField('self', null=True, blank=True) And there's a view for adding/removing user objects from followers/followings: def follow(request, follow, user): if (request.method == 'PUT'): following_user = User.objects.get(username=user) follower_user = User.objects.get(username=request.user.username) if follow: # Follow following_user.followers.add(follower_user) following_user.followers_num += 1 follower_user.followings.add(following_user) follower_user.followings_num += 1 else: # Unfollow following_user.followers.remove(follower_user) following_user.followers_num -= 1 follower_user.followings.remove(following_user) follower_user.followings_num -= 1 following_user.save() follower_user.save() return HttpResponse(status=204) I want it to add follower_user to the followers of following_user and add following_user to the followings of follower_user. However, instead of doing so, it adds follower_user not only to the followers of following_user, but it also adds it to the followings of following_user. Why does it happen? -
psycopg2.OperationalError after makemigrations
I am trying to python manage.py makemigrations for a django app in postgres, but I am getting the follow error: psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "backend_db" does not exist Before this, I am doing docker compose up with the following docker-compose and .env file: version: '3.2' services: postgres: image: postgres:13.4 environment: POSTGRES_DB: backend_db POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - database-data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - postgres volumes: database-data: driver: local networks: postgres: driver: bridge DB_NAME='backend_db' DB_USER='postgres' DB_PASSWORD='postgres' # DB_HOST is localhost or the IP of the machine running postgres DB_HOST='localhost' DB_PORT='5432' The part of the settings.py that I define the postgres is the following: DATABASES = { 'default': get_config( 'DATABASE_URL', 'sqlite:///' + BASE_DIR.child('db.sqlite3'), cast=db_url ), 'postgres': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_config('DB_NAME', 'backend_db'), 'USER': get_config('DB_USER', 'postgres'), 'PASSWORD': get_config('DB_PASSWORD', 'postgres'), 'HOST': get_config('DB_HOST', 'postgres-service'), 'PORT': get_config('DB_PORT', '5432') } } Any idea of what causes the error? -
How to use pillow library to make image from letters in django?
When I try to draw images from the pillow library in django website hosted from pythonanywhere server it shows me an error with : OSError at /confession cannot open resource Request Method: POST Request URL: https://luckyklyist.pythonanywhere.com/confession Django Version: 4.0.3 Exception Type: OSError Exception Value: cannot open resource Exception Location: /home/Luckyklyist/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/PIL/ImageFont.py, line 193, in __init__ Python Executable: /usr/local/bin/uwsgi Python Version: 3.9.5 Python Path: ['/home/Luckyklyist/Confess/Confessout', '/var/www', '.', '', '/var/www', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/Luckyklyist/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages'] Server time: Wed, 06 Apr 2022 14:58:13 +0000 My code to work : def confession(request): if request.method=="POST": message=request.POST.get('confession-msg') ide=random() # Drawing image img = Image.new('RGB', (1080, 1080), color=(0, 0, 0)) d1 = ImageDraw.Draw(img) myFont = ImageFont.truetype("arial.ttf", size=40) words = message lines = textwrap.wrap(words, width=60) a = 0 for word in lines: d1.text((0, a), word, fill=(255, 255, 255), font=myFont) a += 40 img.save(f'{ide}.jpeg') imgge='{ide}.jpeg' confess=Confession(message=message,image=imgge) confess.save() disctionary={"message":message,"activehome":"active"} return render(request,"confession.html",disctionary) But when i remove this part from the code it dosent show me error(OSError at /confession): # Drawing image img = Image.new('RGB', (1080, 1080), color=(0, 0, 0)) d1 = ImageDraw.Draw(img) myFont = ImageFont.truetype("arial.ttf", size=40) words = message lines = textwrap.wrap(words, width=60) a = 0 for word in lines: d1.text((0, a), word, fill=(255, 255, 255), font=myFont) a += 40 img.save(f'{ide}.jpeg') Models.py files … -
Convert String to datetime.timedelta
I have an input string as hundreds or thousand of hours, such as: 1000:50 (One thousand hours and 50 minutes) I need to convert it into a timedelta object, in order to insert it as a DurationField in a Django Model. So far, what I tried is to use datetime.strptime but, the error is giving me is: time data '1000:50' does not match format '%H:%M' I tried to google any kind of solution but so far I didn't find a solution that could help me. Even though the DurationField will convert the timedelta in number of days, I just need to have the input to be as thousand or hundreds of hours, after that, the calculation will be handled in the backend. -
Give a single user permission to view another user's account Django
I would like to give user A revokable permission to enter and view user B's account without the need for using the Admin console, but I am not sure how to do this. I already have custom Users setup, which is working well, as follows: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=False, null=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def save(self, *args, **kwargs): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() return super(User, self).save(*args, **kwargs) def __str__(self): return self.email -
You don't have permission for this user error when trying to update profile
Getting the error message "authorize": "You don't have permission for this user." when trying to update a user profile. I can update information from my default user class (ie.username, first_name, last_name etc), but only if I remove all reference to city, country and bio (anything related to information stored in my extended model and keep my update method nested under class Meta:. Here is my serializer: #updating user profile class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city') country = serializers.CharField(source='profile.country') class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False} } def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): #re-writing updated profile info from request user = self.context['request'].user profile = instance.profile if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] instance.save() … -
Django 3.2.9 Url Path İmportError
I have created a django project called "blogprojesi". I want to import the urls.py file inside the application I created with the name "inf" to the urls.py file inside this project, but I am getting the following error ImportError: cannot import name 'inf' from 'blogprojesi' (.....\blogprojesi\blogprojesi_init_.py) I guess somehow it doesn't see the inf app. I tried the Re_path thing but it didn't work. How can I solve this? **urls.py file inside the "blogprojesi"** from django.contrib import admin from django.urls import path,include from blogprojesi import inf from blogprojesi.inf import urls urlpatterns = [ path('admin/', admin.site.urls), path('',inf,include('inf.urls')), ] **Contents of urls.py file inside inf application** from django.urls import path from . import views urlpatterns = [ path("",views.index), path("index",views.index), path("blogs",views.blogs), path("blogs/<int:id>",views.blog_details), ] **Contents of views.py file inside inf application** from http.client import HTTPResponse from django.http.response import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("Home Page") def blogs(request): return HttpResponse("blogs") def blog_details(request,id): return HttpResponse("blog detail: "+id) -
Disable pagination inspector on drf_yasg
Hi guys im using drf_yasg to create my swagger documentation but I have an issue with a PaginationInspector. In one of my views I declare a paginator and, in swagger, is shown as the default pagination for swagger. Something like this count* integer #This info is generated automatically by swagger next string($uri) #This info is generated automatically by swagger x-nullable: true #This info is generated automatically by swagger previous: string($uri) #This info is generated automatically by swagger x-nullable: trueç results: (THE BODY I ACTUALLY WANT TO SHOW) I would like that the swagger ignore that pagination but haven’t found any info related to it. i try using the decorator, initially I though it could be something like @swagger_auto_schema(paginator_inspectors=False) but it doesn't work and I can't find anything usefull on the docs. Thanks in advance oh and just in case this is my view: class CharacterView(ListChView): class OutputSerializer(serializers.Serializer): id = serializers.CharField(source="external_id") created_at = serializers.DateTimeField() pagination_class = CustomPagination -
How to complete the 19.3 from the book Python-Crash-Course.-Eric-Mattes
Trying to complete the 19.3 from the book Python-Crash-Course.-Eric-Mattes. The task is: 19-3. Refactoring: There are two places in views.py where we make sure the user associated with a topic matches the currently logged-in user. Put the code for this check in a function called check_topic_owner(), and call this function where appropriate. views.py ''' from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') @login_required def topics(request): """Show all topics.""" topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): """Show a single topic, and all its entries.""" topic = Topic.objects.get(id=topic_id) # Make sure the topic belongs to the current user. if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): """Add a new topic.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} … -
how to set loader in django app using python and javascript
I'm building a big project using django, and I want the best way to put the loader during operations for Example: code now this function need almost 2 min to finsh the function when this function run the page only loading how i can set a loader while the function run ? for frontend i use (html , css, js) backend ( django - python ) i want simple method In short, I want to set loader while the run functions in django :) -
Two ways to create timezone aware datetime objects (Django). Seven minutes difference?
Up to now I thought both ways to create a timezone aware datetime are equal. But they are not: import datetime from django.utils.timezone import make_aware, get_current_timezone make_aware(datetime.datetime(1999, 1, 1, 0, 0, 0), get_current_timezone()) datetime.datetime(1999, 1, 1, 0, 0, 0, tzinfo=get_current_timezone()) datetime.datetime(1999, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>) datetime.datetime(1999, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>) In the Django Admin GUI second way creates this (German date format dd.mm.YYYY): 01.01.1999 00:07:00 Why are there 7 minutes difference if I use this: datetime.datetime(1999, 1, 1, 0, 0, 0, tzinfo=get_current_timezone()) -
Manifest.json not found Django React
I'm unable to get rid of manifest.json error. I don't want to remove it's link from HTML file. Also I tried every single answer out there on stackoverflow and other sites but nothing worked. Error Image Directory Structure Following are my settings for static files and html files - INSTALLED_APPS = [ '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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'frontend/build'], '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', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'frontend' / 'build' / 'static'] Can you please tell me what's wrong here ? -
If I need to sort objects by a sum of 2 fields, what is the most efficient way to do this [Django]
I have a class called LogSheet that looks like this: class LogSheet(models.Model): calls_logged = models.IntegerField(default=0) texts_logged = models.IntegerField(default=0) What would be the best way to get a queryset that is sorted by the calls_logged + texts_logged. Is there a way to index this query? -
Django write Q filter based on the Form elements
I would like to write django filter for the following scenario. CASE : I have 4 checkboxes box1, box2, box3, box4 and a submit button on my HTML page. I have written model post with 6 fieldd where 4 fields corresponds to box1,2,3,4. Based on the user input (4 checkboxes) it should filter the post. However does this mean i have to write 16 scenarios 4x4. or is it possible to formulate it in a better way. post.objects.filter(Q(id=1),Q(sid=1),Q(pid=1),Q(kid=1)) # case 1 post.objects.filter(Q(id=1),Q(sid=1)) post.objects.filter(Q(id=1),Q(kid=1)) post.objects.filter(Q(id=1),Q(pid=1)) post.objects.filter(Q(kid=1),Q(sid=1)) . . . post.objects.filter(Q(kid=1)) Is there a better way to do it? -
Rename Filter Label Model Admin Django
Is it possible to change this label in the list filter from model admin without creating a custom filter? I'm using the same table for 2 different fields and user needs to filter the table using both fields (separately or combining them). Without the rename in the Admin view will have 2 filters with same name applying to different fields. Not the best ux. -
how to filter users in admin panel?
I have a task form in my app. Django is informing owners that someone has sent a task and they need to assign a particular person to this task (by choosing user in column owner) from the admin panel. There can be only 1 person assigned to each task. My problem is that people who are assigning tasks can see the list of all users and I want to filter users in this dropdown list only to users that are in a group named "owners". Question Is there any way to filter users that are displayed in the dropdown list? models.py class TaskRquest(models.Model): title = models.CharField(max_length=1000, blank=True, null=True, default='') body = models.TextField('Description') priority = models.BooleanField(default=False, blank=True, null=True) publish_date = models.DateTimeField('publish', default=timezone.now) owner = models.OneToOneField(User, blank=True, null=True, on_delete=models.DO_NOTHING) admin.py class TaskRquestAdmin(ImportExportModelAdmin): list_display = ('title', 'publish_date', 'priority', 'owner') admin.site.register(TaskRquest, TaskRquestAdmin) -
I want more optimizing Django ORM
I have this model: class Actor(models.Model): act_id = models.AutoField(primary_key=True) act_name = models.CharField(max_length=125) act_gender = models.CharField(max_length=1) class Casting(models.Model): actor = models.ForeignKey('Actor', on_delete=models.CASCADE) movie = models.ForeignKey('product.Movie', on_delete=models.CASCADE) part = models.CharField(max_length=25, null=True) class Movie(TimeStampModel): mov_id = models.AutoField(primary_key=True) mov_title = models.CharField(max_length=200) director = models.ForeignKey('participant.Director', on_delete=models.CASCADE) I want this result: <QuerySet [{'actor_id__act_name': 'Dwayne Johnson', 'actor_id__act_id': 24}, {'actor_id__act_name': 'met smith', 'actor_id__act_id': 25}, {'actor_id__act_name': 'Will Smith', 'actor_id__act_id'__act_name': 'Vin Diesel', 'actor_id__act_id': 27}, {'actor_id__act_name': 'Chris Pratt', 'actor_id__act_id': 28}, {'actor_id__act_name': 'Ryan Reynolds', 'actor_id__act_id': 29}]> I wrote this code: Casting.objects.filter(movie_id=1).select_related('actor').values('actor_id__act_name', 'actor_id__act_id') I want to write an optimized ORM. Please suggest a better code. -
Test celery task with django
I´m trying test a celery task in my django project using the same database as django test. In my setup I have databases = '__all__' @classmethod def setUpClass(cls): super().setUpClass() # Start up celery worker cls.celery_worker = start_worker(app, perform_ping_check=False) cls.celery_worker.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() # Close worker cls.celery_worker.__exit__(None, None, None) But i got psycopg2.InterfaceError: connection already closed when run cls.celery_worker.enter(). Somebody can help me? -
Using Class-Based Views with Function-Based Views together in Django
Is it possible to use Class-Based Views with Function-Based Views together in django project? If yes, Is that best practice ? Can I use them together in the same views.py -
Parent form not getting values from child form during child object initialization in Django
I created a basic form in django. class basicform(forms.Form): br = ((None,' '),('CSE','CSE'),('ECE','ECE'),('IT','IT')) se = ((None,' '),('M','Male'),('F','Female'),('O','Others')) secx = ((None,' '),('A','A'),('B','B'),('C','C'),('D','D')) roll_no = forms.CharField(required=False,label='Roll No:') name = forms.CharField(required=False,label='Name:') sex = forms.ChoiceField(required=False,choices=se,label='Gender:') branch = forms.ChoiceField(required=False,choices=br,label='Branch:') sec = forms.ChoiceField(required=False,choices=secx,label='Section:') i made another form class marks(basicform): s11 = forms.DecimalField(max_value=100,min_value=0) s12 = forms.DecimalField(max_value=100,min_value=0) s13 = forms.DecimalField(max_value=100,min_value=0) ...... def __init__(self,*args,**kwargs): super(marks,self).__init__(*args,**kwargs) self.fields['name'].disabled = True self.fields['roll_no'].disabled = True self.fields['sex'].disabled = True self.fields['branch'].disabled = True self.fields['sec'].disabled = True the issue is, i am taking post data from the base form, and i want that data to be assigned into the child (i.e. marks object) mark = marks(data = request.POST) this is what i'm trying to do. keep in mind the post data is from the base class(i.e. basicform), i'm under the assumption that the 'data' parameter would be passed onto the super class and therefore values would be assigned, but that is not the case. what am i doing wrong? def create(request): global form if request.method == 'POST': form = basicform(data = request.POST) if form.is_valid(): mark = marks(data = request.POST) mark.full_clean() print(form.cleaned_data) print(mark.cleaned_data) this is an excerpt from my view, here the print statements are for debugging and as i mentioned before, 'form' variable has the values … -
Django - Admin Area - I can't delete a user from users (User matching query does not exist.)
I created a Users app. In models i create a Profile and signals. In admin area i can create a new user end is created a Profile as well. When i delete the new user form Profile is also deleted from Users and is ok. But if i try to delete the new user from Users area i got error message: "DoesNotExist at /admin/auth/user/3/delete/ - User matching query does not exist". I dont know why ? Any suggestion ? I run and apply all the migrations and also i delete and create another database but is not solve this issue. models.py from django.db import models from django.contrib.auth.models import User from PIL import Image from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) username = models.CharField(max_length=200, blank=True, null=True) nume = models.CharField(max_length=200, blank=True, null=True) avatar = models.ImageField ( upload_to ='utilizatori/', default='utilizatori/avatar_profilearning.jpg', verbose_name='Avatar (320px * 320px)') departament = models.CharField(max_length=200, blank=True, null=True) functie = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) descriere = RichTextUploadingField(external_plugin_resources=[( 'emojione', '/static/src/plugins/ckeditor_plugins/emojione/' , 'plugin.js', )], config_name='default') creat = models.DateTimeField(auto_now_add=True) #pentru a redimensiona rezolutia avatarului incarcat def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img = Image.open(self.avatar.path) if img.height > 320 or img.width > …