Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hosting static site and Django apps on Ubuntu with Nginx
I am hitting a wall on what to do here. I have tried so many variations of solutions on line and none seem to work. This is what I want to do: I have a domain example.com and a VPS running Ubuntu wth a nginx server. I have a static site that I would like accessible when going to example.com. I have a django project and applications that I would like accessible when going to example.com/apps/. I would like example.com/apps/ to be the root for all files that belong in the project. So far, my basic set up is: I can access my static site via example.com. The files are sitting in /var/www/example.com/html. I cannot access my django app correctly. When I try going to www.example.com/apps/, I can see the Django test page when you first install the software and have it running (with the rocket ship). However, when I go to example.com/apps/admin, the browser URL changes to example.com/admin and I get a 404. I have tried many things here that end up not working. I get some kind of error with the server or with Django. Nginx Using proxy_set_header SCRIPT_NAME /apps (this doesn't seem to do anything). Rewriting the … -
Problem with non-Latin letters in website links
I am programming a website using django. I have placed my website in namecheep hosting and in pythonanywhere (for testing only). I faced a problem when adding Arabic links in the project, in namecheep hosting, where when I choose the link that contains an Arabic word, it directs me directly to the page page not found. In pythonanywhere and in localhost, which accepts Arabic links normally Now I want to know whether namecheep does not accept Arabic links? Are there any settings in cpanel to solve the problem? Is there a solution to the problem? I have verified that the problem is not in the code, but rather a settings problem in the hosting -
'NoneType' object has no attribute 'user' in django
def getuser(request): if request is None: return CustomUser.objects.none() return CustomUser.objects.filter(username=request.user) class sales_summary_filter(django_filters.FilterSet): username = django_filters.filters.ModelChoiceFilter(queryset=getuser) class Meta: model = sales_invoice fields= ('username', 'voucher_no','client') 'NoneType' object has no attribute 'user' -
Django ManyToManyField Validators
What's the best solution to apply following requirement? In my model I have 2 manytomany fields (team1 and team2) which contains both a list of players. If a player is in team1 he cannot be also in team2. How can I implement this logic? First idea is to use validators, but they are not supported by manytomanyfield as in the django doc, so i'm humbling ask your support for a better solution please. As of now not a single view expose a POST to create matches and only admin via django admin should be able to create matches. here the Model class Match(models.Model): date=models.DateField(auto_now_add=False,auto_now=False) team1=models.ManyToManyField(Player,related_name='team_1') team2=models.ManyToManyField(Player,related_name='team_2') score_team1=models.IntegerField( validators=[MinValueValidator(0)] ) score_team2=models.IntegerField( validators=[MinValueValidator(0)] ) -
Efficient Django query for model with foreign key to itself
I'm building a simple blog post website using Django. Basically there are two models: Post and Comment, where the comment model looks like this: class Comment: post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') # A comment can have many replies, and an user can only reply to the "parent" comment (A comment which isn't a reply to any comment) reply = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) likes = models.ManyToManyField(User, 'like_comments', blank=True) # Some other fields def save(self, *args, **kwargs): if self.reply is not None: self.post = self.reply.post super(Comment, self).save(*args, **kwargs) I have a class-based view which inherits Django generic DetailView to retrieve a specific post. The problem is I also want to retrieve all comments of the post, along with the replies of those comments and number of likes in an efficient way. What would be the most performant way to do so? I came up with the following way: from django.db.models import Prefetch from django.views.generic.detail import DetailView # Some views here ... class PostDetailView(DetailView): model = Post template_name = 'core/post_detail.html' context_object_name = 'post' def get_queryset(self, **kwargs): return Post.objects.prefetch_related(Prefetch('comments', queryset=Comment.objects.annotate(num_likes=Count('likes')))) However, when I inspect the query using QuerySet.query, the raw SQL looks the same as if I used "Post.objects.all()". I'm not sure if … -
why css is not working on the options of selector in html?
this is my html code <div class="blackbar" id="blackbar"> <div class="title"> <span id="titleText">Screen</span> <input class="search" type="text" id="search" placeholder="Search Movie" > <select class="dropdown" id="fruit"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> <option value="grape">Grape</option> </select> </div> </div> this is my css code for this #fruit { margin-left: 150px; width: 225px; height: 42px; border-radius: 12px; font-size: 24px; border: none; font-weight: lighter; box-shadow: inset 1px 1px 5px rgba(0,0,0, 0.8); padding-left: 50px; /* Add padding for indentation */ overflow-y: auto; /* Enable vertical scrolling */ max-height: 150px; /* Set maximum height for the dropdown */ } /* Style the options */ #fruit option { font-size: 24px; color: #333; background-color: #fff; padding: 10px; border-radius: 12px; } /* Style the hover state */ #fruit option:hover { background-color: #cef106; color: #000; } help me please ! see why my css is not working the options, i want my the hover to be yellow but it still blue and border rounding is also not working its working for the select but not for its options help me please -
Django "KeyError at "
i'm learning python / django and doing this weather app with api with youtube tutorial. But when i enter city name i got an error. I even copied hole tutorial code from github, but i still got same error and this just drives me crazy. And i allways get error on those 2 lines: weather_data1, daily_forecasts1 = fetch_weather_and_forecast(city1, api_key, current_weather_url, forecast_url) and for daily_data in forecast_response['daily'][:5]: enter image description here from django.shortcuts import render import requests import datetime def index(request): api_key = 'my api' current_weather_url = 'https://api.openweathermap.org/data/2.5/weather?q={}&appid={}' forecast_url = 'https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&exclude=current,minutely,hourly,alerts&appid={}' if request.method == 'POST': city1 = request.POST['city1'] city2 = request.POST.get('city2', None) weather_data1, daily_forecasts1 = fetch_weather_and_forecast(city1, api_key, current_weather_url, forecast_url) if city2: weather_data2, daily_forecasts2 = fetch_weather_and_forecast(city2, api_key, current_weather_url, forecast_url) else: weather_data2, daily_forecasts2 = None, None context = { 'weather_data1': weather_data1, 'daily_forecasts1': daily_forecasts1, 'weather_data2': weather_data2, 'daily_forecasts2': daily_forecasts2, } return render(request, 'weatherApp/index.html', context) else: return render(request, 'weatherApp/index.html') def fetch_weather_and_forecast(city, api_key, current_weather_url, forecast_url): response = requests.get(current_weather_url.format(city, api_key)).json() lat, lon = response['coord']['lat'], response['coord']['lon'] forecast_response = requests.get(forecast_url.format(lat, lon, api_key)).json() weather_data = { 'city': city, 'temperature': round(response['main']['temp'] - 273.15, 2), 'description': response['weather'][0]['description'], 'icon': response['weather'][0]['icon'], } daily_forecasts = [] for daily_data in forecast_response['daily'][:5]: daily_forecasts.append({ 'day': datetime.datetime.fromtimestamp(daily_data['dt']).strftime('%A'), 'min_temp': round(daily_data['temp']['min'] - 273.15, 2), 'max_temp': round(daily_data['temp']['max'] - 273.15, 2), 'description': daily_data['weather'][0]['description'], 'icon': … -
Is it safe to manually delete django_sessions data rows in ProsgreSQL table?
First, let me state that I know about the Django Python session cleanup scripts, but I currently don't have easy access to the shell where the Django framework is hosted. However, I have access to the backend PostgreSQL database. I'm trying to reduce the size of the over-data tables, and I noticed that the django_session table now has over 2.8 million rows. I don't think there's ever been a cron job setup for cleanup sessions since this website started running in 2016. From what I read, the django_session table stores user sessions when they log in, and if they don't log out, it stores them. Therefore, could I remove any rows older than a specified date? DELETE FROM public.django_session WHERE expire_date < '2023-01-01' I plan to test this out on a test server, but I would like to know whether it's the right approach. Otherwise, I'll have to figure out how to get access to run the shell script to do the cleanup. -
why the get method not able to use django restframework's request?
I have below code snippet class ListAccTokenView(ListAPIView): serializer_class = TokenSerializers def get_queryset(self): org_id = self.kwargs.get('id') entity_id = self.kwargs.get('comp') queryset = ErpLinkToken.objects.filter(id=id, comp=comp) return queryset class MeCompInfo(APIView): @staticmethod def get_company_info(request): get_token = ListAccTokenView.as_view() queryset = get_token(Request(Request(request=request)).data token = queryset[0]['token'] if queryset else None account_token_client = create_merge_client(token) I am getting below error AssertionError at /api/comp The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request`. I tried importing from django.http import HttpRequest and converting it to rest_framework instance as seen below, but not helping class MeCompInfo(APIView): @staticmethod def get_comp_info(request): django_request = HttpRequest() django_request.method = request.method django_request.GET = request.query_params get_token = ListAccTokenView.as_view() queryset = get_token(Request(request=django_request)).data ac_token = queryset[0]['token'] if queryset else None account_token_client = create_merge_client(ac_tok) def get(self, request, *args, **kwargs): api_log(msg="Processing GET request...") organization_data = self.get_comp_info(request) how can I fix this? -
how to connect django models?
I have two models, applications and additional information. class Submissions(models.Model): def create_new_ref_number(): return str(random.randint(1000000000, 9999999999)) submissions_number_id = models.CharField(max_length=10,blank=True, unique=True, default=create_new_ref_number,editable=False) client = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, related_name='submissions') contents = models.TextField() status = models.CharField( max_length=30, choices=STATUS, default='1') submissions_supervisor = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='submissions_supervisor') contractors = models.ManyToManyField(User, related_name='contractors') submissions_cause=models.CharField(max_length=30, choices=CAUSE, default='3') execution_date = models.DateField(null=True, blank=True) details_planned_service=models.TextField(null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) class AdditionalInfo(models.Model): submission = models.ForeignKey(Submissions, on_delete=models.CASCADE, related_name='additional_info', default='') contents = models.TextField() submissions_supervisor = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='additional_info_supervisor') created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) The website displays all submissions according to the date they were scheduled, and it is also possible to click the mini preview which opens the MODAL WINDOW, and here is the problem because the data from the submission model is all displayed, but I don't know how to add additional information to it. -
Deleting 'disabled' when saving changes in formset
I'm creating a table with a formset from a queryset of existing objects. Few fields in the table should change, and other fields should be displayed, but not changed. For displaying non-editable fields, I use the widget with 'disabled' in the form. GET request does everything right. But the POST request does not save changes to the resolved fields, because unresolved fields are required and have disabled and blocks the sending of existing values. I tried to use jQuery from the example, but it doesn't work. Moreover, I do not understand how I can refer to different ids in the formset. Models: class Order(models.Model): car = models.ForeignKey( Car, blank=True, null=True, on_delete=models.PROTECT, related_name='car_orders', ) department = models.ForeignKey( Department, blank=False, null=False, on_delete=models.PROTECT, related_name='dep_orders', ) ... View def orders_list(request, year, month, day): orders = Order.objects.filter( order_date__year=year, order_date__month=month, order_date__day=day ) if request.method == 'POST': formset = OrderCloseFormSet( request.POST or None, queryset=orders, prefix='order' ) if formset.is_valid(): formset.save(commit=False) for form in formset: form.save() formset = OrderCloseFormSet(queryset=orders, prefix='order') context = {'orders': orders, 'formset': formset} return render(request, 'orders/orders_list.html', context) Form class OrderCloseForm(forms.ModelForm): class Meta: model = Order fields = ( 'type_car', 'department', ... ) widgets = { 'car': forms.Select(attrs={'style': 'width: 100%'}), 'department': forms.Select(attrs={'disabled': 'True', 'style': 'width: 100%'}), ... … -
Solution for Django model composite foreign keys
I’m working with two models in Django: Order and OrderItems. I want to establish a one-to-one relationship between them using two columns instead of the usual single column. I’m aware of solutions like SQL Alchemy’s ForeignKeyConstraint and the django-composite-foreignkey package, but I’d prefer not to use ForeignKeyConstraint and the latter isn’t compatible with Django 4.0. Is there an alternative solution available for creating a composite foreign key that references two columns in Django 4.0? class Orders(models.Model): objects = models.Manager() id = models.AutoField(primary_key=True) order_id = models.CharField(max_length=255) --------> here it should reference with two columns ( id and department_id ) orderItem = models.ForeignKey('OrderCustomers', on_delete=models.PROTECT, db_column='order_item_id', to_field='id') order_item_id = models..CharField(max_length=255) department_id = models.CharField(max_length=255) created_at = DateTimeWithoutTZField(auto_now_add=True) updated_at = DateTimeWithoutTZField(auto_now=True) def __str__(self): return self.order_id -
problem occured during running a django program
from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\LENOVO\OneDrive\Desktop\internet and intranet\django-ecommerce\venv\lib\site-packages\django\utils\encoding.py) i am trying to run django program -
Error in setting SIGNING_KEY in djangorestframework-simplejwt
It's a bit odd! I have separated the base settings from the local settings. For instance, I moved SECRET_KEY into an other file called local.py as my local settings: SECRET_KEY = env( "DJANGO_SECRET_KEY", default="MY_DEFAULT_SEC_KEY" ) and the following is my simple-jwt settings in base.py which does not contain any variable called SECRET_KEY(since I moved it into local.py): REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], } SIMPLE_JWT = { "AUTH_HEADER_TYPES": ("Bearer", ), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "SIGNING_KEY": env("SIGNING_KEY"), "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", } I want to set a different SIGNING_KEY but I get the following error: File "/usr/local/lib/python3.11/site-packages/rest_framework_simplejwt/settings.py", line 19, in celery_worker-1 | "SIGNING_KEY": settings.SECRET_KEY, celery_worker-1 | ^^^^^^^^^^^^^^^^^^^ celery_worker-1 | File "/usr/local/lib/python3.11/site-packages/django/conf/init.py", line 111, in getattr celery_worker-1 | raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") celery_worker-1 | django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I don't need to set SECRET_KEY according to the documentation when I set a different SIGNING_KEY. However, it says I need to give it a value. What is the problem? -
Django Ajax Request - JSONDecodeError: Expecting value
I am working on a Django project where I have a course enrollment system. I have a button on my HTML page that, when clicked, triggers an Ajax request to submit enrollment data. The button redirects me to a page with a form where a student can fill in data such as name, surname, phone number, email, and language level. However, I am facing an issue where the values from the HTML attributes (data-language-id, data-course-name, data-price) are not getting passed into the Django view. The Django view returns a JSONDecodeError: Expecting value when trying to parse the request body. I intend to save this data into two tables in my database: Student and Enrolment. Any insights or suggestions on how to resolve this issue and successfully save the data into these tables would be greatly appreciated. Thank you! HTML Code: <!-- This is the button triggering the Ajax request --> <div class="block1_1"> <!-- ... other HTML content ... --> <div class="block__button" onclick="submitData(this)" data-language-id="1" data-course-name="Стандарт" data-price="6000"> <a href="{% url 'index3' %}">Записатися</a> </div> </div> JavaScript Code: function submitData(clickedBlock) { var languageId = clickedBlock.getAttribute('data-language-id'); var courseName = clickedBlock.getAttribute('data-course-name'); var price = clickedBlock.getAttribute('data-price'); $.ajax({ url: "/index3/", type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", data: … -
Django TypeError: save() got an unexpected keyword argument 'force_insert'
I get an error when creating a new user via a form on the site, or via python manage.py createsuperuser: TypeError: save() got an unexpected keyword argument 'force_insert' signals.py: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) I tried passing args, **kwargs to get def save(self, *args, **kwargs) and super(Profile, self).save(*args, **kwargs). I also tried passing these arguments to signals.py. The error remains, I don't know what to do. If you need more code from any script, I will provide it all Read other threads on this topic, but the solution didn't work for me 😥 -
Incorrect output of parents for a search result in a tree structure
I’m trying to enter parents for the search result so that the user understands in which node the value is located. The output is not correct. How to remove the extra ones???? models.py class Composition(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', db_index=True, verbose_name='Родительская категория') mapping = models.BooleanField(default=False, verbose_name='Отображение в дереве состава') id_drawing = models.ImageField(upload_to='media/image/', blank=True, null=True, default='null', verbose_name='Рисунок') position = models.PositiveIntegerField(verbose_name='Номер позции в родительской категории') designstion = models.CharField(max_length=255, primary_key=True, verbose_name='Обозначение') name = models.CharField(max_length=255, default='null', verbose_name='Наименование') description = models.TextField(blank=True, null=True, default='null', verbose_name='Описание') quantities = models.PositiveIntegerField(blank=True, null=True, default='null', verbose_name='Количество в родительской категории') slug = models.SlugField(verbose_name="Альт. заголовок") objects = TreeManager() @property def drawing_url(self): if self.id_drawing and hasattr(self.id_drawing, 'url'): return self.id_drawing.url class MPTTMeta: order_insertion_by = ['designstion'] class Meta: # unique_together = [['parent', 'slug']] verbose_name = 'Спецификация' verbose_name_plural = 'Спецификация' def get_absolute_url(self): return reverse('manual:catalog_page', args=[str(self.pk), str(self.slug)]) def __str__(self): return "%s (%s)" % (self.name, self.designstion) view.py def get_ancestors(unit): unit.designstion = unit.get_ancestors() return unit def catalog(request): catalog_list = models.Composition.objects.filter(mapping=True) if request.GET.get('q') != None: question = request.GET.get('q') ** seach_catalog =map(get_ancestors, Composition.objects.filter(Q(name__icontains=question)|Q(designstion__icontains=question)))** return render(request, 'catalog.html', { 'catalog_list': catalog_list, 'seach_catalog': seach_catalog, }) else: return render(request, 'catalog.html', { 'catalog_list': catalog_list, }) html {% for unite in seach_catalog %} {{ unite.name}} <div> {{ unite.designstion }}</div> </li> {% endfor %} Output results: … -
__str__ method in model generates large amount of duplicated queries in django admin panel
I have a model Offer which has a ForeginKey to another model Category. And through this Category model I get a Brand associated with this Category and pass it to the Offer on admin page. But it generates a large amount of queries when I use this Brand field in dropdown filter on Offer admin page. models.py class Brand(BaseFields): name = models.CharField() ... def __str__(self): return self.name() class Category(BaseFields): name = models.CharField() brand = models.ForeignKey( Brand, on_delete=models.SET_NULL, null=True, blank=True, ) parents = models.ManyToManyField( 'self', blank=True, verbose_name='Parent_category', related_name='children', symmetrical=False ) def __str__(self): return str(self.brand) + '----' + self.name class Offer(BaseFields): name = models.CharField() category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='offer', verbose_name='Related_category' ) def __str__(self): return self.name admin.py class OfferAdmin(admin.ModelAdmin): list_select_related = True list_display = ( 'name', 'brand_name', 'category', 'place', 'status' ) list_editable = ('place', 'status') list_filter = ( ('category__brand', RelatedOnlyDropdownFilter), ('category', RelatedOnlyDropdownFilter), 'status' ) fields = [ 'name', 'description', 'tech_info', 'ctru', 'category', 'place', 'status' ] autocomplete_fields = ['category'] actions_on_bottom = True list_per_page = 25 search_fields = ['name'] def get_queryset(self, request): return super().get_queryset(request).select_related('category', 'category__brand') @admin.display(description='Brand', ordering='name') def brand_name(self, obj): return obj.category.brand.name These two blocks are the main problem, as I understand def __str__(self): return str(self.brand) + '----' + self.name list_filter = … -
Including some records in an SQL query increases query time fivefold on Heroku
We use Django with django-guardian for object-based permissions. Recently, we have been experiencing an extreme increase in runtime of a specific query for at least one user with a lot of annotation_texthighlight . Here is the query: SELECT "annotation_texthighlight"."uuid", [omitted for readability] FROM "annotation_texthighlight" INNER JOIN "annotation_annotation" ON ("annotation_texthighlight"."annotation_id" = "annotation_annotation"."uuid") WHERE ( "annotation_texthighlight"."annotation_id" IN (SELECT U0."uuid" FROM "annotation_annotation" U0 WHERE (U0."chapter_id" = '9a481c82-c44b-4ead-94bb-48de0910877b'::uuid AND U0."min_revision_id" IN ('5a301886-e200-441f-ad8e-03c4eb9bd773'::uuid, '6f539d6f-c9eb-41e2-956e-32b4a5950c33'::uuid))) AND "annotation_texthighlight"."uuid" IN (SELECT CAST(U0."object_pk" AS uuid) AS "obj_pk" FROM "guardian_userobjectpermission" U0 INNER JOIN "auth_permission" U2 ON (U0."permission_id" = U2."id") WHERE (U0."user_id" = 1522 AND U2."content_type_id" = 89 AND U2."codename" IN ('view_texthighlight'))) ); This puzzles me quite a bit. Here are the results of my investigation so far: Copying the database from its original Heroku (Postgres 13.4, standard-2, 4GB RAM, 1.2 GB DB size) to local (stock Postgres 13 via standard Docker image) will cut the runtime ~250ms. In total, about 1200 records will be returned. The first 700 (LIMIT 700) will take ~5 seconds. The remaining (OFFSET 700 LIMIT 700) will take ~25 seconds. Removing either of the WHERE filters will reduce runtime <1s. My best guess would be a different configuration on Heroku as compared to the default Postgres … -
Django MySQL OperationalError (1045) - Access Denied for User
I'm encountering an OperationalError (1045) in Django when trying to run migrations with MySQL. The error message is "Access denied for user 'database_userkeem'@'localhost' (using password: YES)". Steps Taken: Checked MySQL user and password using the command line, successfully connected. "mysql -u database_userkeem -p" Verified the correctness of the MySQL user and password in Django's settings.py. " settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_btx', 'USER': 'database_userkeem', 'PASSWORD': '?Bi:88R==usQCB4', 'HOST': 'localhost', 'PORT': '3306', }, } Tried running migrations using Django's management command: "python manage.py migrate" resulting in the OperationalError Considered removing a separate user configuration and making 'keem' the default user. Updated DATABASES in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_btx', 'USER': 'keem', 'PASSWORD': '?Bi:88R==usQCB4', 'HOST': 'localhost', 'PORT': '3306', }, A. Any insights into why there might be a discrepancy between successful MySQL command line access and the Django OperationalError? B. Suggestions for resolving the access denied issue when running Django migrations? C. Are there additional steps or configurations I should consider? -
Celery does not see objects in the database
I know that similar questions have already been asked here, but none of the answers I found turned out to be suitable. I hope I get lucky now. So, I have a Django application using Postgres, RabbitMQ and Celery. When I run the components individually, everything works fine. The problem occurs when running through docker-compose. For some reason, celery tasks cannot find the object in the database. The object exists, moreover, it stores the celery task id (for example, for possible subsequent cancellation of the task). Here are the parts of the code relevant to the problem: # docker-compose.yml version: "3.7" services: db: image: postgres:12.4 container_name: "fbrq_db" volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env environment: - POSTGRES_HOST_AUTH_METHOD=trust networks: - default rabbitmq: restart: always container_name: "fbrq_rabbit" image: rabbitmq:3-management-alpine ports: - 5672:5672 - 15672:15672 networks: - default app: restart: always container_name: "fbrq_app" build: . volumes: - .:/code - ./static:/code/static command: gunicorn --bind 0.0.0.0:8000 fbrq_api.wsgi ports: - "8000:8000" networks: - default celery: restart: always container_name: "fbrq_celery" build: . command: celery -A fbrq_api worker -l info env_file: - ./.env depends_on: - app - rabbitmq environment: - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672/ - DJANGO_SETTINGS_MODULE=fbrq_api.settings networks: - default celery-beat: restart: always container_name: "fbrq_celery-beat" build: . command: celery -A fbrq_api beat -l … -
Celery Task does not retry after a certain number of times
I have a celery task with RabbitMQ as the broker. The task calls an API and checks the response, if the response does not meet some conditions, the task retries itself with a 5 seconds countdown. The problem is that my task gets retried for exactly 279 times and after that it gets stuck in "retried" status and does not execute. Here is what my task basically does: @shared_task(name="get-progress", bind=True, max_retries=10 ** 65, acks_late=True, reject_on_worker_lost=True) def get_progress(self, object_id: str): # get progress from third party api and store in status variable if status == "available": # update object in db return else: self.retry(countdown=5) I created another task to test my configuration as follow @shared_task(name="dummy", bind=True, max_retries=10 ** 65, acks_late=True, reject_on_worker_lost=True) def dummy(self): logger.info(f"retry {self.request.retries} of {self.max_retries} with {self.request.id}") self.retry(countdown=1) The dummy task works just fine and gets retried for a ridiculously large number of times. There are no exceptions being raised, I checked if the API times out and that wasn't the case. The number 279 is really confusing me and I guess I'm missing something here. Any help would be appreciated. -
full toolbar in django-ckeditor-5
i cant use full toolbar in django-ckeditor-5 in ckeditor-4 use: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', }, } But in version 5, this method does not work please help me please help me please help me please help me please help me thank you -
CKEditor in django displays as a textarea when i save it from form
I have a form with CKEditor and i need to save it to database. When i save it, it somehow save it with textarea like this: <div> <label for="id_body">Body:</label> <div class="django-ckeditor-widget" data-field-id="id_body" style="display: inline-block;"> <textarea name="body" cols="40" rows="10" required id="id_body" data-processed="0" data-config="{&quot;skin&quot;: &quot;moono-lisa&quot;, &quot;toolbar_Basic&quot;: [[&quot;Source&quot;, &quot;-&quot;, &quot;Bold&quot;, &quot;Italic&quot;]], &quot;toolbar_Full&quot;: [[&quot;Styles&quot;, &quot;Format&quot;, &quot;Bold&quot;, &quot;Italic&quot;, &quot;Underline&quot;, &quot;Strike&quot;, &quot;SpellChecker&quot;, &quot;Undo&quot;, &quot;Redo&quot;], [&quot;Link&quot;, &quot;Unlink&quot;, &quot;Anchor&quot;], [&quot;Image&quot;, &quot;Flash&quot;, &quot;Table&quot;, &quot;HorizontalRule&quot;], [&quot;TextColor&quot;, &quot;BGColor&quot;], [&quot;Smiley&quot;, &quot;SpecialChar&quot;], [&quot;Source&quot;]], &quot;toolbar&quot;: &quot;Full&quot;, &quot;height&quot;: 291, &quot;width&quot;: &quot;100%&quot;, &quot;filebrowserWindowWidth&quot;: 940, &quot;filebrowserWindowHeight&quot;: 725, &quot;language&quot;: &quot;en-us&quot;, &quot;versionCheck&quot;: false}" data-external-plugin-resources="[]" data-id="id_body" data-type="ckeditortype">&lt;p&gt;fhdgh&lt;/p&gt; </textarea> </div> </div> But when i just click save from admin panel it all works perfectly form.html: <div class="form-group"> {{form.as_p}} {{form.media}} </div> forms.py class PostForm(forms.Form): body = forms.CharField(widget = CKEditorWidget()) class Meta: model = Document fields = 'body' models.py from django.db import models from ckeditor.fields import RichTextField from simple_history.models import HistoricalRecords class Document(models.Model): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' header = models.CharField(max_length = 32) body = RichTextField() category = models.ForeignKey(Category, on_delete = models.CASCADE) timestamp = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE) history = HistoricalRecords() def __str__(self): return self.header views.py def add_document_view(request): categories = Category.objects.all() languages = get_language_choices() context = {"allCategories":categories, "form":PostForm, … -
TemplateSyntaxError at \stats2
this is my django code def stats2_view(request): monthly_expenses={} months_ = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] # if request.method == 'POST': # year = request.POST.get('selected_year') # if year: expenses = Expense.objects.filter(owner=request.user, date__year=2024) monthly_expenses = calculate_expense_month_summary(expenses) years = range(2010, datetime.datetime.now().year+1) return render(request, 'expense/stats2.html', {'expense_month_data': monthly_expenses,'yr': years,'months':months_}) and, this template <div class="col-md-6"> <h2>Details</h2> <div class="text-md-start center-paragraph"> <h3>For the year 2024 the break down for each month is as follows</h3> {% for month_num, expense in expense_month_data.items %} <p>Total amount spent in {{ months[month_num]}} till now is <span class="fw-bold">{{ expense }}</span></p> {% endfor %} </div> </div> error Im receiving TemplateSyntaxError at /stats2 i want to print month from the index