Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get unique data for each column from the database in one query (Django ORM)?
I need to get UNIQUE data from EACH column I have a list of fields: MY_FIELDS = ['id', 'created', 'And_more_28'] My HORRIBLY INEFFECTIVE code that produces the correct result qs = Sheets.objects.all() v = [] v += [list(qs.values(v).distinct()) for v in MY_FIELDS] I get what I need.... But at what cost? (28 requests is painful) Tell me how to make one query out of this.... This is how it produces non-unique data for EACH column (tried it) qs = Sheets.objects.all().values(*MY_FIELDS).distinct() -
Increasing span limits in Sentry python
I tried to increase the limit of span by setting up _experiments: {"max_spans": 5000} in the sentry_sdk.init() but the trace doesn't appear on the sentry server if i try to capture a small trace it works. Any ideas if there is any limit enforced on server side too? -
show two different models as the foreign key
There's two models Groups and Sub_groups. How can I show both models in particulars field as foreign key? models.py class Groups(models.Model): name = models.CharField(max_length=255) under = models.CharField(max_length=255) def __str__(self): return self.name class Sub_groups(models.Model): name = models.CharField(max_length=255) under = models.ForeignKey(Groups, on_delete=models.CASCADE, null=True, blank=True, related_name='sub_groups') def __str__(self): return self.name class Voucher(models.Model): particulars = models.ForeignKey(Groups, on_delete=models.CASCADE, null=True, blank=True, related_name='vouchers') #how to add both groups and sub_groups data in particulars here? What I have done so far: forms.py class PaymentVoucherForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PaymentVoucherForm, self).__init__(*args, **kwargs) # Populate the choices for the 'particulars' field with both groups and subgroups group_choices = [("g_" + str(group.id), group.name) for group in Groups.objects.all()] subgroup_choices = [("sg_" + str(subgroup.id), subgroup.name) for subgroup in Sub_groups.objects.all()] # Concatenate the group and subgroup choices all_choices = group_choices + subgroup_choices # Set the choices for the 'particulars' field self.fields['particulars'].choices = all_choices class Meta: model = Voucher fields = ['particulars',] template: <form method="POST"> {% csrf_token %} {{form|crispy}} <input class="btn btn-info btn-block" type="submit" value="Submit"> </form> It gives following error: Select a valid choice. That choice is not one of the available choices. P.S g_ and sg_ are added to the ids of groups and sub_groups respectively since both the models has same ids like … -
Django Throws 302 error when I call API written on Questions app and redirects to /login/?next=/api/questions/tags-list/
I have written an API URL on questions model for retrieving a 1st 10 tags, its a get call. When I call it from the react app, i am getting 302 to that api and redirects to http://localhost:8093/login/?next=/api/questions/tags-list/ with 200 responses as html code for django admin pannel login. I have not implemented the authentication and it's not required. Django - 4.2.7 I tried working on adding middlewares for the restframework and is still having the same issue The below shown is the base app urls, urlpatterns = [ path('jet/', include('jet.urls', 'jet')), path('', admin.site.urls), path(r'/api/questions/', include('question.urls')), path(r'user_auth/', include('user_auth.urls')) ] The questions urls is as follows: urlpatterns = [ path('/tags-list/', TagsView.as_view(), name='tags-list' ), path('match-tags/', MatchTags.as_view(), name='matching-tags'), path('presigned-urls/', PresignedURL.as_view(), name='presigned_url'), path('question-submission/', QuestionSubmission.as_view(), name='question-submission') ] this is the view called. class TagsView(APIView): def get(self,request): print("HI", flush=True) tags = Tag.objects.all()[:10] # Get first 10 tags serializer = TagSerializer(tags, many=True) return Response(serializer.data) on settings.py INSTALLED_APPS = [ 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'user_auth', 'corsheaders', 'question', 'storages', 's3direct', 'file' ] AUTH_USER_MODEL = 'user_auth.User' SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1000), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1000), 'AUTH_USER_MODEL': 'user_auth.User' } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
DRF requires the user to be logged in to use login_user api
I am trying to create a CustomUserViewset, and add a login_user api to it. The problem is that although I set the permission_classes to AllowAny, still when calling the login_user api, it says: {"detail":"Please login to perform this action"}. Here is my API: class CustomUserViewset(AutoPermissionViewSetMixin, viewsets.ModelViewSet): queryset = User.objects.none() serializer_class = CustomUserSerializer permission_type_map = { "create": "add", "destroy": "delete", "partial_update": "change", "retrieve": "view", "update": "change", "register": "view", "login_user": "view", "logout": "change", } @decorators.action(methods=["POST"], detail=False, permission_classes=[permissions.AllowAny]) def login_user(self, request): serializer = LoginSerializer(data=request.data) if not serializer.is_valid(): raise exceptions.ValidationError({"detail": "Invalid username or password"}) username = serializer.validated_data["username"] password = serializer.validated_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response(CustomUserSerializer(user).data, status=status.HTTP_200_OK) else: raise exceptions.AuthenticationFailed({"detail": "Invalid username or password"}) As you see, I have permission_classes=[permissions.AllowAny] in the api action. Also, giving this permission class in the action was the last thing I tried, before that, I tried to adjust the permission in rules.py: import typing import rules if typing.TYPE_CHECKING: from .models import User rules.add_perm("accounts.login_user", rules.predicates.always_allow) None of the above methods has worked, and I still get the same message that I need to log in to perform this action. -
AttributeError : 'NoneType' object has no attribute 'lower'
I installed django-comments-dab package and i have done steps like documents but recived this error: AttributeError: 'NoneType' object has no attribute 'lower' how can i fix it? def get_model_obj(app_name, model_name, model_id): content_type = ContentType.objects.get(app_label=app_name, model=model_name.lower('')) model_object = content_type.get_object_for_this_type(id=model_id) return model_object -
My Django endpoint does not access the has_object_permission method
Here's a view class that I have: from rest_framework.views import APIView class MyView(APIView): permission_classes = [CustomAccessPermission] def get(self, request, id: int) -> Response: object = get_object_or_404(MyObjectClass, id) serializer = MySerializer(object) return Response(serializer.data) def delete(self, request, id: int): object = get_object_or_404(MyObjectClass, id) object.status = MyObjectClass.Status.DELETED object.save() return Response(status=status.HTTP_200_OK, data=id) Here's my custom access permission class: from rest_framework import permissions from django.core.exceptions import PermissionDenied class CustomAccessPermission(permissions.BasePermission): message = "You cannot access objects created by other users." def has_object_permission(self, request, view, obj): if obj.user_id != request.user.id: raise PermissionDenied(self.message) return True So within my objects I store user_id that contains IDs of users that created this object. I want to check if the id from request is equal to that user_id to undestand if user can see this object. So, for example, when I run GET:http://localhost:8050/api/objects/4 i want to take the user_id of object with id=4 and if it's equal to request.user.id then we'll allow the user to see it, otherwise we should deny. The same with DELETE requests, they should be first checked against the user_id of object. This code above doesn't work, it doesn't access the has_object_permission() method in my permission class. What should I modify? -
removing trailing slashes from django multi language url pattern (i18n_patterns)
I'm trying to get rid of trailing slash from urls. Currently the web-server successfully removes slashes and APPEND_SLASH = false Everything works fine but I have a problem with the localized homepage: http://example.com/en/ - ok http://example.com/en - Page not found (404) I add this class to Middleware: from django.shortcuts import redirect from django.utils import translation class RemoveTrailingSlashFromMultilingualURLsMiddleware: def init(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Check if the URL ends with a language code and a slash language_code = translation.get_language() if request.path.endswith(f'/{language_code}/') and request.path != f'/{language_code}/': new_path = request.path.rstrip('/') return redirect(new_path) and add MIDDLEWARE to setting: MIDDLEWARE = [ # ... other middleware 'blog.middleware.RemoveTrailingSlashFromMultilingualURLsMiddleware', # ... other middleware ] But it doesn't work and keeps giving 404 not found error if possible help me to solve my problem thanks a lot -
Django+Cython Deployment with Gunicorn
I have a Django application and I don't want to provide access my source code. As a result of my research, I used the Djcompiler library, which basically uses Cython. As a result, I converted the project into .so modules. When I run this converted project with the python3 manage.py runserver command, the project runs smoothly. However, when I run the project for production via Gunicorn with the gunicorn tracking.wsgi.python-39-darwin:application --bind0.0.0.0:7005command, I get the following errors. ModuleNotFoundError: No module named 'accounts.urls' ModuleNotFoundError: No module named 'log.models' How can I successfully implement this Cython converted project to .so modules with Gunicorn? -
How to test nested Serializers in Django Rest?
I have a ToDo App Django project, and so there are Task and TaskList models which are linked with a ManyToMany relation. Inside my TaskSerializer, I have defined a nested TaskListSerializer which handles the reverse relation of a task's tasklists. Everything is going well in real world, and the serialization and deserialization is ok. This is what you should put request when updating a task (as json): { "title": "hello", "tasklists": [ {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"}, {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"} ] } But inside the Tests, I want to test this serializer and, when I'm sending the put request the tasklists field is not sent to the view! This is the test request: path = self.task.get_absolute_api_url() data = { "title": "hello", "tasklists": [ {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"}, {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"} ] } self.client.put(path, data) But there is no tasklists field inside the validated_data and initial_data of view.(the title field is sent and validated) I guess that the Renderer and json_encoder have the problem with this type of data. so how should the correct request data be inside a nested serializer test? In General, How to test a Nested Serializer! -
How to handle forward slash in API call
I know this goes against all of the rules, but I have a database that has a primary key in the format of /. Ex. 12345/A. I'm using Django Rest Framework and can't seem to make the API call to retrieve this record. The Django admin changes this to 12345_2FA in the URL, but this doesn't work for the API call. Thanks! -
Django Password Reset Form Not Showing When Using DRF, Works from Website
I'm facing an issue with my Django application involving the password reset functionality. When the password reset link is sent via the standard Django website flow, everything works as expected: the user receives an email with a link, and upon clicking it, they are taken to a page with a form to reset their password. However, when the reset link is sent through a Django Rest Framework (DRF) API (triggered from a Flutter app), the user still receives the email with a link, but the page that opens does not show the password reset form. The rest of the HTML content on the page renders correctly, but the form itself is missing. Here's the relevant part of my CustomPasswordResetConfirmView in Django: class CustomPasswordResetConfirmView(PasswordResetConfirmView): form_class = SetPasswordForm success_url = reverse_lazy('users:password_reset_complete') template_name = 'users/password_reset_confirm.html' @method_decorator(sensitive_post_parameters('new_password1', 'new_password2')) @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form_class(user=self.request.user) return context And the template users/password_reset_confirm.html is as follows: <main class="mt-5" > <div class="container dark-grey-text mt-5"> <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Reset Password</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Reset Password</button> </div> </form> </div> </div> </main> I am not sure … -
conditional constraints for django model
I have database model like this ActionType = ( (1,"PostBack"), (2,"Uri"), ) class RichMenu(BaseModel): key = m.CharField(max_length=64,unique=True) action_type = m.IntegerField(choices=ActionType,default=1) url = m.CharField(max_length=255,blank=True,null=True) name = m.CharField(max_length=255,blank=True,null=True) Now I would like to make constraint like this, When action_type is 1, url should be null and name should not be null When action_type is 2, name should be null and url should not be null Is it possible to make conditional constraints for this case? -
Nginx can't load static files, did I set wrong path?
I tried setting up nginx with docker on my django project. I checked the volume exists on docker container. And I do have access to my swagger path, but staticfiles does not load. What else can I attempt? Thanks... For example, as settings.py has set the path: # Static files STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") and here is nginx/nginx.conf, may see locaiotn in http: events { worker_connections 1024; } http { upstream django { server web:8000; } server { server_name localhost; access_log off; listen 80; location /static/ { alias /app/staticfiles/; } location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } And finally, docker-compose script: version: '3.8' services: web: build: . command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 --timeout 120 --workers 3 volumes: - .:/app - static_volume:/app/staticfiles ports: - "8000:8000" depends_on: - redis nginx: image: nginx:latest volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - static_volume:/app/staticfiles ports: - "80:80" depends_on: - web ...... volumes: static_volume: -
Como aplico estilos a un img de un modelo en Django? [closed]
Quiero aplicar estilos en css a los img para que queden centrados y del mismo tamaño pero no se aplica ninguno, intenté de varias formas hasta utilicé chatgpt y aún asi no pude arreglar este problema que tengo. aquí el código class Taza(models.Model): nombre = models.CharField(max_length=20, verbose_name="Nombre") imagen = models.ImageField(upload_to='img/tazas') def __str__(self): return self.nombre def imagen_url(self): return self.imagen.url <div class="container d-flex justify-content-center"> <section class="layout"> {% for ta in taza %} <div><img src="{{ ta.imagen_url }}" alt="{{ ta.nombre }}"></div> {% endfor %} </section> </div> .layout { width: 1366px; height: 768px; display: grid; grid-template-rows: repeat(3, 1fr); grid-template-columns: repeat(3, 1fr); gap: 8px; } div.layout img { max-width: 100%; height: auto; } -
Django queryset remove all duplicates(not just remove one of them)
for example, I have a queryset1 = [objects1, objects2, objects2, objects3] and I know queryset1.distinct() can return [objects1, objects2, object3] but I don't want the objects2 anymore cause there could be some issues so what I want to get is [objects1, object3] -
Django : What is the best way to Generic list (Product) and detail view (Category)
It is better to use class based view or function view? use get_absolute_url or slugify? How to use for and if to display categories in the menu? Some issues are really confusing And it is impossible to understand which way is the best views.py: class ProductView(ListView): template_name = 'main/Html/html_components.html' model = Product class ProductCategoryView(DetailView): model = ProductCategory url: urlpatterns = [ path('', ProductView.as_view(), name='Product'), path('category/', ProductCategoryView.as_view(), name='category-detail'), # path('<int:pk>/', ProductCategoryView.as_view(), name='category-detail'), # path('category/<slug:slug>/', ProductCategoryView.as_view(), name='category-detail'), ] html: html(for loop) {% load static %} <nav class="menu__main"> <ul class="menu"> {% for ProductCategory in ProductCategory %} <li class="single"> <a href="" class="single__link"> <span class="single__text">{{ ProductCategory.title }}</span> </a> </li> <li class="dropdown"> <a href="javascript:void(0);" class="active dropdown__link"> <span class="dropdown__text">Forms</span> <svg class="dropdown__arrow"><use href="#arrow-down"></use></svg> </a> <ul class="dropdown__list"> <li class="dropdown__list__item"> <a href="" class="dropdown__list__link"> <span class="dropdown__list__text">Checkbox</span> </a> </li> <li class="dropdown__list__item"> <a href="" class="dropdown__list__link"> <span class="dropdown__list__text">Radio</span> </a> </li> </ul> </li> {% endfor %} </ul> </nav> models:py class ProductCategory(models.Model): title = models.CharField(max_length=100, null=False, blank=False, unique=True, verbose_name='Title') slug = models.SlugField(max_length=300, blank=True, unique=True, verbose_name='slug') create_date = models.DateTimeField(auto_now_add=True, verbose_name='Create Date') class Meta: verbose_name = 'Category' def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=200, null=False, blank=False, unique=True, verbose_name='Title') slug = models.SlugField(max_length=300, allow_unicode=True, null=False, blank=False, unique=True, verbose_name='slug') category = models.ForeignKey('ProductCategory', null=True, blank=True, db_index=True, on_delete=models.CASCADE, verbose_name='Category Parent') class … -
Django Facebook Login Authentication
I had an application that was using Facebook to login and authenticate. However from May onwards something happen and now users when trying to go to the site they are getting this error message. import os from pathlib import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'paymentlist', 'bootstrap_datepicker_plus', 'bootstrap4', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'django.contrib.sites', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', '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', 'django_user_agents.middleware.UserAgentMiddleware', ] ROOT_URLCONF = 'paymesite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'microsoft_auth.context_processors.microsoft', ], }, }, ] WSGI_APPLICATION = '' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases # # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': str(os.path.join(BASE_DIR, "db.sqlite3")), # } # } DATABASES = { 'default': { 'ENGINE': '', 'NAME': , 'USER': , 'PASSWORD': , 'HOST': , 'PORT': , … -
How to fix "django.core.exceptions.ValidationError: ['Il valore "" ha un formato di data non valido. Deve essere nel formato AAAA-MM-GG.']"
**model.py ** class Customer(models.Model): n_tessera = models.CharField(max_length=200, null=True, default='ABC123') nome = models.CharField(max_length=200, null=False) cognome = models.CharField(max_length=200, null=False) email = models.CharField(max_length=200, null=True) tel = models.CharField(max_length=200, null=True) via = models.CharField(max_length=200, null=True) cap = models.IntegerField(null=True) provincia = models.CharField(max_length=2, null=True) comune = models.CharField(max_length=200, null=True) citta_nascita = models.CharField(max_length=200, null=True) data_nascita = models.DateField(blank=True, null=True) scadenza_certificato_medico = models.DateField(default='', null=False) importo_qa = models.FloatField(null=True, default=0) tipo_qa = models.CharField(choices=[('SR', 'SR'), ('SPC', 'SPC'), ('CF6.0', 'CF6.0'), ('CF6.0 Ridotte', 'CF6.0 Ridotte')], null=False, default='SR', max_length=20) note = models.CharField(max_length=200, null=True, default='--Nessuna nota--') attivo = models.BooleanField(default=True) def __str__(self): return self.nome + " " + self.cognome class Meta: verbose_name = "Cliente" verbose_name_plural = "Clienti" **views.py ** def new_customer(request): if request.method == 'POST': print(request.POST) form = CustomerForm(request.POST) print(form) if form.is_valid(): form.save() return redirect('lista_clienti') # Nome dell'URL della lista dei trainer else: print(form.errors) else: form = CustomerForm() return render(request, 'new_customer.html', {'form': form}) **forms.py ** class CustomerForm(forms.ModelForm): data_nascita = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Customer fields = ['nome', 'cognome', 'via', 'cap', 'provincia', 'comune', 'citta_nascita', 'data_nascita', 'attivo', 'tel', 'email', 'note'] testing: from crm_ff.models import Customer new_customer = Customer(nome='Mario', cognome='Rossi', via='Via Roma 1', cap='00100', provincia='RM', comune='Roma', citta_nascita='Roma', data_nascita='1990-01-01', attivo=True, tel='1234567890', email='mario.rossi@example.com', note='Nessuna nota') new_customer.save() Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode coro = func() ^^^^^^ File "", … -
Can anyone help me with this situation [closed]
Reference Image const library = (await(await fetch( ' ./indexData/theLibrary.json')) .json()) const uniquelD = (await(await fetch(• ./indexData/uniqueid .json')).json()) I was trying to load static files like this javascript file using django But can't figure out the source of error here, My editor shows no error and this file ran perfectly fine until i added it to django. Can you please point out what i am missing here -
Can't access media files in nginx
I have a problem that I can't access any of /media files on my development instance of nginx with django. I'm getting 404 every time I do requests to /media my nginx conf file server { listen 80; server_name _; server_tokens off; client_max_body_size 20M; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } location /api { try_files $uri @proxy_api; } location @proxy_api { proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://backend:8000; } location /media { root /home/user/backend/media/; } } docker-compose version: "3.8" services: # Database service database: container_name: adverity-transformer-challenge-database image: postgres:9.6-alpine environment: POSTGRES_DB: transformer POSTGRES_HOST_AUTH_METHOD: trust ports: - "5433:5432" restart: unless-stopped networks: - djangonetwork # Async tasks broker service redis: container_name: adverity-transformer-challenge-redis image: redis:6 ports: - "6379:6379" restart: unless-stopped # Async tasks worker celery: container_name: adverity-transformer-challenge-celery build: context: ./backend/ dockerfile: Dockerfile.development image: adverity-transformer-challenge-backend environment: BROKER_URL: redis://redis:6379 DATABASE_HOST: database DATABASE_USER: postgres DATABASE_NAME: transformer command: watchmedo auto-restart --pattern '*.py' --signal SIGINT --recursive -- celery -A transformer worker -l debug volumes: - ./backend/:/home/user/backend/:delegated # Main backend application backend: container_name: adverity-transformer-challenge-backend build: context: ./backend/ dockerfile: Dockerfile.development image: adverity-transformer-challenge-backend ports: - "8000:8000" environment: BROKER_URL: redis://redis:6379 DATABASE_HOST: database DATABASE_USER: postgres DATABASE_NAME: transformer volumes: - … -
Django its not printing on HTML
I am trying to understand why Django its not printing on my HTML page, the user db its printing just fine but my ticket db its not being printed, it actually creates the space to allocate the information, as its shown on the image, but it doesn't fill the information on it. views.py #The actual page def dashboard(request): ticket = Userdb.objects.filter(userid = request.user.id) context = {'ticket': ticket} return render(request,'dashboard/home.html', context) #Data in the ticket def ticketr(request): data = {} if request.method == 'POST': if request.POST.get('nomctt') and request.POST.get('tiposerv') and request.POST.get('areaserv') and request.POST.get('tickettext'): table = Userdb() table.nomctt = request.POST.get('nomctt') table.numctt = request.POST.get('numctt') table.tiposerv = request.POST.get('tiposerv') table.areaserv = request.POST.get('areaserv') table.tickettext = request.POST.get('tickettext') table.userid = request.user table.save() data['msg'] = 'Ticket registrado!' data['class'] = 'alert-success' return render(request,'dashboard/home.html', data) else: data['msg'] = 'Preencha todos os campos!' data['class'] = 'alert-danger' return render(request,'dashboard/ticket.html',data) home.html {% block content %} {% if request.user.is_authenticated %} <nav class="navbar"> <div class="navbar__container"> <a href="/" id="navbar__logo"><img src="{% static 'images/logo.png' %}" style="width:180px;height:100px;"></a> <div class="navbar__toggle" id="mobile-menu"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> <ul class="navbar__menu"> <ul class="navbar__menu"> <li class="navbar__item"> <a href="/" class="navbar__links"> {{ user.username }} </a> </li> <li class="navbar__btn"> <a href="/loginv" class="button"> Logar </a> </li> </ul> </div> </nav> <a href="/dashboard/ticket/">Abra um Ticket</a> </div> <br> <div class="container bootdey"> … -
Getting invalid name(s) given in select related
I am getting the error invalid field name(s) given in select_related: ‘author_set’. Choices are : first_name, last_name, city, state, country Below are my models: class Author(models.Model): first_name = models.CharField(null=True, blank=True, max_length=50) last_name = models.CharField(null=True, blank=True, max_length=50) city = models.CharField(null=True, blank=True, max_length=50) state = models.CharField(null=True, blank=True, max_length=50) country = models.CharField(null=True, blank=True, max_length=50) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(null=True, blank=True, max_length=50) narration = models.CharField(null=True, blank=True, max_length=200) released = models.DateField() The below command is raising the error authors = Author.objects.select_related(“author_set”) I have tried to use researched and don’t know why -
Change the table name of the Model in django admin
I want to change my django admin table name in django admin panel I want to change the Products name in the top of that table, for example I want to change PRODUCTS and ACCOUNTS names in the picture below: django admin panel side menu In the picture above I have Two model. first is the محصولات and the second one is the نظرات And also my app name is Products which is the shown in the table name. but I want to change this name. and if possible I want to change the other table names which is the "ACCOUNTS". I did change my model verbose_name and verbose_plural_name as you can saw, but I couldn't change the table name. -
Best way to import models from a bunch of different django projects
Basically I have a project that has a bunch of microservices and a number of databases across them. What I want is to create another service that I can run different scripts on that make some changes to the prod db. For example if there was a bug that messed up some records, I'd have to go in to the prod db and fix those records. What would be the best way to import all these models? I want to be able to do something like service_a.db.ModelA service_b.db.ModelB etc Or is there a package I can use to do this already instead of trying to build my own?