Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django chat working on project_ip:8000 but not on project_ip
My django chat is working if I run my project on port xx.xx.xx.xx:8000 but the moment I run iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000 to map 8000 to 80, to run my project on ip xx.xx.xx.xx the chat doesn't work, why is this happening ? My project is running on ec2 ubuntu instance -
Initial Dropdown Menu Table Population
I was wondering if someone could help me solve this problem I have. I created a form that populates a table based on the selected name in a dropdown menu, however, when I initially load the page, since it is a for-loop and no option has been selected yet, the for loop runs through all the datapoints, populating the table with all the data for each name, but works fine once an option is chosen. I was wondering if someone could explain how I can get the initial page load to either show nothing or the values of one option, not everything at once until an option is chosen. Thanks for the help. <form method="GET" action="."> <div id="option-wrap"> <select name="option-menu" id="option-menu"> <option value="" hidden disabled selected value id="option-filler">Choose a Name</option> {% for l in options %} <option value="{{loans.company_name}}">{{l.names}}</option> {% endfor %} </select> <button type="submit" class="btn-filter">Filter</button> </div> <div class="card-items"> <table class="main-items-table"> <tr> <td class="menu-box-tab-items-identifiers">Name:</td> {% for l in queryset %} <td class="menu-box-tab-items" href=""><span>{{l.name}}</span></td> {% endfor %} <td class="menu-box-tab-items-identifiers">Sector:</td> {% for l in queryset %} <td class="menu-box-tab-items" href="#6"><span>{{l.sector}}</span></td> {% endfor %} </tr> </tbody> </table> </div> </form> -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__blogapp_created_blog.user_id
I just created a simple childish model but it raise a unpredictable error that is django.db.utils.IntegrityError: NOT NULL constraint failed: new__blogapp_created_blog.user_id enter code here from django.db.models import * from django.db import models class created_blog(Model): user=CharField(max_length=100) blog_title=CharField(max_length=100) blog_subtitle=CharField(max_length=100000000) date=CharField(max_length=100) blog_content=CharField(max_length=1000000000000000) -
Django validate property
Is there any way to apply a Django validator to a property instead of a field? I have a field dob and a property age tied to that field. I'll like to guarantee that age cannot be smaller than 18. -
How to delete an object after 5 minutes? Celery
I am trying to create a periodic task with celery to delete an object after 24 hours of expiration, I have searched and tried several solutions but none of them work celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arhi.settings') app = Celery('arhi') BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') CELERY_BROKER_URL = os.environ.get('REDIS_URL') app.conf.broker_url = BASE_REDIS_URL app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.beat_schedule = { 'every-1-minute':{ 'task':'tarea.tasks.delete_file', 'schedule':60, } } app.conf.timezone = 'America/Bogota' app.autodiscover_tasks() models.py import uuid from django.db import models from django.utils import timezone # Create your models here. class Archivo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) file = models.CharField(max_length=60) fecha_subida = models.DateTimeField(default=timezone.now) class Meta: verbose_name = 'Archivos' Celery executes any other task that you assign to it, but this one to delete some object does not execute it tasks.py from datetime import datetime from django.utils import timezone from celery import shared_task from .models import Archivo @shared_task def delete_file(): files = Archivo.objects.filter(fecha_subida__lte=timezone.now()) if files: files.delete() return "files eliminados" return "no hay archivos" -
Django Nested Query
Here is my view.py class ItemFilter(filters.FilterSet): stk_no=filters.CharFilter(lookup_expr="icontains") itemtran__ledindi=filters.CharFilter(lookup_expr="iexact") part_no=filters.CharFilter(lookup_expr="icontains") brand_name=filters.CharFilter(lookup_expr="icontains") class Meta: model=Item fields=['stk_no','itemtran__ledindi','part_no','brand_name'] class ItemViewSet(viewsets.ModelViewSet): serializer_class = ItemSerializer queryset = Item.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = ItemFilter pagination_class = PostPagination def get_queryset(self): return self.queryset.filter() Here is my serializer.py class ItemTranSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = ItemTran read_only_fields = ( "stk_no_id", ), fields = ( "id", "stk_no", "qty", "trntype", "company", "department", ) class ItemSerializer(serializers.ModelSerializer): itemtran = ItemTranSerializer(many=True) class Meta: model = Item read_only_fields = ( "created_at", "created_by", ), fields = ( "id", "stk_no", "part_no", "brand_name", "itemtran", ) Im trying to filter all items with the "company" field in "ItemTran" filtered. but the api just returns all the transactions. "id": 7614, "stk_no": "NT1515", "part_no": "185/65 R 15", "brand_name": "Brand X", "itemtran": [ { "id": 620855, "stk_no": "NT1515", "qty": 4.0, "trntype": "INV", "company": "I", "department": "I" }, { "id": 632238, "stk_no": "NT1515", "qty": 2.0, "trntype": "ARR", "company": "A", "department": "F" }, where i only need the "itemtran" to show only company "I" rows. i pretty new at this so please any help is greatly appreciated. i have a similar module which works but cant figure out whats wrong here i tried rewriting the whole thing from scratch and still not … -
why i am getting NoReverseMatch error while i am practicing beginner projects from github in Django 4.0.6?
I am getting a NoReverseMatch error after adding the primary key to the URL links in the urls.py file. please solve it. I am a beginner in programming so I could not find a solution for this issue. Thank you for your time and effort. I got this exercise from Github. The code is written below. settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR=os.path.join(BASE_DIR,"templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-6mtsgnhk=-=5ka0-e4619v0_uq)s+t=dtybe8^ojwmg1gwoj**' # 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', 'g7app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'g7.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], '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 = 'g7.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } urls.py from django.contrib import admin from django.urls import path from … -
Elegant way to handle invalid pages in Django with a generic class-based view
I found a partial solution in Django: How to catch InvalidPage exception in class-based views?, but the URL in the address bar still shows the original page request. Django has Paginator.get_page(number), but there doesn't seem to be a way to use it to redirect inside of the view. I originally thought I might be able to do it in get_context_data, but I don't seem to be able to force a redirect as it will only allow a dict as a response. def get_context_data(self, **kwargs): paginator = self.get_paginator(self.queryset,self.paginate_by,self.paginate_orphans) try: context = super().get_context_data(**kwargs) except Http404 as err: self.kwargs['page'] = paginator.get_page(self.request.GET['page']).number return redirect('my_list_view', kwargs=self.kwargs) context['page_list'] = context['paginator'].get_elided_page_range(context['page_obj'].number,on_each_side=2,on_ends=1) return context That fails outright. The following works (per the linked answer above), but does so in a non-optimal way. def get_context_data(self, **kwargs): paginator = self.get_paginator(self.queryset,self.paginate_by,self.paginate_orphans) try: context = super().get_context_data(**kwargs) except Http404 as err: self.kwargs['page'] = paginator.get_page(self.request.GET['page']).number context = super().get_context_data(**kwargs) context['page_list'] = context['paginator'].get_elided_page_range(context['page_obj'].number,on_each_side=2,on_ends=1) return context I feel like there should be a simple/elegant way to do this, but I just haven't found one. I could of course go for a function-based view, but I can't shake the feeling that there's got to be a way to do it this way. -
Django - how to make frontend-customizable sets / groups in models?
I am trying to create an app, that handles laboratory analyses - something like similar Laboraotory Information System (LIS) The issue is that i dont know which approach to take. I am plannin to make it as follows: "ANALYSES" table - consisting of "name", "ID" of analyses "PROBES" table - consisiting of "name", "ID", "reference", "VALUE", "measurement". Also the PROBES will have the field which links it to certain "ANALYSES" instance. SO it will be like "ANALYSES #1" -> "PROBE1", "PROBE2", "PROBE3" "ANALYSES #2" -> "PROBE1", "PROBE3" And so on. The operator should be capable of adding new analyses and adding probes to this analyses via frontend in one "view" - like "LAB settings" and in another view - to enter values to instances of this analyses (all analyses instances will be linked to some "VISIT" - the service case) What approach should i take planning the app and models? will it be some Meta classes or just multiple tables linked "manytoone" or "manytomany"? Will be gratefull for any advice! -
I can't start runserver in django. the error is cannot find python
I'm using a different computer. I have Windows 10 Pro, "py manage.py runserver" does not work for me. Creating a project works for me. I use py -m django startapp My error from the terminal: "I'm using a different computer. I have Windows 10 Pro, "py manage.py runserver" does not work for me. Creating a project works for me. I use py -m django startapp My error from the terminal: "python could not be found. start" please help with that -
Como fazer o deploy do Django + vue.js no heroku? [closed]
Eu estou querendo fazer o Deploy do Django rest + vue.js em apenas um servidor, mas não sei como fazer. -
Mongoengine conditonal query using fastapi
I want to get spacetypes where is_custom is false and where is_custom is true but user should be requested user I've written below code but this seems to give me empty qs spacetypes = SpaceType.objects.filter( Q(is_custom = False) & Q(is_custom = True, user=user) ) -
Annotate new field with the same name as existing one
We are facing a situation here that I would like to get more experienced user’s opinion. We are at Django 4, Python 3.9. The current scenario: We already have our system running in production for a reasonable time and we need to change on the Backend some returned data to our Frontend application (Web, mobile…) based on users choice. Something important is: Changes on the Frontend side are not an option for now. We need to override some attributes from one model, based on existing or not corresponding data on another table. The Tables (Django Models): AgentSearch (this data is replaced every single day by an ETL process) id identifier_number (unique) member_first_name member_last_name member_email some_other_attrbs Agent (Optional data that the agent can define) id agent_search_identifier_number (FK OneToOne) first_name last_name email For our requirement now, all the queryset will be made starting on AgentSearch. The idea is getting the Agent data instead of AgentSearch data every time there is an agent linked to it. Today we get like this: AgentSearch.objects.all() I know that would be easier to annotate new columns like this: # using a different attribute name NEW_member_first_name=Case( When( agent__id__isnull=True, then=F("member_first_name"), ), default=F("agent__first_name"), ), This would require us to make … -
Django Rest How I can Get all values from model Serializer each separately
I have model serializer in django rest frame work I would like to use values from my class serializer for example serializer.py profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'profile'] @api_view(['GET', 'POST']) def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() BUT INSTEAD OF USING Response I would like to make something like serializerd_sername = serializer.data['username'] serializerd_email = serializer.data['email'] serializerd_profile = serializer.data['profile'] and after few if else then some respond but how to get serialized data/values to use? return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
restrict signup with django-allauth
I'm thinking of using Django allauth for user athentication/authorization but am a bit puzzled about how you prevent or screen initial signup. I'm envisioning a small group of maybe 50 users (and I would have a list of these). I see nothing about allauth allowing you to check against my personal list of people who should be allowed access. Is allauth even a good solution in this scenario? Just to reiterate, my concern is not about using, say, Google to verify their email / identity, but rather pre-screening the people who can sign up in the first place. -
Problem with CSS styling in a html page in Django
So, i am literarily one week into learning web development and i'm following this Django tutorial, i got the index page that i swiped from online to compile properly with it's static elements also. Ran the "python3 manage.py collectstatic" command and everything. So now i'm linking a registration page which i setup up as a new app in the project and when i try and put the css styling file it doesn't work. i've tried just puting in the same directory as the html templates, then i've moved it to styles and rerun the earlier python command so it's also present in assets, also made use of the "{% static 'abcde.css' %}" as well as {% load static %} in the register.html (only did it in the index initially) and i'm still having no luck with styling the page, any help would be appreciated -
django: override admin/login with custom loginview and authenticationform but same template
I added an expiry date field to my User. Now I want to add a custom error message to a failed login if the account is expired, because if I only override the ModelBackend's can_authenticate method, the form throws the standard validation error which suggests that the problem resides with the credentials. I prefer clarity. So I extended AuthenticationForm and overwrote its confirm_login_allowed method to do an expiry check and raise a ValidationError with a newly added error message. However, I get complaints from Django that the template does not exist: TemplateDoesNotExist at /admin/login/ registration/login.html urls.py from django.contrib.auth import views as auth_views from my_app.auth.forms import AuthForm urlpatterns = [ # path("admin/", admin.site.urls), # Have to comment out or the next item will not match re_path(r"^admin/login/$", auth_views.LoginView.as_view(form_class=AuthForm), name="login"), re_path(r"^logout/$", auth_views.LogoutView, name="logout"), ... ] my_app/auth/forms.py from django.contrib.auth.forms import AuthenticationForm from django.core.exceptions import ValidationError class AuthForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.error_messages["account_expired"] = "This account has expired." def confirm_login_allowed(self, user): super().confirm_login_allowed(user) if user.expired: raise ValidationError(self.error_messages["account_expired"], code="inactive") -
Django Single sign on (okta): you are not allowed to access this app
I have a very simple Django test app running to try and integrate SSO using Okta as IDP. I am using the Django-saml2-auth library for django sso. When I open the sso related pages im getting the following screen (you are not allowed to access this app): you are not allowed My settings.py looks like this: SAML2_AUTH = { 'METADATA_LOCAL_FILE_PATH': [os.path.join(BASE_DIR, 'metadata.xml')], 'ASSERTION_URL': 'http://localhost:8002', 'ENTITY_ID': 'http://localhost:8002/django_saml2/acs/', } urls: from django.contrib import admin from django.conf.urls import url from django.urls import path, include import django_saml2_auth.views urlpatterns = [ url(r'^django_saml2/', include('django_saml2_auth.urls')), path('accounts/login/', django_saml2_auth.views.signin), path('admin/login/', django_saml2_auth.views.signin), path('admin/', admin.site.urls), ] And Okta settings like this: Okta settings Any help would be very much appreciated. -
openapi.IN_FORM don't work with JSONParser in parser_classes
When I changed parser_classes=[MultiPartParser, FormParser] to parser_classes=[MultiPartParser, FormParser, JSONParser] I get an error when I open swagger: drf_yasg.errors.SwaggerGenerationError: cannot add form parameters when the request has a request body; did you forget to set an appropriate parser class on the view? I need my endpoint to be able to process multipart/formdata or application/json. how can I do it in such code?: @swagger_auto_schema(operation_description='desc', manual_parameters=[ openapi.Parameter('phone', openapi.IN_FORM, description="phone", type=openapi.TYPE_STRING, required=True), ]) def post(self, request, *args, **kwargs): ... -
django update password for User not working
Using django's built in User model I have a basic update password view: class ChangePasswordView(PasswordChangeView): form_class = ChangePasswordForm success_url = reverse_lazy('password_success') def form_valid(self, form): account = self.request.user.account email = account.user.email update_password_notification_task.delay(email) return redirect(self.success_url) def password_success(request): return render(request, 'accounts/password_success.html') its form: class ChangePasswordForm(PasswordChangeForm): class Meta: model = User and its url: path('password/',ChangePasswordView.as_view(template_name='accounts/change_password.html')), And finally, the template: <h1>Change Password...</h1> <form method="POST"> {% csrf_token %} {{form.as_p}} <button>Change Password</button> </form> There are no errors, and everything seems to work, but the password is not being updated. I don't know why, I think I did everything, but for some reason after I update the password and get redirected to the reverse_url if I try logging out and in, the new password doesn't work. I don't know what's causing this issue or in what file, so it's hard to troubleshoot. -
I am creating Django web application for additional payments like Shift allowance on call etc, I am getting HttpResponse error
I am creating Django web application for additional payments like Shift allowance on call etc, I have created several apps under same, shift if one of the among applications, In this app, user will submit shift details and manager will approve it, here I am getting error when manager try to approve users shift details ValueError at /shift/6/ The view shift.views.update_status didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:8000/shift/6/ Django Version: 3.2.5 Exception Type: ValueError Exception Value: The view shift.views.update_status didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\vikasdange\Anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response Python Executable: C:\Users\vikasdange\Anaconda3\python.exe Python Version: 3.9.7 Python Path: ['C:\Users\vikasdange\django\additional_payments', 'C:\Users\vikasdange\Anaconda3\python39.zip', 'C:\Users\vikasdange\Anaconda3\DLLs', 'C:\Users\vikasdange\Anaconda3\lib', 'C:\Users\vikasdange\Anaconda3', 'C:\Users\vikasdange\Anaconda3\lib\site-packages', 'C:\Users\vikasdange\Anaconda3\lib\site-packages\locket-0.2.1-py3.9.egg', 'C:\Users\vikasdange\Anaconda3\lib\site-packages\win32', 'C:\Users\vikasdange\Anaconda3\lib\site-packages\win32\lib', 'C:\Users\vikasdange\Anaconda3\lib\site-packages\Pythonwin'] Server time: Sat, 23 Jul 2022 12:38:22 +0000 project name additional_payments Project additional_payments urls.py file urlpatterns = [ path('', include('login.urls')), path('admin/', admin.site.urls), path('ot/', include('ot.urls')), path('oncall/', include('oncall.urls')), path('shift/', include('shift.urls')), path('accounts/', include('accounts.urls')), ] app shift urls.py file urlpatterns = [ path("shift", views.shift,name="shift"), path("<int:id>/", views.update_status,name="update_status"), path("shift_details/", views.shift_details,name="shift_details"), ] app shift views.py file def shift_details(request): sdetails = Shift.objects.all() return render(request, 'shift_details.html', {'details':sdetails}) def update_status(request, id): if request.method == 'POST': ar_status = Shift.objects.get(pk=id) fm = shiftforms(request.POST,ar_status) if fm.is_valid(): fm.save() return redirect('/') else: ar_status=Shift.objects.get(id=id) fm … -
django-admin startproject my_site problem in vscode
when i am typing command in cmd django-admin startproject my_site it is giving this error please help me universe. I tried everything from installing all to uninstalling all and it is not working and hinderancing my progress to become a web developer. when i am typing command in cmd django-admin startproject my_site it is giving this error please help me universe. I tried everything from installing all to uninstalling all and it is not working and hinderancing my progress to become a web developer. Traceback (most recent call last): File "c:\users\chayan\appdata\local\programs\python\python39-32\lib\site-packages\django\utils\timezone.py", line 10, in <module> import zoneinfo ModuleNotFoundError: No module named 'zoneinfo' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\chayan\appdata\local\programs\python\python39-32\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\chayan\appdata\local\programs\python\python39-32\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\CHAYAN\AppData\Local\Programs\Python\Python39-32\Scripts\django-admin.exe\__main__.py", line 9, in <module> File "c:\users\chayan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "c:\users\chayan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\chayan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\__init__.py", line 279, in fetch_command klass = load_command_class(app_name, subcommand) File "c:\users\chayan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\__init__.py", line 48, in load_command_class module = import_module("%s.management.commands.%s" % (app_name, name)) File "c:\users\chayan\appdata\local\programs\python\python39-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1021, in _gcd_import File "<frozen importlib._bootstrap>", line 998, in _find_and_load … -
How do I properly deserialize data with django-money?
I have Model that contains MoneyField from djmoney class Task(models.Model): description = models.CharField(max_length=512) user = models.ForeignKey("user.User", on_delete=models.CASCADE) price = MoneyField( max_digits=8, decimal_places=2, default_currency="USD", default=0) Serializer class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = "__all__" read_only_fields = ("user",) My APIView POST function of Viewset def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=201, headers=headers) def perform_create(self, serializer): serializer.save(user=self.request.user) When I'm trying to POST data in format like this { "description": "Test", "price": "20.00" } It gives me an error, that 'decimal.Decimal' object has no attribute 'amount' with given Traceback. How can I solve this issue? Traceback (most recent call last): File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/user/PycharmProjects/my_project/tackapp/tack/views.py", line 37, in create serializer.is_valid(raise_exception=True) File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/serializers.py", line 227, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/serializers.py", line … -
how to link 3 models / tables and filter by value in django
in my database I have three tables: account.customer with "id" field account_customer_groups with "group_id" field auth_group with "name" field how to link with object.filter these 3 models to select the "name" field of the auth_group table which has the value "myvalue" my accounts/models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError('Vous devez entrer une adresse email.') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email=email, password=password) user.is_staff = True user.is_admin = True user.save() return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=255, unique=True, blank=False ) nom = models.CharField(max_length=50, blank=False, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = "email" def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" return True def __str__(self): return self.email and my catalog/views.py from django.shortcuts import render from catalog.models import Book, Author, BookInstance, Genre from accounts.models import CustomUser from django.views.generic import ListView, DetailView from django.contrib.auth.models import Group class BookDetailView(DetailView): """Generic class-based detail view for a book.""" model = Book class AuthorListView(ListView): """Generic class-based list view for a list of … -
Media volume inaccessible to Celery using Docker
I'm dockerizing a Django app and I'm having quite some trouble with it. I have the Django app using postgres as well as nginx and gunicorn successfully settled. However, when dockerizing Celery, it seems that it doesn't have access to my media files. I've been looking for the reason for a few hours, but nothing came up. The only thing I saw that I found strange was that my media volume seems to be empty when checking on Docker desktop, but I don't even know if that's the way it should or not... I've tried different approaches on the definition of the media volume in my Celery container but to no avail. Here is my docker-compose.yml: version: '3.8' services: rabbitmq3: container_name: rabbitmq image: rabbitmq:3-alpine ports: - 5672:5672 postgres: container_name: postgres hostname: postgres image: postgres:latest env_file: - env environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=ThisPasswordShouldBeChanged19456 - POSTGRES_DB=Scripts Application ports: - "5432:5432" restart: on-failure volumes: - postgresql-data:/var/lib/postgresql/data django_gunicorn: container_name: django_gunicorn volumes: - media:/media env_file: - env build: context: . ports: - "8000:8000" command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000" depends_on: - postgres nginx: container_name: nginx build: ./nginx volumes: - .:/code - static:/static ports: - "80:80" …