Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with implementation of django-microsoft-auth in Django app with custom user model
I want to implement django-microsoft-auth library to my Django project and I am struggling with migrating data. The problem is that I am using Custom User model that does not contain a username field and when I am trying to run the foolowing command: python manage.py migrate I get error like this: SystemCheckError: System check identified some issues: ERRORS: <class 'microsoft_auth.admin.UserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'user.User'. I've cloned the repository and I don't see anywhere in admin.py or in any other file that ordering is refering to a username field. My user model looks like this: class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" … -
Error trying to migrate my database. Typing error
Sorry but I don't know what is happening when I try to run (python3 manage.py makemigrations) I really don't know what's going on I'm looking for an answer for a while but I can't figure out where the error is (paginas) root@janstar:/home/paginas/proyectodedjango# python3 manage.py makemigrations Traceback (most recent call last): File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 236, in _cursor self.ensure_connection() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 199, in get_new_connection conn = Database.connect(**conn_params) TypeError: argument 1 must be str, not PosixPath During handling of the … -
Django not connecting to postgres db. port 5432 failed: FATAL: database "postgres" does not exist
I have a database called postgres. However when trying to connect it gives the following error output: port 5432 failed: FATAL: database "postgres" does not exist. If i change to template1 it works but i want to use postgres. Please see image of list of db's Django settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Please note i am using Docker. docker-compose.yml services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres -
How to set the title of a new tab when returning a fileresponse
I have an button that when pressed opens up a new tab and displays a PDF. When the new tab is opened the title looks like some sort of metadata about the PDF. ex: "Microsoft Powerpoint:The original.ppt" instead of the name of the PDF "Generated.pdf". How do I set the title of the tab to be the name of the actual PDF being displayed? <input type="button" onclick="window.open('{% url 'get_file' %}','_blank');" value="Show File"/></td> views.py: def GetFile(request) filepath = os.path.join('my_path/' + variable + '/' + filename) response = FileResponse(open(filepath, 'rb'), content_type='application/pdf') response['Content-Disposition'] = 'filename="{}"'.format(filename) return response -
How to use arrays in loop with if statment in django template
I want to choose include button_free when hour_1 is 0 or choose button_busy when hour_0 is 1 view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[hour_1] = [0,0,1,1,0] context['range_5'] = [0, 1, 2, 3, 4] return context ` part of template {% for schedule_part in range_5 %} {% if hour_1.schedule_part == 0 %} {% include "users/button_free.html" with button_id=hour_1.schedule_part %} {% else %} {% include "users/button_busy.html" with button_id=hour_1.schedule_part %} {% endif %} {% endfor %} hour_1 is for example [0,0,1,1,0] Displays only button_busy When debugging hour_1.schedule_par raises VariableDoesNotExist exception. How should I get to the hour_1 elements -
Django - Python: Shopping bag for theatre tickets. Ticket models for two separate prices (adult_price/ child_price)
I am setting up a Django project to allow tickets to be sold for various theatre dates with a price for adults and a price for children. I have created a models.py and ticket_details.html. I am unfortunately receiving the error: 'int' object has no attribute 'get' and I am at a loss to how I am to get the adult and child price for the total calculations to display in my bag.html. The problem is with my contexts.py and views.py files. I have tried the 'get' option but it is not working. Can someone advise? enter image description here models.py: class Show(models.Model): '''Programmatic Name''' name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) poster = models.ImageField(null=True, blank=True) def __str__(self): return self.name def get_friendly_name(self): return self.friendly_name class Ticket(models.Model): show = models.ForeignKey('show', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=254) event_date = models.CharField(max_length=254) description = models.TextField(null=True, blank=True) event_details = models.TextField(null=True, blank=True) place = models.CharField(max_length=254) location = models.CharField(max_length=254) position = models.CharField(max_length=254) image = models.ImageField(null=True, blank=True) price_details = models.TextField(null=True, blank=True) date = models.DateTimeField(null=True, blank=True) adult_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) child_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) def __str__(self): return self.name ticket_detail.html: <form class="form" action="{% url 'add_to_bag' ticket.id %}" method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group w-50"> … -
How to optimize multi column indexing in Django with PostgreSQL
In my application I have this model: class ObservedData(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) unique_id = models.CharField(max_length=128) timestamp = models.DateTimeField() value = models.FloatField(null=True) 90% of my queries are select * from ObservedData where user=<user> AND unique_id=<uid> AND timestamp BETWEEN <date1> AND <date2> This is how I am indexing: class Meta: indexes = [ models.Index(fields=['user', 'unique_id', 'timestamp']), models.Index(fields=['user', 'unique_id']), models.Index(fields=['unique_id', 'timestamp']), ] unique_together = ('user', 'unique_id', 'timestamp') Is this the correct way to do it? I have noticed an increased growth of the database allocated space and I was wondering if this is an overloading or unnecessary overlapping of indexes. -
RetrieveUpdateDestroyAPIView image field when i update a field in django rest framework
i created this api which has a model collection where there is an image field. the list and collection creation part is not a problem but the part of detail especially update has a problem, when I want to update a field I get an error because the image field is not filled in. How can I fix this, I would like if I don't change the image the file will remain the same. model class Collection(models.Model): name = models.CharField(max_length = 255) description = models.TextField() discount = models.PositiveIntegerField(default = 0) image = models.ImageField(upload_to ='collection/') active = models.BooleanField(default = False) def __str__(self): return self.name serializer class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields = ('id', 'name', 'description', 'discount', 'image', 'active') views class CollectionDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Collection.objects.all() serializer_class = CollectionSerializer url path('collections/', CollectionListCreate.as_view(), name="collections-list"), path('collections/<int:pk>/', CollectionDetail.as_view(), name="collection-detail"), -
DJANGO: How to Display or Access Data from ListView and DetailView on The Same Page / Template?
I want to be able to render, display or access List-view and Detail-view on this same page or Django templates. Below is what I tried so far. Here is a link to where I got a very similar but limited code on how to solve this issue. (DJANGO: How to access data from ListView and DetailView on the same template?). The result when I runserver.py shows a completely blank page with no single error even on the terminal Please Help me resolve this issue. THANKS A LOT models.py class Reports(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=255) name = models.CharField(max_length=255) email = models.EmailField(max_length = 254) phone = models.CharField(max_length=11) address = models.CharField(max_length=255, blank=True, null=True) subject = models.CharField(max_length=255) message = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) due = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ('-created',) views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.views.generic.list import ListView from django.views.generic.detail import DetailView from datetime import timezone, tzinfo from . models import Reports # Create your views here. class index(TemplateView): template_name = 'reports_list.html' class ReportsListView(ListView): model = Reports # context_object_name = 'data' def get_queryset(self): return Reports.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') class Detail(DetailView): model = Reports def get_context_data(self, **kwargs): context … -
Django postgres psycopg2: ImproperlyConfigure even though module installed
I am using Django for the first time but have used PostgreSQL previously. I am trying to follow the official Django tutorial to set up with a database. I have followed everything but I get an error when using the command "python manage.py migrate" that psycopg2 is not found even though I have it installed.Traceback (most recent call last): File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/alexanderverheecke/Documents/GitHub/mysite/manage.py", line 22, in <module> main() File "/Users/alexanderverheecke/Documents/GitHub/mysite/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import … -
Django rest filter by serializermethodfield with custom filter
As declared in question title, i got task to filter results by field not presented in model but calculated by serializer. Here is the view code: class RecipeViewSet(ModelViewSet): queryset = Recipe.objects.all() permission_classes = [IsAdminOrAuthorOrReadOnly, ] serializer_class = RecipeInSerializer pagination_class = LimitPageNumberPagination filter_backends = [DjangoFilterBackend] filterset_fields = ['tags', ] filter_class = RecipeFilter Serializer: class RecipeOutSerializer(serializers.ModelSerializer): tags = ManyRelatedField(child_relation=TagSerializer()) author = CustomUserSerializer() ingredients = serializers.SerializerMethodField() is_favorite = serializers.SerializerMethodField() is_in_shopping_cart = serializers.SerializerMethodField() class Meta: fields = '__all__' model = Recipe def get_ingredients(self, obj): ingredients = IngredientAmount.objects.filter(recipe=obj) return GetIngredientSerializer(ingredients, many=True).data def get_is_favorite(self, obj): request = self.context.get("request") if request.user.is_anonymous: return False return Favorite.objects.filter(recipe=obj, user=request.user).exists() def get_is_in_shopping_cart(self, obj): request = self.context.get("request") if not request or request.user.is_anonymous: return False return ShoppingCart.objects.filter(recipe=obj, user=request.user).exists() And custom filter code: class RecipeFilter(rest_framework.FilterSet): tags = ModelMultipleChoiceFilter( field_name='tags__slug', to_field_name="slug", queryset=Tag.objects.all() ) favorite = BooleanFilter(field_name='is_favorite', method='filter_favorite') def filter_favorite(self, queryset, name, value): return queryset.filter(is_favorite__exact=True) class Meta: model = Recipe fields = ['tags', ] Target is is_favorited field that return boolean value. I tried writing func in custom filter class that return queryset but didnt work, neither documentation helped me with examples. Hope for your help. -
render a word document download as a response using django rest framework
I used the python-docx module to create a word document. In my views.py file. I want to be able to render or trigger a download of this word document as a response using django rest framework. Most of the solutions have a file already saved in the database, I need a solution where the file is being created dynamically like with the python-docx module. How can this be done? I tried using custom renderers but I'm not sure how to go about it -
How to find the location of a news article (i.e. the news is related to which place) from a news website?
I am making a news app that aggregates news from different news websites. I have successfully made the UI and the scrapping part is also done. But I am unable to get the location of the news article wherefrom the news is based. Suppose, the news is of Masachuttes from the USA Today. So, I need to extract the location - Masachuttes from the news website - USA Today. This is my problem description. So, I need your help in this regard. I tried the Geo-Location API but it did not work as it only asks for the user permission so it went in vain. As of now, I have no idea how to do it. Expectation is that I could scrape the loation of a particular news article of a news website. -
Override_settings not working at runtime with pytest DJANGO
In my settings.py file inside my django proyect I added a new constant ALLOW_SELF_REGISTRATION, that constant will allow or not a url in the proyect in the way: if settings.ALLOW_SELF_REGISTRATION: urlpatterns += [path( "self_registration/", views.self_registration_client, name="self_registration" ),] My problem is that I need to test when that constant is set to False in that case the url should not be added and a test to that url must raise a NoReverseMatch. I found that the override_settings is not working as expected, I do differents attemps to see if any could work, but no. Until now i tried: def test_constant_on_change_edit_urls_on_false(client): with override_settings(ALLOW_SELF_REGISTRATION=False): with pytest.raises(NoReverseMatch): response = client.get(reverse('profiles:self_registration')) If I print the value of the constant in that test is set to True (as default) and not False as it should by the override_settings context manager. I need a way to override that constant at runtime inside the tests so I can test that functionality. Also tried: @override_settings(ALLOW_SELF_REGISTRATION=False) def test_constant_on_change_edit_urls_on_false(client): with pytest.raises(NoReverseMatch): response = client.get(reverse('profiles:self_registration')) But also failed. There is any way to change that value at runtime during the tests? -
How connect Django with SQLServer 2008 r2
I tried connect Django with SQL Server 2008 r2 SP3. But when y run "python manage.py migrate" i get "django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Sintaxis incorrecta cerca de 'OFFSET'. (102) (SQLExecDirectW)")" My Settings: DATABASES = { "default": { "ENGINE": "mssql", "NAME": "xx", "USER": "xx", "PASSWORD": "xx", "HOST": "xx", "PORT": "1433", "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", }, }, } Version SQL Server: Microsoft SQL Server 2008 R2 (SP3) - 10.50.6000.34 (X64) Aug 19 2014 12:21:34 Copyright (c) Microsoft Corporation Express Edition with Advanced Services (64-bit) on Windows NT 6.3 (Build 19045: ) (Hypervisor) Version Python: 3.8.10 Version Django: 3.1.7 -
Create template with two forms
Good morning, I'm new to python and I have a problem with data entry. Some of the data is in a form and other data is selected and stored in another table. How can I load the two forms that are related in the same Template? I will appreciate if you can help me. Thank you forms.py from cProfile import label from dataclasses import fields from datetime import date, datetime from email.policy import default import imp from mailbox import NoSuchMailboxError from random import choices from django import forms import datetime,django.utils from django.contrib.admin.widgets import AdminTimeWidget, AutocompleteSelect from django.contrib.admin import widgets from .models import Detalle_remito, Personas, Recursos, Remito from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms.widgets import NumberInput OPERADOR=( ('Fabiana', 'Fabiana'), ('Ma. Laura', 'Ma. Laura'), ('Adrian', 'Adrian'), ('Martín', 'Martín'), ('Andres', 'Andres'), ) USO=( ('INTERNO', 'INTERNO. Uso dentro de la Universidad'), ('EXTERNO', 'EXTERNO. Uso fuera de la Universidad') ) DIA_SEMANA=( ( '0', 'Lunes'), ( '1', 'Martes'), ( '2', 'Miercoles'), ( '3', 'Jueves'), ( '4', 'Viernes'), ( '5', 'Sabado'), ) class DetalleRemitoForm(forms.ModelForm): class Meta: model = Detalle_remito fields = {'id_remito', 'fecha', 'hora_retiro', 'hora_devolucion', 'id_recurso', 'estado'} class formularionuevo (forms.Form): uso=forms.ChoiceField(label="Uso del equipamiento ",choices=USO, widget=forms.widgets.RadioSelect(), initial='INTERNO') fecha_retiro=forms.DateField(label="Fecha retiro ",widget=NumberInput(attrs={'type': 'date'}), initial = datetime.date.today()) hora_retiro=forms.TimeField(label="Hora … -
How to define my aggregate function in django orm
I want to define an aggregate function, but I don't understand the example in Django document toally. -
Save zip to FileField django
I have a view that create two csv and my goal is to zip them and add to a model.FileField zip = zipfile.ZipFile('myzip.zip','w') zip.writestr('file1.csv', file1.getvalue()) zip.writestr('file2.csv', file2.getvalue()) I have tried this, the zip is upload but when I download it I have the error 'the archive is damaged or unknown format' Mymodel.objects.create(zip = File(open('myzip.zip','rb')) -
I can't use the command ' python manage.py makemigrations' in django VSC
I already did 'python manage.py migrations'. Now i want to create '0001_inital.py' file in migrations with the code 'python manage.py makemigrations'. Firstly this is my models.py; from django.db import models class Room(models.Model): #host = #topic = name = models.CharField(max_Length=200) description = models.Textfield(null=True, blank = True) #participants = updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add = True) def __str__(self): return str(self.name) And here is the some of the errors that when i write 'python manage.py makemigrations'. File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\base\models.py", line 5, in class Room(models.Model): File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\base\models.py", line 8, in Room name = models.CharField(max_Length=200) File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\new_env\lib\site-packages\django\db\models\fields_init_.py", line 1121, in init super().init(*args, **kwargs) TypeError: Field.init() got an unexpected keyword argument 'max_Length' -
Converting two complex dictionary list to a dictionary
suppose I have two dictionary list below: all=[] lis1={ 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } lis2={ 'code':'fropm', 'commandes':[ { 'date':'04-08-21', 'content':[ { 'article':'Article2', 'designation':'Designe2', 'quantity':3 } ] } ] } Now I add at list level my two dictionaries all.append(list1) all.append(liste2) to replace the [..] in {..} for a single list we can do all[0] But after adding the two lists and then doing all[0] we only have the first list whose [..] whose square brackets are replaced by {..} I would like to have this rendering { {...}, {...} } Is this possible?? -
python django app deploy error in cpanel?
I can't solve Cpanel 503 Error. If anyone can solve this problem please Help me. For hosting Django project I have tried many time with many python versions but showing same error -
How to use Filterset and paginateion in ApiView?
I am trying to use PageNumberPagination and FilterSet in APIView. But I have an error below in my code. object of type 'ListSerializer' has no len() How to implement this? Here are the code: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' class MyFilter(filters.FilterSet): class Meta: model = MyModel fields = '__all__' class MyAPIView(views.APIView, PageNumberPagination): def get(self, request, *args, **kwargs): filterset = MyFilter(request.query_params, queryset=MyModel.objects.all()) if not filterset.is_valid(): raise ValidationError(filterset.errors) serializer = MySerializer(instance=filterset.qs, many=True) paginate_queryset = self.paginate_queryset(serializer, request, view=self) return Response(paginate_queryset.data) Django 3.2.6 django-filter 22.1 djangorestframework 3.12.4 Python 3.8 -
What is the difference between Django timezone now and the built-in one?
I've just noticed this: >>> import datetime >>> from django.utils import timezone >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).microseconds 999989 >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).seconds 86399 >>> 24*60*60 86400 >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).days -1 >>> timezone.now() datetime.datetime(2022, 11, 17, 13, 1, 36, 913132, tzinfo=<UTC>) >>> datetime.datetime.now(tz=datetime.timezone.utc) datetime.datetime(2022, 11, 17, 13, 1, 41, 913958, tzinfo=datetime.timezone.utc) How do both options to get the current time with the UTC "timezone" differ? Why is the difference a positive number of seconds, but exactly negative one day? Can I replace timezone.now() by datetime.datetime.now(tz=datetime.timezone.utc)? -
In Celery Task, MyModel matching query does not exist
I am trying to run my django application using docker which involves celery. I am able to set everything on local and it works perfectly fine. However, when I run it docker, and my task gets executed, it throws me the following error: myapp.models.mymodel.DoesNotExist: mymodel matching query does not exist. I am particularly new to celery and docker so not sure what am I doing wrong. Celery is set up correctly, I have made sure of that. Following are the broker_url and backend: CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' This is my docker-compose.yml file: version: "3.8" services: redis: image: redis:alpine container_name: rz01 ports: - "6379:6379" networks: - npm-nw - braythonweb-network braythonweb: build: . command: > sh -c "python manage.py makemigrations && python manage.py migrate && gunicorn braython.wsgi:application -b 0.0.0.0:8000 --workers=1 --timeout 10000" volumes: - .:/code ports: - "8000:8000" restart: unless-stopped env_file: .env networks: - npm-nw - braythonweb-network celery: build: . restart: always container_name: cl01 command: celery -A braython worker -l info depends_on: - redis networks: - npm-nw - braythonweb-network networks: braythonweb-network: npm-nw: external: false I have tried few things from different stackoverflow posts like apply_async. I have also made sure that my model existed. -
I want create comment section that can only logged in users can use but i have this problem
cannot unpack non-iterable bool object profile = Profile.objects.get(Profile.user == request.user) this is my models.py in account app and blog app: class Profile(models.Model): STATUS_CHOICES = ( ('manager', 'مدیر'), ('developer', 'توسعهدهنده'), ('designer', 'طراح پروژه'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.CharField(max_length=50, blank=True) task = models.CharField(choices=STATUS_CHOICES, max_length=20, blank=True, null=True, default=None) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/photos/%Y/%m/%d/', blank=True) def __str__(self): return f'{self.user.get_full_name()}' class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) and this is my views.py for comments: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) tags = Tag.objects.all() tagsList = [] for tag in post.tags.get_queryset(): tagsList.append(tag.name) profile = Profile.objects.get(Profile.user == request.user) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.profile = profile new_comment.post = post new_comment.save() return redirect('post_detail', slug=post.slug) else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags}) Is there any solution for this problem?