Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'views' from 'birds_eye'
I've recently started to learn how to build django projects with multiple apps. I have learnt that by using from . import views I can import the different views from the current directory that I am in. However, when using this method, the prompt would give me an error saying: ImportError: cannot import name 'views' from 'birds_eye' The following is my current directory tree of my django project: birds_eye |- accounts (app folder) |- birds_eye (actual project folder) |- clubs (app folder) |- events (app folder) |- posts (app folder) |- static |- templates And this is the actual code of what is happening: birds_eye |- birds_eye (actual project folder) |- urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.HomePage.as_view(), name="home"), path("admin/", admin.site.urls), path("test/", views.TestPage.as_view(), name="test"), path("thanks", views.ThanksPage.as_view(), name="thanks"), path('accounts/', include("accounts.urls", namespace="accounts")), path("accounts/", include("django.contrib.auth.urls")), # Events --> Calendar, Posts --> Feed | Expected to finish later on. Uncomment when done. # path("posts/", include("posts.urls", namespace="posts")), # path("events/", include("events.urls", namespace="events")), path("clubs/", include("clubs.urls", namespace="clubs")), path('surveys', include('djf_surveys.urls')), ] Is there any solution to this? (I can edit the question in order to provide more resources from my project) -
Django media returns the 404 NOT FOUND when I try to GET media using Axios
I'm trying to get media from django but I get this 404 NOT FOUND error message in the console xhr.js?1a5c:244 GET http://127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D 404 (Not Found) My product/urls.py code is this from product import views urlpatterns = [ path('latest-products/', views.LatestProductsList.as_view()), path('products/<slug:category_slug>/<slug:product_slug>/', views.ProductDetail.as_view()), ] the first path works perfectly but the second one shows this error GET http://127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D 404 (Not Found) -
Django rest framework browsable api show null for manytomany field
I am going to implement api for blog app using DRF ModelViewSet: This is how i implemented: views.py from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.response import Response from .serializers import PostSerializer, CategorySerializer from ...models import Post, Category from rest_framework import viewsets from rest_framework.decorators import action from .permissions import IsOwnerOrReadOnly from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter, OrderingFilter from .paginations import DefaultPagination class PostModelViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] serializer_class = PostSerializer queryset = Post.objects.filter(ok_to_publish=True) filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = { "category": ["exact", "in"], "author": ["exact"], "ok_to_publish": ["exact"], } search_fields = ["title", "content"] ordering_fields = ["publish_date"] pagination_class = DefaultPagination @action(detail=False, methods=["get"]) def get_ok(self, request): return Response({"detail": "ok"}) class CategoryModelViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly] serializer_class = CategorySerializer queryset = Category.objects.all() serializers.py from rest_framework import serializers from ...models import Post, Category from accounts.models import Profile class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["id", "name"] class PostSerializer(serializers.ModelSerializer): summary = serializers.CharField(source="get_summary", read_only=True) relative_url = serializers.CharField(source="get_relative_api_url", read_only=True) absolute_url = serializers.SerializerMethodField(method_name="get_absolute_api_url") category = serializers.SlugRelatedField( queryset=Category.objects.all(), slug_field="name", many=True ) class Meta: model = Post fields = [ "id", "title", "author", "image", "content", "summary", "category", "relative_url", "absolute_url", "ok_to_publish", "login_required", "n_views", "created_at", "publish_date", ] read_only_fields = ["author"] def get_absolute_api_url(self, obj): # It is not a standard and correct … -
Can't serve Django static files with NGINX
I'm trying to deploy a Django and React website using gunicorn, nginx and docker. I can't get nginx to read my static files for example the django admin panel. I already ran python manage.py collecstatic and the files are in recommendations-be/backend/static Here is the docker-compose.yml file: version: '3' services: backend: build: context: ./recommendations-be command: gunicorn backend.wsgi:application --bind 0.0.0.0:8000 --timeout 0 ports: - "8000:8000" volumes: - static:/django/backend/static frontend: build: context: ./recommendations-fe volumes: - react_build:/react/build nginx: image: nginx:latest ports: - "80:8080" volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - react_build:/var/www/react - static:/django/backend/static depends_on: - backend - frontend volumes: static: react_build: Here is my nginx conf file: upstream api { server backend:8000; } server { listen 8080; location / { root /var/www/react; } location /api/ { proxy_pass http://api; proxy_set_header Host $http_host; } location /static/ { alias /django/backend/static; } } Here's the Dockerfile in backend directory recommendations-be: FROM python:3.10.8-slim-buster ENV PYTHONUNBUFFERED 1 WORKDIR /django COPY requirements.txt requirements.txt RUN pip install --upgrade pip --no-cache-dir RUN pip install -r requirements.txt --no-cache-dir COPY . . And the django settings.py: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "backend", "static") Here is the file structure in my project: file structure -
Django needs to restart server for changing data in template
The goal is to make texts in static templates like "about us" page dynamic with a model so that it can be edited easily later on. My model is as below: class SiteData(models.Model): data_set_name = models.CharField( max_length=200, blank=False, null=False, default="نام مجموعه داده" ) main_page_english_info = models.TextField( verbose_name="مقدمه انگلیسی", blank=True, null=True ) main_page_persian_info = models.TextField( verbose_name="مقدمه فارسی", blank=True, null=True ) my view is as below: class HomePageView(ListView): model = SiteData template_name: str = "core/index.html" site_data = SiteData.objects.get(pk=1) context_vars = { "site_data": site_data, } def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) context.update(HomePageView.context_vars) return context and my template: <p class="mt-3 text-justified text-english fw-semibold nm-text-color" style="direction: ltr; ">{{ site_data.main_page_english_info }}</p> <p class="mt-3 text-justified nm-text-color">{{ site_data.main_page_persian_info }}</p> My problem with this method is two main issues: This method works and if I change data from admin panel, it will be applyed, BUT ONLY if I restarted development server! (ctrl + c and py manage.py runserver). Where is my problem? How can I solve this issue? My model itself isn't so dynamic itself, and this is why I'm also trying another method which I have other problems in that, and I've asked another question here. Now, I'll appreciate an answer to either of these question! -
How to rename default django model field after creation in admin panel
I am making a simple application in Django, where I want my admins to be able to go into the admin panel and create a Level object class Level(models.Model): content = models.CharField(max_length = 200) ^^ This is my simple layout for the model, only admins can create this. However, when my admins create the Level object, it shows up like this: How it shows up in admin panel I don't want this, and I want that to be replaced with the string content, which is a field in my Level model So instead of looking like above, I want it to just contain the context. How can I do this? -
Django Extend Default User Model
I am searching for a way to easily add more character fields to the default user model from Django. This question has been asked, but I couldn't find an up to date answer. I let Django handle all the authenticating and logging in, so I don't want to create a custom user model, any ideas? -
From SQL to Django without raw method
I'm trying to convert SQL Query to Django. I'm new to Django and I find it hard to do simple things, here is the SQL query I'm trying to run with Django : SELECT * FROM balance_hold bh1 WHERE bh1.account_balance = X and bh1.hold_id in ( SELECT hold_id FROM balance_hold bh2 WHERE bh2.transaction_id = bh1.transaction_id and bh2.account_balance = X and ( bh2.release_time = null and hold_type >= (select * from balance_hold bh3 where bh3.transaction_id = bh2.transaction_id and bh3.account_balance = X and bh3.release_time = null) ) or ( bh2.release_time != null and bh2.release_time >= (select release_time from balance_hold bh3 where bh3.transaction_id = bh2.transaction_id and bh3.account_balance = X and bh3.release_time != null) )) ) how do I run this with Django (without using RAW method!)? -
Download a file created using python-docx from Django DRF?
I am trying to create a file using python-docx and download it using DRF/Django. I have tried almost all the answers to questions similar to mine. I get errors. Api.py class CreateDocx(viewsets.ModelViewSet): queryset = BooksModel.objects.all() serializer_class = BooksSerializer # serializer_class = BooksSerializer # permission_classes = [ # permissions.AllowAny # ] # def get(self): def download(self, request): print('creating file') document = file_create() # Function is returning a Document from python-docx, see below response = FileResponse(document, content_type='application/msword') # response['Content-Length'] = instance.file.size response['Content-Disposition'] = 'attachment; filename="TEST.docx"' return response file_create function: def file_create(): document = Document() docx_title = "TEST_DOCUMENT.docx" # Get the required info queryset = BooksModel.objects.all() # Place queries in document for query in queryset.values(): print(query) table = document.add_table(rows=1, cols=1) pic_cel = table.rows[0].cells[0].paragraphs[0] run = pic_cel.add_run() run.add_picture("/Users/xxx/Downloads/1.jpg", width=Mm(90), height=Mm(45)) print('added picture') return document urls.py from rest_framework import routers from .api import CreateDocx router = routers.DefaultRouter() router.register('api/download', CreateDocx, 'download-doc') urlpatterns = router.urls When I make a call to api/download/ I get a json reponse. I can't figure out what I am doing wrong because it seems download function inside the CreateDocx is not getting called whatsoever. I tried removing the serializer_class and queryset before the function but that results in errors. Such as: 'CreateDocx' … -
How to define default_search_fields in StretchIndex for Object type
I am trying to apply search for some of the child attributes of an Object in elastic search StretchIndex. The base attribute is defined in the below manner. primary_occupied_property = elasticsearch_dsl.Object( source='get_primary_occupied_property', properties=PROPERTY_MAPPING_PROPERTIES, dynamic=False, enabled=True, ) PROPERTY_MAPPING_PROPERTIES is defined as below. PROPERTY_MAPPING_PROPERTIES = { 'building': elasticsearch_dsl.Object(properties=BUILDING_MAPPING_PROPERTIES) } BUILDING_MAPPING_PROPERTIES is defined as below. 'city': elasticsearch_dsl.Keyword( fields={ 'standard': elasticsearch_dsl.Text(analyzer='standard'), 'autocomplete': elasticsearch_dsl.Text(analyzer=autocomplete_analyzer) }), 'state': elasticsearch_dsl.Keyword( fields={ 'standard': elasticsearch_dsl.Text(analyzer='standard'), 'autocomplete': elasticsearch_dsl.Text(analyzer=autocomplete_analyzer) }), On checking the index, we receive the below data. "primary_occupied_property": { "dynamic": "false", "properties": { "building": { "properties": { "address": { "type": "keyword" }, "city": { "type": "keyword", "fields": { "autocomplete": { "type": "text", "analyzer": "autocomplete_analyzer" }, "standard": { "type": "text", "analyzer": "standard" } } }, } } The default_search_fields are defined as - default_search_fields = [ 'primary_occupied_property.building.city.standard', 'primary_occupied_property.building.state.standard', 'primary_occupied_property.building.city.autocomplete', 'primary_occupied_property.building.state.autocomplete', ] However when I am executing the API, the search with specific city or state is not working. Please suggest. -
Django doesn't show images after adding multiple environments
I'm trying to add local and production environments to my Django project. So instead of one settings.py file, I created a settings directory and in that directory, added 3 settings files: base.py, local.py, and pro.py settings (directory) base.py (the new name for settings.py) local.py (inherits from base.py with some parameter overrides) pro.py (inherits from base.py with some parameter overrides) In the base.py file, I updated the BASE_DIR parameter to point to the parent folder of the current file. previous BASE_DIR: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) new BASE_DIR: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath( os.path.join(__file__, os.pardir)))) I didn't change static and media root parameters (in base.py): STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') However, after the change, my images don't show up anymore. What am I doing wrong? -
send variables or messages to page while script is doing tasks (django 4)
I'm doing some python script with django, and I when the user submit a file, I process the file and do tons of tasks, it can last a few minutes. While the user is waiting, I got a loading screen in js, and I print in console what's happening. But I would like to print it in the page, on the loading screen, is there a simple way to do this? my model looks like that models.py def main(): #all the long stuff & logic and my view : views.py def upload(request): #some other stuff MyModel.main() return render(request, 'frontend/upload.html',{ 'form':form, } ) It can be frustrating for the user (and for me) to wait and not know what's going on, I'd like to use my page as I use the console with print, because I'm not over with the stuff to do and I guess it could last some long minutes. -
error while using django_scopes : 'A scope on dimension(s) tenant needs to be active for this query.'
I am using django_scopes module to integrate tenancy across all get views in my django app. As per the readme doc in the repo: https://github.com/raphaelm/django-scopes it says: You probably already have a middleware that determines the site (or tenant, in general) for every request based on URL or logged in user, and you can easily use it there to just automatically wrap it around all your tenant-specific views. Accordingly, I have setup my middleware : class TenantScoper: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): with scope(tenant='xyz'): response = self.get_response(request) return response However, for model view set, when i bring up the server i get an error: django_scopes.exceptions.ScopeError: A scope on dimension(s) tenant needs to be active for this query. class TenantFeatureViewSet(viewsets.ModelViewSet): serializer_class = TenantFeatureSerializer queryset = TenantFeature.objects.all() Although it works perfectly for custom get view: class TenantFeatureView(APIView): def get(self, request): data = TenantFeature.objects.all() Error seems to originate when the line TenantFeature.objects.all() gets executed during server initialisation itself, Is there any workaround for this? -
How to reverse a filter class in Python/Django?
I needed to filter models instances with custom function, and using Post.objects.filter(func) didnt help, I got a type error cause "object is not iterable, so I went with def filter_posts(x): if x.author in followed_author_list: return True else: return False posts = filter(filter_posts, Post.objects.all()) return render(request, 'main.html', {'posts':posts }) And it worked, but now I cant reverse the list, cause I want to order it so newest will be last. If I use list() on it, then posts stop appearing on my website at all, cause I assume its not a different type?.. Question is, how do I reverse filter class, or pull this off in general, so I get my posts filtered in reverse order? -
How do I exclude some File Types from FilerFileField (filer.fields.image)?
I'm working on Django-CMS project. For some models I need to let users upload only these types of files -> .svg, .png, .jpg, .webp (basically for images). The best solution, as I thought, was to use FilerImageField, but it doesn't allow me to upload .svg or .webp. So, what I need to do, is to exclude the possibility of uploading .pdf and other types of files to FilerImageField and allow only for .svg, .png, .jpg, .webp. Would appreciate any kind of help. from cms.models.pluginmodel import CMSPlugin from django.db import models from filer.fields.image import FilerFileField, FilerImageField class MainSection(CMSPlugin): image = FilerFileField(verbose_name="Section Image", related_name="section_image", null=True, blank=True, on_delete=models.CASCADE, help_text="Max file size: 500 kb. Recommended dimensions: 1100x650 px. Recommended file types: svg, png, jpg, webp") -
how to perform django queryset in more efficient way to get following response?
here is my model fields: staff = models.ForeignKey(StaffProfile, on_delete = models.SET_NULL, blank=True,null = True) created_at = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length = 250,choices = EventStatusChoice.choices,default = EventStatusChoice.PROGRESS_NOTES) summary = models.CharField(max_length=200, blank=True, null=True) Event category choices are: class EventStatusChoice(models.TextChoices): INJURIES = 'injury','Injuries' FEEDBACKS = 'feedback','Feedbacks' ENQUIRIES = 'enquiry','Enquiries' INCIDENTS = 'incident','Incidents' PROGRESS_NOTES = 'note','Progress Notes' WARNING = "warning", "Warning" I want a response something like following: "data": [ { "staff": "admin", "injury": 0, "feedback": 2, "enquiry": 0, "incident": 1, "note": 0, "warning": 0 }, { "staff": "tutaketuw", "injury": 0, "feedback": 0, "enquiry": 0, "incident": 1, "note": 0, "warning": 0 },] I did it in my own way, and its working good. Following is my way: def get_staff_summary(self,start = None,end = None,search = None): qs = EventModel.objects.get_distinct_staff(search) data_list = [] for i in qs: data = {} data['staff'] = i['staff__staff__username'] for j in EventStatusChoice.choices: if start != None and end != None: data[f'{j[0]}'] = EventModel.objects.filter(category = j[0],staff__staff__username = i['staff__staff__username'],created_at__date__gte = start,created_at__date__lte = end).count() else: data[f'{j[0]}'] = EventModel.objects.filter(category = j[0],staff__staff__username = i['staff__staff__username']).count() data_list.append(data) return data_list Now, I want to do it in much more proper and efficient way. Can anybody please help to get above response(or any similar type of response) by using only … -
Detect changes in django-bootstrap-datepicker-plus with JQuery
I am using django-bootstrap-datepicker-plus package, and I am trying to display an alert when the date is changed. However, jquery does not seem to detect any changes to the date. Following this question Detect change to selected date with bootstrap-datepicker only works when I add the JQuery UI CDN to my code, which causes a problem as two datepickers appear. Is there a way to get JQuery to detect a change in django-bootstrap-datepicker without adding JQuery UI code? forms.py from django import forms from bootstrap_datepicker_plus.widgets import DatePickerInput class ExampleForm(forms.Form): DOB = forms.DateField(required=False, label="Date of Birth", input_formats=['%d/%m/%Y'], widget=DatePickerInput(format='%d/%m/%Y') ) Html <div class="col-12 col-md-6 mb-0 p-1"> {{ form.DOB|as_crispy_field }} </div> Rendered HTML -
PostgreSql not coming to database from Django project
I am using PostgreSql as database in my Django project. When I run it locally via pgAdmin, the data appears, but when I run it on the server, the data does not come in pgAdmin. Django settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xxxx', 'USER' : 'xxx', 'PASSWORD': 'xxx', 'HOST': 'pgdb', 'PORT': 5432, } } docker-compose.yaml services: # CaddyServer reverse proxy caddy: restart: always image: caddy:2-alpine ports: - "443:443" command: caddy reverse-proxy --from https://xxxxxx.com --to http://0.0.0.0:8000 #volumes: # - /local/path/to/Caddyfile:/path/inside/continer/to/Caddyfile # networks: # - web # - bridge # Django web app django: restart: always build: . ports: - "80:8000" depends_on: - pgdb #environment: # - url=https://api.backend.example.com #command: "gunicorn config.wsgi:application --bind 0.0.0.0:8000" #networks: # - bridge pgdb: image: postgres container_name: pgdb environment: - POSTGRES_DB=xxxx - POSTGRES_USER=xxxx - POSTGRES_PASSWORD=xxxx volumes: - pg-data:/var/lib/postgresql/data/ volumes: pg-data: I am connecting via pgAdmin server ip. The pgAdmin connection is established, but the data I entered into the system is not visible on pgAdmin. -
Filter and get all the customers who had brought the authors other contents to send the notification when new content is added
I want to Filter and get all the customers who had brought the authors other contents to send the notification when new content is added This works on queryset I know but I'm Confused on how to do that. If anyone please share. Here are my models content: class Content(models.Model): title = models.CharField(max_length=1000) Author = models.ForeignKey('User',on_delete=models.CASCADE) slug = AutoSlugField(populate_from='title', unique=True, null=False) cover = models.ImageField(upload_to='course', default='nocover.jpg') catogary = models.ForeignKey(Category, on_delete=models.RESTRICT) description = models.TextField(max_length=2000, null=True, blank=True) requirements = models.TextField() price = models.FloatField() language = models.ForeignKey(Language, on_delete=models.RESTRICT) Puchased content class PurchasedContent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) course = models.ManyToManyField(Course, blank=True, related_name='course') I want all the list of Customers email who had brought a particular Authors course the Author will be authenticated while adding. We'll get the Author as request.user Here is sample ListCreateAPIView in django rest Framework class createlistcourseview(generics.ListCreateAPIView): permission_classes = [TokenHasReadWriteScope] queryset = Content.objects.all() serializer_class = ContentSerializer def perform_create(self, serializer): #Here I want to create a Function that sends mall serializer.save(author=self.request.user) -
How to pass variable from views to model in Django
Models.py from django.db import models class Voiceapi(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=200) voice_text = models.CharField(max_length=200,default="voice_data") Views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. from rest_framework import viewsets import requests import gdown from pydub import AudioSegment import speech_recognition as sr from .serializers import * from .models import * import time from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from urllib.request import urlopen # create a viewset class VoiceViewSet(viewsets.ModelViewSet): # define queryset queryset = Voiceapi.objects.all() # specify serializer to be used serializer_class = VoiceSerializer # print(Voiceapi.objects.values()) datas = Voiceapi.objects.values() print(datas) for i in datas: try: print("Audio File-->",i['name']) audio_url = i['name'] audio_id = i['id'] def VoiceRecognizer(audio,audio_id): r = sr.Recognizer() with sr.AudioFile(audio) as source: audio_text = r.listen(source) try: text = r.recognize_google(audio_text) print(text) Voiceapi.objects.filter(pk=audio_id).update(voice_text=text) except: print('Audio Not Clear') audio = "/home/venpep/voicetotext/messages/media/test.wav" VoiceRecognizer(audio,audio_id) except: print("Not audio file") I need to pass the variable "text" from my view.py to models.py to set the default in voice_text.Is there any solution to get the text from the view page. The text variable is a basic string that needs to pass to the models.py -
SQLAlchemy - AttributeError: 'str' object has no attribute 'body'
I need to save some data using SQLAlchemy. The Insert statement works fine when the sqlalchemy create_engine is initialize inside the file where the function lives from sqlalchemy import create_engine from sqlalchemy.sql import text engine = create_engine('sqlite:///db.sqlite3') // this will work @csrf_exempt def save(request): payload = json.loads(request.body.decode('utf-8'))['data'] payload = payload['body'] response = cu.call("externalapi/someendpoint", payload=json.dumps(payload), method="POST") id = response['id'] statement = f"""INSERT INTO consignments(consignment_id) VALUES({id})""" with engine.connect as con: con.execute(statement) // this will not work from utils import create_consignment @csrf_exempt def save(request): payload = json.loads(request.body.decode('utf-8'))['data'] payload = payload['body'] response = cu.call("externalapi/someendpoint", payload=json.dumps(payload), method="POST") id = response['id'] statement = f"""INSERT INTO consignments(consignment_id) VALUES({id})""" create_consignment(statement) //this will throw error `payload = json.loads(request.body.decode('utf-8'))['data'] AttributeError: 'str' object has no attribute 'body'` // If I remove the `create_consignment`, the error gone So the create_consignment method, is just lines of codes extracted to make it more reusable utils/create_consignment.py import sqlalchemy as db from sqlalchemy.sql import text engine = db.create_engine('sqlite:///db.sqlite3', connect_args={'check_same_thread': False}) def create_consignment(stmt): with engine.connect() as con: statement = text(stmt) con.execute(statement) Any Idea whats going on and how to prevent this error? -
Strip tags in django view page django admin
I have a user with view only permission in a model with richtextfield, but when viewing the data on this particular user with only view permission, the data is not formatted in html. I know, below is how to strip tags when you want to strip tags in list_display, def what_field(self, obj): return format_html(obj.what) please see attached image. -
Facing problem while trying to update a django-model
I have a requirement to update few fields of django-ORM-model ( legacy db being used is postgressql), i have tried different approaches but nothing is working please help tried approaches: 1) user = Model.objects.using('default').filter(id=ids) user.name="Gandalf" user.save() 2) user = Model.objects.using('default').filter(id=ids).update(name="Gandalf") -
DRF Filtering model by another model id
I have this models: class Organization(models.Model): name = models.CharField( "Organization name", max_length=100, unique=True ) description = models.TextField("Organization description") districts = models.ManyToManyField( "District", related_name="organizations", blank=True, ) class District(models.Model): name = models.CharField("District name", max_length=100, unique=True) And I need to filter organizations by district id, so url should be: organizations/<district_id>/ What is the better way to do it? Currently I have two solutions, first: urls.py router.register("organizations", OrganizationViewSet, basename="organizations") router.register( "organizations/(?P<district_id>\d+)", OrganizationViewSet, basename="organizations_by_district", ) views.py class OrganizationViewSet(viewsets.ModelViewSet): serializer_class = OrganizationSerializer def get_queryset(self): district = self.kwargs.get("district_id") if district: return Organization.objects.filter(districts__in=[district]) return Organization.objects.all() Second solution: urls.py urlpatterns = [ path(r"organizations/<int:district_id>/", get_orgs_by_district, name="org_by_district"), ... ] views.py @api_view(http_method_names=['GET']) def get_orgs_by_district(request, district_id): objs = Organization.objects.filter(districts__in=[district_id]) data = OrganizationSerializer(objs, many=True).data return Response(data, status=200) Both solutions work, but which is better? And maybe there is another solution that I don't know? -
Django tests - reset session or change session['session_key']
I need to test behavior when two different users access a particular URL (sequentially). User A visited URL User B visited URL for this I want to change an IP address of the self.client and also a session['session_key'] It looks like changing the session key is not so straightforward. I tried, for example: self.client.defaults['REMOTE_ADDR'] = '2.2.2.2' session = self.client.session session['session_key'] = 'abc' session.save() which did not help Do you know how to change it or reset the session?