Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
upgrade django app from version 2 to the new(4)
How do I upgrade my django app from version 2 to the new(4). how to correctly and simply update the code, how to do it. here are the versions of all libraries It works on python 3.7.4 Babel==2.7.0 certifi==2019.6.16 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 Django==2.2.8 django-cas-ng==3.6.0 django-enum-choices==2.1.1 django-extensions==2.2.1 django-filter==2.1.0 django-method-override==1.0.3 django-rest-swagger==2.2.0 django-webpack-loader==0.6.0 djangorestframework==3.9.4 drf-extensions==0.5.0 idna==2.8 imagesize==1.1.0 itypes==1.1.0 Jinja2==2.10.1 lxml==4.4.1 Markdown==3.1.1 MarkupSafe==1.1.1 openapi-codec==1.3.2 packaging==19.0 psycopg2==2.8.2 Pygments==2.4.2 pyparsing==2.4.1.1 python-cas==1.4.0 pytz==2019.1 requests==2.22.0 setuptools==41.6.0 simplejson==3.16.0 six==1.12.0 snowballstemmer==1.9.0 sqlparse==0.3.0 uritemplate==3.0.0 urllib3==1.25.3 uuid==1.30 drf-yasg==1.17.0 waitress==1.4.2 httpretty==0.9.7 whitenoise==4.1.4 python-dotenv==0.10.3 django-cors-headers==3.1.1 django-nose==1.4.6 coverage==4.5.4 pycodestyle==2.5.0 I tried python -Wa manage.py test but i got an error from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' -
Data from DateTimeField() to TimeField() leaving only the time in the latter without the date?
Good morning! I have a django database model table. To fill this model table, data replenishment is used - a form in the template. One of the columns from this model table is a DateTimeField() data type. I also have a second table, the Django database model. The differences from the first table described above are minimal - just an additional added column - which has a TimeField() data type. I plan to copy from the first model - part of the data from the DateTimeField() column to the second table of the model - into the column - which has the data type TimeField(). I'm planning to copy some of the DateTimeField() data - just the time without the date. Data from DateTimeField() to TimeField() leaving only the time in the latter without the date. How can you come up with something for this? -
Wrong thumbnail url returned in Django/DRF
I am trying to create an application (Django and DRF), by which you can create and view posts. The posts contain an image, and the preview is supposed to only show a thumbnail of the original image, which will be created by the application using Pillow. I mainly followed this stackoverflow post, but changed it to fit my application. However, the image is saved in /media/images/, the thumbnail is saved in /media/resize/, the thumbnail-url is saved in the database as resize/image_thumb.jpg, but the thumbnail-url in the returned json-object in Postman is the image-url, not the thumbnail-url. Where am I going wrong? settings.py MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media/" urls.py from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = [ path('feed/', PostAPIView.as_view(), name='feed_of_posts'), path('feed/<int:id>', PostDetailAPIView.as_view(), name='update_delete_posts'), ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class PostAPIView(ListCreateAPIView): serializer_class = PostSerializer queryset = Post.objects.all() ... def perform_create(self, serializer): return serializer.save(poster = self.request.user) serializers.py class PostSerializer(serializers.ModelSerializer): thumbnail = serializers.ImageField(source='image', required=False) class Meta: model = Post fields = ('id', 'image', 'pub_date', 'imageDescription', 'poster', 'thumbnail') def to_representation(self, instance): self.fields['poster'] = PosterSerializer(read_only=True) return super(PostSerializer, self).to_representation(instance) models.py class Post(models.Model): image = models.ImageField(upload_to='images/') thumbnail = models.ImageField(upload_to='resize/', editable=False) imageDescription = models.TextField() ... pub_date = models.DateTimeField(auto_now_add=True) … -
Add Fields to Django form not present in model
I have a student model to keep data of students. Models.py class Student(models.Model): roll_no = models.IntegerField(editable=True, blank=False, primary_key=True) name = models.CharField(max_length=30) date_of_birth = models.DateField(default='1900-01-01', blank=True) admission_no = models.IntegerField(default=roll_no) admission_date = models.DateField(default=datetime.now) student_cnic = models.CharField(max_length=15) father_cnic = models.CharField(max_length=15) grade = models.ForeignKey('school.SchoolClasses', on_delete=models.CASCADE, null=True, blank=True) mobile = models.CharField(max_length=12) active = models.BooleanField(default=True) Student Form looks like Forms.py class StudentForm(forms.ModelForm): extra_fields = ['school'] class Meta: model = Student fields = ['roll_no', 'name', 'date_of_birth', 'admission_no', 'admission_date', 'student_cnic', 'father_cnic', 'mobile', 'grade'] def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout(Row(Column('roll_no', css_class='form-group col-md-6'), Column('admission_no', css_class='form-group col-md-6'), ), Row(Column('date_of_birth', css_class='form-group col-md-6'), Column('admission_date', css_class='form-group col-md-6'), ), Row(Column('name', css_class='form-group col-md-3'), Column('student_cnic', css_class='form-group col-md-3'), Column('father_cnic', css_class='form-group col-md-3'), Column('mobile', css_class='form-group col-md-3'), ), Row( Column('school', css_class='form-group col-md-3'), Column('grade', css_class='form-group col-md-3'), ), Submit('submit', 'Add Student', css_class='btn btn-primary'), ) self.fields['date_of_birth'].widget = forms.DateInput(attrs={'type': 'date'}) self.fields['admission_date'].widget = forms.DateInput(attrs={'type': 'date'}) ` The school field is just to Filter the result for grade field to return only those grades present in the selected school But i am getting an error KeyError: "Key 'school' not found in 'StudentForm'. Choices are: admission_date, admission_no, date_of_birth, father_cnic, grade, mobile, name, roll_no, student_cnic." -
While deploying django app in jenkins why docker not run application when building image
I am new to CICD trying to understand docker. While deploying Django app using jenkins pipeline which is calling dockerfile to build docker image. The dockerfile calls runner.sh which have below line of code : uwsgi --http "0.0.0.0:${PORT}" --module my_proj.wsgi --master --processes 4 --threads 2 Everything is working fine, but i curious to know why this code not run application while building docker image and running application when this image is being run on host server. I tried running application in dockerfile in that case while deploying jenkins pipeline get stuck as it run the application and keep as stuck as application will keep on running while building image. -
How to extend the template for a Django Admin model add/create form?
In Django, you can override the Django Admin change forms by providing a path to a new template: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # some other admin form config... # override change form template... change_form_template = "admin/some_custom_change_form.html" Then you can create a template within your application at app/templates/admin/some_custom_change_form.html that needs to extend the original template: {% extends "admin/change_form.html" %} <!-- Add your changes here --> <p>Hello World!</p> I am trying to override not only the change form, but the form for creation/addition too. Django also provides add_form_template for the ModelAdmin interface too: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # some other admin form config... # override add and change form template... change_form_template = "admin/some_custom_change_form.html" add_form_template = "admin/some_custom_add_form.html" Now I just need the original template to override. I can't for the life of me find in documentation where the templates you can override are located, so I made a best guess and tried admin/add_form.html {% extends "admin/add_form.html" %} <!-- Add your changes here --> <p>Hello World!</p> Which throws an Exception on render of the add page, as it cannot find the chosen template to extend it. I've also tried using {% extends "admin/change_form.html" %} but that doesn't work as a different template is being used in … -
How to perform 2 operations in MathFilters ( Django )
I wanted to perform 2 operations 1: subtract entry_price from Exit_price then multiply the outcome by size. I am getting the error: Could not parse some characters: |(journals.exit_price||sub:journals.entry_price)|mul:journals.size <p class="pnl"> {% if journals.trade_direction == 'Long - Buy' %} {{ (journals.exit_price|sub:journals.entry_price)|mul:journals.size }} {% else %} {{ (journals.entry_price|sub:journals.exit_price)|mul:journals.size }} {% endif %} </p> -
django admin template overriding not working
I want to override templates/admin/change_form.html in my own django module app1, so following the standard, i added file change_form.html with following content to app1->templates->admin {% extends "admin/change_form.html" %} {% load i18n static %} {% block object-tools %} <h3>My extended html</h3> => Not rendered until => change_form_template = 'admin/change_form1.html' {{ block.super }} <script defer="defer" src="{% static 'app1/image_preview.js' %}"></script> {% endblock %} admin.py (I can achieve it by changing every admin and add giving change_form_template = 'admin/change_form1.html' but that is not the way i need it) from django.contrib import admin from .models import Model1 class Model1Admin(admin.ModelAdmin): # change_form_template = 'admin/change_form1.html' #overriding does not affect, but this does pass admin.site.register(Model1, Model1Admin) Expected output: <h3>My extended html</h3> should be the part of every change_form.html because I have extended admin/chamge_form.html without doing anything else anywhere while app1 exists in project and installed app in settings.py Complete steps (I have Django installed in default python of my system) django-admin startproject pr1 cd pr1 django-admin startapp app1 edited settings.py to append a line => INSTALLED_APPS += ['app1'] Added chnage_form.html to app1/templates/admin Made migrations, created superuser, logged in and opened http://127.0.0.1:8000/admin/app2/model1/add/ Complete code https://github.com/humblesami/django-templates -
I can't import multiselectfield
I'm trying to use multiselectfield in Django although I installed it with pip install django-multiselectfield and put it in my INSTALLED_APPS but I can't import it in my forms.py file... what can i do? -
Python Django: model <name> not recognized in views.py
Background: I want to open the CourseForm in order to edit existing course data by clicking on a link. Problem description: Running the development server, if I click on the link, I get the following error: File "/home/usr/project/workbench/courses/views.py", line 92, in ManageCourseView course = Course.objects.filter(id=id) UnboundLocalError: local variable 'Course' referenced before assignment Line 92 in ManageCourseView: from django.views import generic from .models import Course from .forms import CourseForm from django.shortcuts import render, redirect from django.http import HttpResponseRedirect def ManageCourseView(request, id): course = Course.objects.get(id=id) if request.method == 'POST': form = CourseForm(request.POST, instance=course) if form.is_valid(): # I do something with it else: form = CourseForm(instance=course) return render(request, 'courses/manage_course.html', {'form': form}) Definition of the Course model: class Course(models.Model): name = models.CharField('Kurs', max_length=200) capacity = models.PositiveSmallIntegerField('Anzahl Plätze') start_date = models.DateField('Erster Kurstag') end_date = models.DateField('Letzer Kurstag') price = models.FloatField('Preis', null=True, blank=True) def __str__(self): return self.name I am referencing the Course model in other view functions and there it works perfectly fine. Definition of the CourseForm: class CourseForm(forms.ModelForm): class Meta: model = Course exclude = ['name', 'price'] Extract of the html with the respective link: <div class="column is-two-thirds"> <a href="{% url 'courses:manage_course' course.id %}"> <div class="box has-background-info is-clickable"> <p class="title has-text-white">{{ course.name }}</p> <p class="has-text-white">{{ course.start_date … -
Daphne ModuleNotFoundError: No module named
I'm unable to get the Daphne server running. It always fails with the following error: ModuleNotFoundError: No module named 'apps' /home/prassel/sml-266/simlai-api/apps/asgi.py django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]), } ) And I invoke Daphne as follows: daphne -b 0.0.0.0 -p 8000 apps.asgi:application -
How to move Virtualenvwrapper.sh to it's appropriate location?
I am working a new project where it requires me to create a virtual environment since im working with Django frameworks. I been having trouble working creating "mkvirtualenv" and its been kicking my butt for the past couple days. I think I found the underlying problem that Virtualwrapper.sh is not in the right location. I been trying to figure out how to move it into the right location does anybody have some guidance on what to do. /Users/name/opt/anaconda3/bin ----> currently where the file is at the moment I been trying to add it to the .bashrc folder but im having a hard time adding it there. How can I do this so I can successfully run "mkvirtualenv" **I been trying for hours to write .bashrc and research anything but nothing is helping so far -
admin panel in Django creating for to change Product media and text from webpage
I have created a website in Django that contains product details and captions. Now, I want to create a dynamic admin panel that performs the following tasks without using code (because the client has no idea about coding): Add or change product photos and details. change or add any paragraphs or details on the website. ( just like we are changing the our images on social media account without using any coding like using prebuilded system) So here is what to do as the next step in processing this: pls guide me i have tried models but i don't understand it very well -
127.0.0.1:8000 refused to connect after django manage.py runserver
I'm new to python and django. I did the python manage.py runserver in cmd for the first time and it showed starting development server at http://127.0.0.1:8000/. It said: System check identified no issues (o silenced)April 04,2023- 19:42:34 Django version 2.2.4,using settings 'MyProject.settings!Starting development server at http://127.0.0.1:8000/Quit http://127.0.0.1:8000/Quit the server withCTRL-BREAK But in chrome it said "this site cant be reached". It said: ERR SSL PROTOCOL ERROR my setting.py: ALLOWED_HOSTS = ['*',] Can someone help me out with this? -
New wagtail project: main page not working
The problem is the following. I have created a new wagtail project. Nothing special. No changes, just created. At startup I get this. What is this url? Nothing has changed in the project yet, the project is clean... The main page is not displayed, everything is redirected to /catalog. -
Problem with the construct of LoginView.as_view formul
I know that command django.contrib.auth.views import login has changed. That's why I used a new formula. I don't know why my webiste is not working althouh I think that I used a new formula correctly. Everything is fine: the paths to the files are used correctly although my website is not rendered. I will be grateful for any help :) Nornik/urls.py: from django.urls import re_path from django.urls import path from . import views from django.contrib.auth.views import LoginView urlpatterns = [ path(r'^$', views.home), path('login/', LoginView.as_view (template_name='Nornik/login.html'), name='login'), views.py: from django.shortcuts import render, HttpResponse def home(request): numbers = [1,2,3,4,5] name = 'John Lock' args = {'MyName': name, 'Numbers': numbers} return render(request, 'Nornik/home.html',args) tutorial/urls.py: from django.urls import re_path, include from django.urls import path from django.contrib import admin urlpatterns = [ path(r'^admin/', admin.site.urls), path(r'^Nornik/', include('Nornik.urls')), I will be grateful for any help :) -
How to stop url redirection to urls ending with '/' in Django?
On my website, few urls are not crawlable and are returning non 200 response code. It is happening because those are getting redirected. Example: https://mywebsite.com/fr -> https://mywebsite.com/fr/ When I crawl https://mywebsite.com/fr/, it returns me 200 but not for https://mywebsite.com/fr. Website is built using django. I am not sure how can I make https://mywebsite.com/fr to return 200 code. Please advise. -
migrating mysql db to django, unique constraints?
Currently I have part of a model: class Flight(models.Model): flight_number = models.PositiveIntegerField(primary_key=True) airline_name = models.ForeignKey(Airline, models.DO_NOTHING, db_column='airline_name') departure_datetime = models.DateTimeField() departure_airport = models.ForeignKey(Airport, models.DO_NOTHING, db_column='departure_airport', blank=True, null=True, related_name='departure_airport') arrival_airport = models.ForeignKey(Airport, models.DO_NOTHING, db_column='arrival_airport', blank=True, null=True, related_name='arrival_airport') arrival_datetime = models.DateTimeField(blank=True, null=True) airplane = models.ForeignKey(Airplane, models.DO_NOTHING, blank=True, null=True) base_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) flight_status = models.CharField(max_length=9) class Meta: managed = False db_table = 'flight' constraints = [ models.UniqueConstraint(fields=['flight_number', 'airline_name', 'departure_datetime'], name='unique_flight') ] class Ticket(models.Model): ticket_id = models.AutoField(primary_key=True) customer = models.ForeignKey(Customer, models.DO_NOTHING) flight_number = models.ForeignKey(Flight, models.DO_NOTHING, db_column='flight_number', to_field='flight_number', related_name='ticket_flight_number') airline_name = models.ForeignKey(Flight, models.DO_NOTHING, db_column='airline_name', to_field='airline_name', related_name='ticket_airline_name') departure_datetime = models.ForeignKey(Flight, models.DO_NOTHING, db_column='departure_datetime', to_field='departure_datetime', related_name='ticket_departure_datetime') first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.CharField(max_length=100) date_of_birth = models.DateField() class Meta: managed = False db_table = 'ticket' constraints = [ models.UniqueConstraint(fields=['flight_number', 'airline_name', 'departure_datetime', 'first_name', 'last_name', 'email', 'date_of_birth'], name='unique_ticket') ] But I keep getting the error log while trying to run migrate: ERRORS: atrsapp.Ticket.airline_name: (fields.E311) 'Flight.airline_name' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints. atrsapp.Ticket.departure_datetime: (fields.E311) 'Flight.departure_datetime' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or add a UniqueConstraint … -
Messages not rendering in djangos built in Login and Logout View
I am trying to show alerts on my home page when some one successfully logs in or logs out, and also show an error alert if something goes wrong with login. All my message alerts are working with all of my views apart from the login and logout views and I have no idea why. VIEWS: def user_login(request): data = cartData(request) cartItems = data['cartItems'] context = { 'cartItems': cartItems, } if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,"You were successfully logged in...") return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {'context': context}) def user_logout(request): logout(request) messages.info(request, ("You were successfully logged out...")) return redirect('home') HTML: {% if messages %} <div class="alert alert-success" id="msg" role="alert"> <h4 class="alert-heading">Success</h4> {% for message in messages %} <p>{{message}}</p> {% endfor %} </div> {% endif %} -
Authorization is not working for jwt token using axios
settings.py from datetime import timedelta 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/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-siq5r5k3*sg#858b4w8$i*6c-ubf*zkpjj1wb&chn4v$%t!ve+' # 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', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dlt.urls' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True } CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] 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 = 'dlt.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' … -
Pytest and pytest-django ends up with assert error
I've been dealing with this for the last 30 mins and I just want to move on from it. Basically, the test returns Assertion Error: E AssertionError: assert {} == {'rant': 'Kulugo', 'slug': 'apostrophe'} E Right contains 2 more items: E {'rant': 'Kulugo', 'slug': 'apostrophe'} E Full diff: E - {'rant': 'Kulugo', 'slug': 'apostrophe'} E + {} tests/rants/test_serializers.py:26: AssertionError Now tracing back the error in line 26: assert serializer.data == invalid_serializer_data I expect everything to pass since this written code is based on a tutorial from testdriven.io Here's the full code: from main.serializers import RantSerializer, CategorySerializer def test_valid_rant_serializer(): valid_serializer_data = { 'id': 1, 'title': "First Rant", 'slug': "first-rant", } serializer = RantSerializer(data=valid_serializer_data) assert serializer.is_valid() assert serializer.validated_data == valid_serializer_data assert serializer.data == valid_serializer_data assert serializer.errors == {} def test_invalid_rant_serializer(): invalid_serializer_data = { 'rant': 'Kulugo', 'slug': 'apostrophe' } serializer = RantSerializer(data=invalid_serializer_data) assert not serializer.is_valid() assert serializer.validated_data == {} assert serializer.data == invalid_serializer_data assert serializer.errors == {"id": ["This field is required"]} -
How to properly upload a CSV file to Django model
I am trying to upload a CSV file to a Django model. Here is the code i have been trying for it to work: def post(self, request): if(request.method=='POST'): # csv_file=request.FILES.get('file') csv_file = request.FILES['file'] with open(csv_file, 'r') as csvfile: # reader=csv_file.read().decode("utf-8") # reader=TimeSeries.import_data(data = open(csv_file)) # reader = csv.reader(csv_file.read().decode('utf-8').splitlines()) reader = csv.reader(csvfile) print("here3") print (reader); for row in reader: print("here4") print(row) queryset = Station.objects.all() print("here5") # serializer_class = TimeSeriesSerializer queryset = queryset.filter(name=row['Station Name']) TimeSeriesInstance=TimeSeries(station=queryset.number,date=row['Date'],hour=row['Time'],value=row['Value']) TimeSeriesInstance.save() # process_file.delay(csv_file) return HttpResponse('Success') The problem is that i have tried to remove and add the above commented lines for somehow check if the code works.But it is throwing different types of errors for different lines. currently it is throwing the error: expected str, bytes or os.PathLike object, not InMemoryUploadedFile Kindly tell what might be the issue? Thanks. -
Extending Django's nav-sidebar with additional options
I am working with Django and currently trying to add options to default nav-sidebar which will not be anyhow connected with models, but will open other additional pages. The best idea i got is to extend the default base_site.html with my new option for a sidebar. Therefore i resulted in the following code: {% extends "admin/base_site.html" %} {% block sidebar %} <div class="app-dashboard module current-app"> <h2>Custom Options</h2> <ul> {% include "admin/custom_sidebar.html" %} </ul> </div> {{ block.super }} {% endblock %} custom_sidebar.html: <th class="model-group"><a href="{% url 'email' %}">Send message</a></th> This indeed extends the page, but adds my option to the bottom of the content block, whereas I want it to appear in my sidebar. Here is how it looks: I understand I practically didnot affected the default nav_sidebar anyhow, but I am out of ideas how to make it. Is there a way i can modify a nav_sidebar in django? And if so how shall i do it? -
Django - How to show Full name of the Month in Admin Panel
I want to show Full month (like April or September) in Django Admin Panel. But it keeps show me first 3 letter of the month or a number. Is there any way to do make it show full month on Admin Panel? Thanks! -
Celery task stays running forever, but completes successfully
My Task: @app.task(ignore_result=True) def leaks_scan(target: str, remove_type: str = "old", **kwargs): url = settings.API_URL + "leaks" skip = 0 limit = 1000 max_limit = 5000 if remove_type == "all": remove_all_data(Leak, target) scan_id = None target_id = None while True: data = get_data(url, target, skip=skip, limit=limit) count = data.get("count") data = data.get("data", []) if not data: if not count: remove_all_data(Leak, target) break break scan_id, target_id = load_leak_data(data) skip += limit if skip > max_limit: break if remove_type == "old" and scan_id and target_id: remove_old_data(Leak, scan_id, target_id) print("Leak scan completed") Notice that this task has a print statement that prints Leak scan completed in the last line Logs: Task received: Task finished (debug print line): The task works as expected and completes successfully. However, when I check the Celery worker logs, the task stays in the running state indefinitely, even though it has been completed: Can anyone suggest a solution or provide any guidance on how to troubleshoot this issue? Thanks in advance for your help. Environment & Settings Celery version: celery report Output: software -> celery:5.2.7 (dawn-chorus) kombu:5.2.4 py:3.11.2 billiard:3.6.4.0 py-amqp:5.1.1 platform -> system:Linux arch:64bit, ELF kernel version:5.15.90.1-microsoft-standard-WSL2 imp:CPython loader -> celery.loaders.default.Loader settings -> transport:amqp results:disabled deprecated_settings: None Broker & Result …