Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got "No Books matches the given query" error even though the object exist on Django
I got this problem where Django return "No Books matches the given query", even though the object exist in database. For context, I want to create an update page without relying the use of URL. First, here is my model : User = get_user_model() class Books(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=50) author = models.CharField( max_length=40, ) author_nationality = models.CharField(max_length=20, default='Japanese') author_medsos = models.CharField(max_length=30, default='None') book_type = models.CharField( max_length=10, null=True, choices=BOOKS_TYPES ) tl_type = models.CharField( max_length=20, null=True, choices=TRANSLATION_BY ) series_status = models.CharField( max_length=20, choices=SERIES_STATUS, default=ONG ) source = models.CharField(max_length=100) # source can refer to downloage page, example = https://www.justlightnovels.com/2023/03/hollow-regalia/ reading_status = models.CharField( max_length=20, choices=READING_STATUS, default=TOR ) current_progress = models.CharField( # For tracking how many chapter have been read max_length=30, null=True ) cover = models.FileField(upload_to='cover/', default='cover/default.png') genre = models.CharField(max_length=40, null=True) class Review(models.Model): books = models.ForeignKey('Books', on_delete=models.CASCADE, null=True) volume = models.IntegerField() review = models.TextField() Before the user get to the update page, they first have to visit /library page, {% for book in user_books %} <div class='lib-item'> <form method='POST' action="{% url 'core:update_library' %}"> {% csrf_token %} <input type='hidden' name='book_id' value='{{ book.id }}'> <button type='submit'> <img src={{ book.cover.url }} width='185'> <span> {{ book.title }} </span> </button> </form> </div> {% endfor … -
In Django Rest Framework how to make a function base view roll back every change made if somethings fails
I have a api endpoint that the user will send a key pair of file_field: File in the multipart content type. The function need to update every document and create a history about the change. Then It should complete the session that the user used to do this change. If a document couldn't be updated or a historic couldn't be created all the operations and changes should roll back how to archive this. This is my current function base view: @transaction.atomic @api_view(['POST']) @parser_classes([JSONParser, MultiPartParser]) @permission_classes([HasSpecialSessionPermission]) def update_documents(request): user = request.user special_session = SpecialSessionConfiguration.objects.filter(user=user, completed=False).first() lot = DefaultLotModel.objects.filter(user=user, call__active=True).first() for key, uploaded_file in request.FILES.items(): try: validate_file_size(uploaded_file) if key != 'financial_form' and key != 'power_point': validate_file_extension(uploaded_file) except ValidationError as e: return Response({'message': str(e)}, status=status.HTTP_400_BAD_REQUEST) if special_session.special_session_fields.filter( field_name=get_field_number(SPECIAL_SESSION_FIELD, key)).exists(): if hasattr(lot, key): current_file = getattr(lot, key) if current_file: setattr(lot, key, uploaded_file) LotDocumentHistory.objects.create( lot=lot, old_file=current_file, field_name=key, ) setattr(lot, key, uploaded_file) lot.save() else: for child_field in ['first_lots', 'second_lots', 'third_lots']: child_lot = getattr(lot, child_field, None) if child_lot and hasattr(child_lot, key): current_file = getattr(child_lot, key) if current_file: LotDocumentHistory.objects.create( lot=lot, old_file=current_file, field_name=key, ) setattr(child_lot, key, uploaded_file) child_lot.save() elif special_session.extra_files: try: data = {'name': key, 'file': uploaded_file, 'lot': lot.pk} serializer = ExtraFileSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() except ValidationError as ve: error_dict … -
Difficulty Using gettext_lazy in Django 4 Settings with django-stubs, Resulting in Import Cycle and mypy Type Inference Error
Problem: Mypy Error: The mypy error encountered is as follows: error:Import cycle from Django settings module prevents type inference for 'LANGUAGES' [misc] I'm encountering challenges with the usage of gettext_lazy in Django 4 settings while utilizing django-stubs. The recent update in Django 4 brought changes to the typing of gettext_lazy, where the old return type was str, and the new type is _StrPromise. The issue arises from the fact that _StrPromise is defined in "django-stubs/utils/functional.pyi," and within this file, there is also an import of django.db.model which imports settings. This creates a circular import. current module-version: typing mypy = "1.7" django-stubs = "4.2.7" Django dependencies Django = "4.2.10" Seeking advice on a cleaner and more sustainable solution to the circular import issue and mypy error in the context of Django 4 settings with the updated gettext_lazy typing. Any insights or alternative approaches would be greatly appreciated. possible Solutions: Several solutions have been considered, but none of them are ideal: Disable Mypy Typing for Settings: Disabling Mypy typing for settings is a workaround, but it might compromise the benefits of static typing. Remove gettext_lazy from Settings: Another option is to remove gettext_lazy from settings. However, this contradicts the current recommendations in … -
Django - CSRF Failed: CSRF cookie not set
I want to create a API that has login / logout / signup / edit etc, but when I try it in Postman i get the error: CSRF Failed: CSRF cookie not set I've noticed that if the user is not logged in, The API works fine but after the login I get the CSRF error when using any url from it ( /logout/, /login/ etc) views.py `@csrf_exempt @api_view(['POST']) def login_user(request): if request.user.is_authenticated: return JsonResponse({"detail": "User is logged in!"}) body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) nickname = body['nickname'] password = body['password'] user = authenticate(nickname=nickname, password=password) if user is not None: login(request, user) logout(request) return JsonResponse({"response": "Login success!"}) else: return JsonResponse({"error": "Nickname or Password are incorrect!"})` settings.py `MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]` I've seen that I should get a CSRF token in the cookies section in Postman, but the only thing i get is a sessionId -
why this error coming actually there is issue related to migrations so i tried to delete the all migrations files then
return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.ProgrammingError: relation "auth_group" does not exist why it is showing like that can you explain how actually migrations works i am expecting to schema to migrate in database -
Circular Import - Django
I can't see where the circular import is django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'Reciept.urls' from 'Reciept\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import project level urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('PPMS/', include('PPMS.urls')), path('Dispute/',include('Dispute.urls')), path('Reciept/', include('Reciept.urls')) ] urls.py from django.urls import path from .views import Disputeindex app_name='Dispute' urlpatterns = [ path('',Disputeindex, name='Disputeindex') ] View.py from django.shortcuts import render def Recipetindex(request): return render(request, 'Reciept/index.html') -
Why does Django order by column number instead of column name?
I have this Django ORM code: queryset.filter(filters).annotate(rank=SearchRank(vectors, search_query)).order_by('-rank').distinct() and Django transforms this code into that sql: SELECT DISTINCT "model_1"."id", ... ... ... ts_rank( "model_2"."search_vector", phraseto_tsquery(query) ) AS "rank" FROM "model_1" INNER JOIN "model_2" ON ( "model_1"."id" = "model_2"."case_id" ) WHERE ( "model_2"."search_vector" @@ ( phraseto_tsquery(query) ) ) ORDER BY 41 ASC I cant understand why Django use 41(its a number of annotated rank column) instead of column name and i cant find any Django docs that describe this logic. Django version: 5.0.2 -
Celery Task Fails with "Object Does Not Exist" Error Despite Using Auto-Commit in Django
In my Django application, I've encountered a rare issue where a Celery task, invoked via apply_async immediately after creating an object in a model's save method, failed because it could not find the newly created object. This issue has occurred only once, making it particularly puzzling given Django's auto-commit mode, which should commit the new object to the database immediately. Below is a simplified version of the code where the issue appeared: from django.db import models from myapp.tasks import process_new_object class MyModel(models.Model): .... class AnotherModel(models.Model): .... def save(self, *args, **kwargs): new_obj = MyModel.objects.create(name="Newly Created Object") process_new_object.apply_async(args=[new_obj.pk], countdown=5) return super().save(*args, **kwargs) @shared_task def process_new_object(obj_id): try: obj = MyModel.objects.get(pk=obj_id) ... except MyModel.DoesNotExist: pass what might be potential causes for the Celery task to sometimes fail to find the newly created object, despite the delay and Django's auto-commit? -
Docker container restarting without producing logs
I'm encountering an issue with a Docker container where it keeps restarting without producing any logs. Here are the details of my setup: I have a Docker Compose configuration with two services: profiles and postgres. The profiles service is built from a custom Dockerfile and runs a Python application. The postgres service uses the official PostgreSQL Docker image. Both services are defined in the same docker-compose.yml file. The profiles service container (profile-profiles-1) keeps restarting, but when I try to view its logs using docker logs profile-profiles-1, there is no output. Here is my docker-compose.yml: x-variables: &variables ENV_STAGE: local services: profiles: build: context: . dockerfile: ./compose/dev/web/Dockerfile volumes: - ./web/:/usr/src/web/ ports: - "8000:8000" environment: <<: *variables env_file: - compose/dev/env/.env - compose/dev/env/.db.env - compose/dev/env/.data.env depends_on: - postgres restart: unless-stopped postgres: image: postgres:latest restart: always volumes: # - postgres-data:/var/lib/postgresql/data # - compose/dev/db/pg.conf:/etc/postgresql/postgresql.conf - ./compose/dev/db/pg.conf:/etc/postgresql/postgresql.conf environment: - POSTGRES_USER=test - POSTGRES_PASSWORD=password - POSTGRES_DB=test - PGDATA=/var/lib/postgresql/data ports: - 5432:5432 # command: # - config_file=/etc/postgresql/postgresql.conf command: postgres -c config_file=/etc/postgresql/postgresql.conf env_file: - compose/dev/env/.db.env volumes: postgres-data: This is my Dockerfile for the application: # pull official base image FROM python:3.9-alpine ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ LANG=C.UTF-8 \ HOME=/usr/src/web WORKDIR $HOME ARG GID=1000 ARG UID=1000 ARG USER=ubuntu # install dependencies RUN … -
How to set dict key as dynamic field name to add value m2m fields in Django
I want to set the m2m field name from the dictionary key dynamically so that I don't have to type each field name separately. Any help would be much appreciated. instance = ProductAttributes.objects.create(device_type=1, manufacturer=2, created_by=request.user) device_dict = { 'watch_series': WatchSeries.objects.get(series=mergedict['watch_series']), 'watch_size': WatchSize.objects.get(size=mergedict['watch_size']), 'color': Color.objects.get(id=mergedict['color']), 'band_color': BandColor.objects.get(color=mergedict['band_color']), 'watch_connectivity': 1 if mergedict['is_gps'] == True else 2 } This is how I'm trying to add m2m field name after instance for key, val in device_dict.items(): instance._meta.get_field(key).add(val) I'm getting this error: AttributeError: 'ManyToManyField' object has no attribute 'add' -
How to create Tree Survey in Django?
I need help You need to do a tree survey in jang Type : Question: Who do you work for? Answer options : Programmer, Welder If the user answers as a Programmer, they are asked questions about this profession If a welder answers, he is asked questions about this profession Well, and so on into the depths That is, the user's answers affect the next question But you also need to create a custom admin panel to add, edit and establish links between these issues I just can't figure out how to optimally configure the models so that the tree survey is normally implemented. Specifically, I do not understand how to store this connection, how to store it correctly and conveniently in models, and how to implement them so that quickly, beautifully and simply you can specify these links between questions and answers in the admin panel -
How can I automatically assign the current user as the author when creating a post?
How can I automatically assign the current user as the author when creating a post? forms: from django import forms from publication.models import Userpublication class PostForm(forms.ModelForm): content = forms.CharField(label='',widget=forms.Textarea(attrs={'class': 'content_toggle app-textarea', 'utofocus': 'true', 'maxlength': '250', 'placeholder': 'hello', 'required': True})) class Meta: model = Userpublication fields = ['content', 'author'] labels = { 'Content': False, } views: def create_post(request): if request.method == 'POST': form = PostForm(request.POST, initial={'author': request.user}) if form.is_valid(): form.save() return redirect('home') else: form = PostForm(initial={'author': request.user}) post_lists = Userpublication.objects.all() context = { 'form': form, 'post_lists': post_lists, } return render(request, 'twippie/home.html', context) enter image description here This is how it works. But as soon as I remove fields 'author' from the form, but 'content' remains, the following error appears: File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.IntegrityError: NOT NULL constraint failed: publication_userpubl ication.author_id the browser shows this error: IntegrityError at /feed/ NOT NULL constraint failed: publication_userpublication.author_id What could I have missed or overlooked? model if needed: from django.db import models from autoslug import AutoSlugField from django.urls import reverse from django.contrib.auth.models import User from django.conf import settings class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=1).order_by('-time_create') class Userpublication(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = AutoSlugField(max_length=255, unique=True, populate_from='content') content = models.TextField('', blank=True) … -
I am unable to use Django Filter for Related Foreignkey in Django model
I am unable to filter reverse Foreign key field in my filter. Here is My Main Model: class VendorService(models.Model): """ Class for creating vendor services table models. """ vendor_id = models.ForeignKey(CustomUser, null=False, blank=False, on_delete=models.CASCADE) service_id = models.ForeignKey(Service, null=False, blank=False, on_delete=models.CASCADE) business_name = models.TextField(null=True, blank=False) business_image = models.URLField(max_length=500, null=True, blank=False) working_since = models.TextField(null=True, blank=False) ... And Here is my second Model: class ServiceSubTypeDetail(models.Model): ''' Additional Service Details ''' title = models.CharField(max_length=255, null=True, blank=True) service_subtype = models.CharField(max_length=255, null=True, blank=True) service = models.ForeignKey(VendorService, related_name='subtypes', on_delete=models.CASCADE, null=True, blank=True) actual_price = models.FloatField(null=True, blank=True) ... My second model uses First Model as foreignkey And Here is my Filter Class using django-filter library: class ServiceFilter(filters.FilterSet): service_type = filters.CharFilter(field_name="service_id__service_type", lookup_expr='icontains') city = filters.CharFilter(field_name="city", lookup_expr='icontains') price = filters.RangeFilter(field_name="vendorpricing__discounted_price") subscription = filters.CharFilter(field_name="vendorplan__subscription_type", lookup_expr='iexact') property_type = filters.CharFilter(field_name="subtypes__title", lookup_expr='icontains') def __init__(self, *args, **kwargs): super(ServiceFilter, self).__init__(*args, **kwargs) # Dynamically add the price range filter based on the service_type service_type = self.data.get('service_type', None) if service_type == 'Venues': self.filters['price'] = filters.RangeFilter(field_name="venue_discounted_price_per_event") else: self.filters['price'] = filters.RangeFilter(field_name="vendorpricing__discounted_price") class Meta: model = VendorService fields = ['service_id__service_type', 'city', "vendorpricing__discounted_price", "venue_discounted_price_per_event", "subtypes__title"] all other filters are working properly, but property_type dosnt work at all. I tried using method as well. please help..!! -
Change style for filteredselectmultiple widget tooltip text
I have used help help-tooltip help-icon in that I want add bootstrap tooltip styles. But not able to do? For reference I have attached screenshot. Provide solution according to that.in following image that question mark shows tooltip text and i want add bootstrap tooltip style in that text . enter image description here Add bootstrap tooltip style for tooltip -
Django Media files is not displaying when debug=false on production in Render
I currently have two kind of files static files and media files.The static files contain my css,js and other static content. The media files contain stuff that the user uploads.The static folder is right next to the media folder.Now on my deployed machine. If I set the DEBUG = False my static files are presented just fine however my media content is never displayed `This my settings.py code were debug=false and included the code for the static but my media files is not displaying in the render hosting platform .I want to display my media files on production server when debug=False ` DEBUG = False ALLOWED_HOSTS = ["*"] This my static code but i get static files and it is displaying in the production .But the media files are not displaying in the production server is there any way to solve this problem STATIC_URL = '/static/' STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')] STATIC_ROOT=os.path.join(BASE_DIR,'assets') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") Im using Render hosting platform for the deployment of the application -
A p2p secure chat application need more ressources to establish the work
I want to do this so called p2p chat app project, and I need some clear guidance and ressources where I can find some good p2p documentation or courses so I can digest this notion, I'm not so familiar woth it even though I have some basic knowledge about it I hope u suggest some great ressources where I can find a p2p based book or documentation -
Referencing model in another model is displaying id and object instead of name. How can I fix this?
I have made two models. One of which references another. Here is my first model: Here is my second model.py. (I know it is weird). This is what I get. I have tried using: def __str__(self): return self.employee Abd I have tried using: def __str__(self): return self.employee.employee_name I am not sure what I am doing wrong or how to fix this. I have also set employee = models.ForeignKey(Employee, on_delete=CASCADE) to see if that would make a difference. I knew it wouldn't. >:( I honestly have never referenced another Model into another one before so I am a newbie at this. Any suggestions? Any help would be greatly appreciated. -
Django: Refresh captcha form
I have a registration form with multiple fields and captcha form. I'm new to django-simple-captcha, and I made a refresh button to only refresh the captcha alone. Is it possible to do that? How should I write the function? register.html <div><input type="text" name="studentId"></div> <div><input type="text" name="Name"></div> ... <div>{{ form.captcha }}</div> <button type="button" class="btn">Refresh</button> // refresh captcha <button type="submit" class="btn btn-primary">Submit</button> forms.py from captcha.fields import CaptchaField class MyForm(forms.Form): captcha = CaptchaField() views.py from .forms import MyForm def preRegistration(request): form = MyForm(request.POST) if request.method == 'GET': return render(request, 'registration_form.html', {"form": form}) if request.method == 'POST': studentId = request.POST.get('studentId') ... if form.is_valid(): Applicant.objects.create(studentID=studentID, ...) return render(request, 'login.html') else: messages.error(request, 'Wrong Captcha!') return render(request, 'registration.html', {"form": form}) def refreshCaptcha(): ... -
In container Podman with systemd cgroups v2, i get error: Error: runc create failed: unable to start container process: error during container init
In Django i'm using Podman as a subprocess, i'm trying to create a container to isolate a code that will be returned as a string. My system (ubuntu) uses systemd as its cgroups manager and is using cgroups v2 (cgroupVersion: v2), i.e. simply systemd with cgroups v2. I checked the configuration and I'm exactly using systemd with cgroups. I'm also using the latest updated version of Podman and have also tried uninstalling and updating. But when I open the app in Django, I get the error: Error: runc create failed: unable to start container process: error during container init: error setting cgroup config for procHooks process: openat2 /sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/user .slice/libpod-a7fc0b085c40c19042d082.scope/cpu.max: no such file or directory: OCI runtime attempted to invoke a command that was not found Some of my code in Django is: podman_process = subprocess.Popen(['podman', 'run', #'--cgroup-manager=systemd', #'--cgroup-manager=cgroupfs', '-the', '--rm', '-to', 'stdin', '-to', 'stdout', '--user', 'nobody:users', '-m', '256m', '--cpus', '0.5', 'alpine'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) I've tried both using '--cgroup-manager=cgroupfs' and also '--cgroup-manager=systemd', but I still get the same error. How can I solve the problem? -
How would you use a website builder that operates with your Django backend?
I'm working on this app that basically manages users and projects for my company, and then potentially sell it to other companies wishing to do the same thing. I'm thinking that I'll use Django + Python in the backend, and I really want to use a website builder to design the UI. The reason for using a website builder is that I'd like to speed the development up a little bit. I'm newer to coding, so the HTML hurdle seems like it'll be a lot to manage. I'm good at designing websites with my background in design. I'm trying to avoid manual HTML entry since I'm already climbing a steep hill learning app structuring, Django and Python at the same time (not to mention JSON and whatever else I'll need). My question is how could I use a Wix website that has been built visually, with my Django backend? I'd use Django to process the information, sort, filter, etc. Then I'd use the Wix site to interact with the information. Any tools or tips would help. Like I said, I'm a beginner and the learning curve is huge. Thanks! I haven't really tried anything to be honest. I don't even … -
How do I serve specific and/or arbitrary static files from Django?
I'm building an extension to a SASS product. This extension requires: The / directory to contain index.html The / directory to contain config.json The / directory to contain customActivity.js The / directory to contain icon.png I'd like to keep my config.json and customActivity.js files in my projects static directory, and my icon.png file in the media directory. My index.html file should be via a template. So far, my urls.py file looks like: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] and my views.py looks like: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def index(request): return HttpResponse("some stuff") // just an example How do write a url paths that will direct / to the index view, but /somefile.someextension to either the static or media directories? -
Cannot access local variable 'user' where it is not associated with a value
so, I'm trying to make a function in my django project that sends a confirmation key through email for the user so I tried to do this: views.py def createuser(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): return redirect('confirm-email') else: messages.error(request,'An error occured during your registration') context = {'form':form} return render(request, 'signup.html', context) def confirmemail(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) page = 'confirm-email' subject = 'Confirm your email' # Erro from_email = 'adryanftaborda@gmail.com' email = request.user.email recipient_list = email return send_mail(subject, 'Use %s to confirm your email.' % request.user.confirmation_key, from_email, recipient_list) user.confirm_email(user.confirmation_key) if user.is_confirmed == True: user = form.save(commit=False) user.username = request.user.username.lower() user.save() login(request,user) return redirect('home') context = {'form':form} return render(request, 'emailconfirm.html', context) models.py from django.db import models from django.contrib.auth.models import AbstractUser from simple_email_confirmation.models import SimpleEmailConfirmationUserMixin class User(SimpleEmailConfirmationUserMixin, AbstractUser): name = models.CharField(max_length = 50) username = models.CharField(max_length = 50, null=True) email = models.EmailField(unique=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','username'] and I've got this error: UnboundLocalError at /confirm-email/ cannot access local variable 'user' where it is not associated with a value the error in this line: user.confirm_email(user.confirmation_key) I tried to add requests.user everywhere, but it didn't work. I have an … -
How do I configure a Django model against an agreggating postgres view?
Django 4.2.9, postgres 15.2 (server), Python 3.10 I have a view that does it's own aggregation and I want to map it into a Django Model. CREATE VIEW report_usage AS SELECT t.team_id, t.display_name, t.report_allowance", count(r.*) as "monthly_usage" FROM report r LEFT JOIN teams t ON t.team_id = r.team_id WHERE date_trunc('month', r.response_ts) = date_trunc('month', now()) GROUP BY t.team_id, t.display_name, report_allowance; This view works as promised; it counts the number of reports run by each team. Now that view is also used in other places so I want to simply incorporate it into a Django model for use in my app. So I built a Django Model around it: class ReportUsage(models.Model): class Meta: managed = False verbose_name_plural = 'Report Usage' db_table = 'report_usage' # Not really a key for this table.. just needed by django team_id = models.IntegerField(primary_key=True, db_column='team_id') display_name = models.CharField(db_column='display_name') report_allowance = models.IntegerField(db_column='report_allowance') report_usage = models.IntegerField(db_column='count') However It is not working: django.db.utils.ProgrammingError: column "report_usage.team_id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "report_usage"."team_id", "report_usage"."display_n... Which makes a total of zero sense to me. At a guess, Django saw the count() function and decided to take over. I have read everything I … -
Django - cPanel environment variable not working
While setting up a Django app in cPanel, I can assign environment variables. However, I am having trouble using them. For instance, I made an assignment as seen in the picture. But when I use it in my Django application as os.environ.get('EMAIL_PASSWORD_V'), It doesn't recognize the variable. How can i fix that? I know there are other methods to do this but if this method is can be used, I wonder how can it. Thank you already Django_Variable_in_cPanel -
Django DRF Viewset URL Reversing Issue - NoReverseMatch for 'orderitem-list
I'm encountering a perplexing issue while working with Django and the Django Rest Framework (DRF). Specifically, I have two viewsets, namely OrderViewSet and OrderItemViewSet, both registered with a DefaultRouter. The problem arises when attempting to perform URL reversing for the 'orderitem-list' endpoint, where I consistently encounter a NoReverseMatch error. Surprisingly, this issue is not present when reversing the URL for 'order-list'. urls.py `router = DefaultRouter() router.register(r"", OrderViewSet, basename="order") router.register(r"^(?P<order_id>\d+)/order-items", OrderItemViewSet, basename="orderitem") urlpatterns = [ path("", include(router.urls)), ]` test_orders.py `def test_create_order_for_anonymous_user(self, client, address): url = reverse("order-list") response = client.post(url, {}) assert response.status_code == 403 assert Order.objects.count() == 0` This test code works successfully `def test_create_order_item_for_anonymous_user(self, client, order): url = reverse("orderitem-list", kwargs={"order_id": order.id}) response = client.post(url, {}) assert response.status_code == 403 assert OrderItem.objects.count() == 0` The error message is: django.urls.exceptions.NoReverseMatch: Reverse for 'orderitem-list' with keyword arguments '{'order_id': 1}' not found. Any ideas on why this might be happening? The reverse for 'order-list' works without any issues.