Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset from url parameter issue
I have multi models, and I want to have one listview to display it. I would like to have something like this: model = self.kwargs['name'] queryset = model.objects.all() but seems not working.... any help please ? Regards, -
multilevel user admin in django
Need to create multi level users with roles having same validation for the models as that specified in admin.py, only that each of these users will have different roles.eg. Customer can have different custom_users with diff. roles. A customer can create multiple such custom users with different roles. Each customer can see only his own records in the admin panel. Models: Customer, Custom_user(customer f.key), Role(permission) , customer_customuser(custom_user_id,role_id), But I need to use the same permissions as available in the original django default admin panel for the diff.models like add,edit,delete, view. But have also customized it in admin.py such that each customer can administer using changelist_view and filtering the queryset objects accordingly. How can this be achieved. The models: class Role(models.Model): name = models.CharField(max_length=100, unique=True) permissions = models.ManyToManyField(Permission) def __str__(self): return self.name class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("The Email field must be set") email = self.normalize_email(email) user = self.model(username=username, email=email) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None): user = self.create_user(username, email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=150, unique=True) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # Specify a related_name below role … -
Adding WeasyPrint to Dockerfile - Django Cookiecutter
I am new to Docker and have never used WeasyPrint before. (I need to create Javascript charts.) I use the django Cookiecutter setup for Docker. So what do i need to change in this Dockerfile to include Weasy? I found this on Weasy setup page. https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#ubuntu-20-04 Not sure what to add or where? Or even if this is how to set up? Thank you. # define an alias for the specific python version used in this file. FROM python:3.11.5-slim-bullseye as python # Python build stage FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ # psycopg2 dependencies libpq-dev # Requirements are installed here to ensure they will be cached. COPY ./requirements . # Create Python Dependency and Sub-Dependency Wheels. RUN pip wheel --wheel-dir /usr/src/app/wheels \ -r ${BUILD_ENVIRONMENT}.txt # Python 'run' stage FROM python as python-run-stage ARG BUILD_ENVIRONMENT=local ARG APP_HOME=/app ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV BUILD_ENV ${BUILD_ENVIRONMENT} WORKDIR ${APP_HOME} # devcontainer dependencies and utils RUN apt-get update && apt-get install --no-install-recommends -y \ sudo git bash-completion nano ssh # Create devcontainer user and add it to sudoers RUN groupadd --gid 1000 … -
MacOs M2Crypto for Django error I don't know how to solve it
Raised when I execute 'python manage.py xxxx' in Django's virtual environment ImportError: Dlopen (/ Users/xieyang/Desktop/nagain shyun_virtualenr/lib/python3.8 / site - packages/M2Crypto / _m2crypto retaining - 38 - Darwin. S o, 0x0002): symbol not found in flat namespace (_X509_it) But I can start my project normally in the IDE, I don't know how to solve it. Please help me My environment is Mac m2,python is 3.8. I try not to use virtual environment but I still get the above problem. -
django-import-export Customize Admin Missing Field Error
I am using django-import-export to manage csv uploads. I have the following import working vanilla and now want to extract the 'league' and 'season' fields from the .csv and instead choose them via form fields in the admin interface. I am able to select values but when I submit I receive the following error: Line number: 1 - (1048, "Column 'league_id' cannot be null") I followed the code example here: https://django-import-export.readthedocs.io/en/latest/advanced_usage.html#customize-admin-import-forms Here's the relevant code: # admin.py class TeamsSeasonResource(resources.ModelResource): # https://django-import-export.readthedocs.io/en/stable/advanced_usage.html#importing-model-relations ballpark = fields.Field( column_name='ballpark', attribute='ballpark', widget=ForeignKeyWidget(Ballpark, field='park_name')) team = fields.Field( column_name='team', attribute='team', widget=ForeignKeyWidget(Team, field='team_acronym')) league = fields.Field( column_name='league', attribute='league', widget=ForeignKeyWidget(LeaguesSeason, field='id')) season = fields.Field( column_name='season', attribute='season', widget=ForeignKeyWidget(Season, field='season_year')) class Meta: model = TeamsSeason import_id_fields = ('ballpark', 'team', 'season', 'league') class TeamsSeasonAdmin(ImportMixin, admin.ModelAdmin): list_display = ('id', 'season','team') resource_classes = [TeamsSeasonResource] import_form_class = TeamSeasonImportForm confirm_form_class = TeamSeasonConfirmImportForm def get_confirm_form_initial(self, request, import_form): initial = super().get_confirm_form_initial(request, import_form) # Pass on the value from the import form to # the confirm form (if provided) if import_form: initial['league'] = import_form.cleaned_data['league'] initial['season'] = import_form.cleaned_data['season'] return initial pass admin.site.register(TeamsSeason, TeamsSeasonAdmin) # forms.py from django import forms from import_export.forms import ConfirmImportForm, ExportForm, ImportForm from .models import * class TeamSeasonImportForm(ImportForm): league = forms.ModelChoiceField( queryset=LeaguesSeason.objects.all(), required=True) season = forms.ModelChoiceField( queryset=Season.objects.all(), … -
How to effectively use django-sso for Single Sign On
Am using django-sso package for SSO(Single Sign On), i have installed it and set the configuration by following the documentation and everything seems to work well. But my questions now is According to the documentation, to get additional fields on the client side, we put this line of code in the Server settings.py . # SSO settings section in the gateway side are optional SSO = { # Timeout for the communication with subordinated services. (OPTIONAL) # This timeout is defined in seconds with a default value of 0.1s # (100ms) per registered service. 'SUBORDINATE_COMMUNICATION_TIMEOUT': 0.1, # Additional fields. (OPTIONAL). For more details look to part # named as "Send additional data to subordinated services" 'ADDITIONAL_FIELDS': ('first_name', 'last_name', 'phone_number'), } So my question is how can i get these first_name, last_name and phone_number on the client side How can i make the login page more secure by adding Multi factor Authentication like Kagi or django-mfa How can i add Social Auth to work with it **What i have tried ** In my server settings.py, i added # SSO settings section in the gateway side are optional SSO = { # Timeout for the communication with subordinated services. (OPTIONAL) # This … -
Codecov coverage considers wrong files on Django app
I have been using codecov on my projects to produce test coverage, among others, a Django app. I could upload by hand after each push, but there are GitHub actions to perform this automatic action for me, right!? I wrote the yml file below to perform such a pipeline. However, there are two problems, from my perspective: It must consider ONLY application folder src! On the current state, it considers folders setup, src and tests. Your help will make me help others develop nice apps in Django. name: Coverage CI on: [push, pull_request] jobs: poetry: runs-on: ubuntu-20.04 defaults: run: shell: bash strategy: max-parallel: 42 fail-fast: false matrix: python-version: ["3.8", "3.9", "3.10"] steps: #---------------------------------------------- # check-out repo and set-up python #---------------------------------------------- - name: Check out repository uses: actions/checkout@v3 - name: Set up python id: setup-python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} #---------------------------------------------- # install & configure poetry #---------------------------------------------- - name: Install and configure Poetry uses: snok/install-poetry@v1 with: virtualenvs-create: true virtualenvs-in-project: true #---------------------------------------------- # load cached venv if cache exists #---------------------------------------------- - name: Load cached venv id: cached-poetry-dependencies uses: actions/cache@v3 with: path: .venv key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }} #---------------------------------------------- # install dependencies if cache does not exist #---------------------------------------------- … -
Rest Api not found in django application
I'm trying to do a simple app in django, I'm a beginner and I'm having some problems; My error is: AttributeError: 'function' object has no attribute 'get_extra_actions' My view: class UserViewSet(viewsets.ViewSet): serializer_class = UserSerializer def list(self, request): users = [ {'id': 1, 'name': 'John', 'phone': '3382496345','email': 'john@example.com'}, {'id': 2, 'name': 'Jane', 'phone': '3382496345','email': 'jane@example.com'}, ] serializer = self.serializer_class(users, many=True) return Response(serializer.data) router = routers.DefaultRouter() router.register('users',UserViewSet.as_view({'get':'users'}), basename='user') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] I don'know wher is my error -
error django.db.utils.ProgrammingError: cannot cast type bytea to boolean
i want to change bytea type to boolean in is_reply field and migrate it but i can not do it even i delete model. i registerd this model in admin panel. i use postgresql class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ucomments') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pcomments') reply = models.ForeignKey('self', on_delete=models.CASCADE, related_name='rcomments', blank=True, null=True) is_reply = models.BooleanField(default=False) body = models.TextField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' -
I used if form. is_valid() but it gives a typerror that says: any() takes exactly one argument (0 given)
def listing_view(request, listing_title): list_id = get_object_or_404(Listing, title=listing_title) form = BidForm() # Define the form outside of the if block if request.method == 'POST': form = BidForm(request.POST) if form.is_valid(): bid_input = form.cleaned_data['bid_input'] print(bid_input) if bid_input <= list_id.current_price: messages.error(request, 'Bid must be greater than the current price.') print(messages.error) return redirect('auctions:view', listing_title=listing_title) else: bidding_instance = Bidding() bidding_instance.bidder = request.user bidding_instance.bid = list_id bidding_instance.bid_amount = bid_input bidding_instance.save() messages.success(request, 'Bid Successfully Input') print(bidding_instance.objects.all()) return redirect('auctions:new', listing_title=listing_title) return render(request, 'auctions/view_listing.html', {"list_id": list_id, "form": form}) I am expecting for it to accept the bid_input then go to either a newpage or thesame page with a message but it gives a any() error instead..kindly help check it out -
Many-to-Many relationship saving on one form, not on the other
i'm at a loss, i have some code to save a modelform using the FilteredSelectMultiple widget on a many-to-many relationship. It does work on 2 out of the 4 forms. But i can't figure out why it wont work on the last 2. any help? Here is the code for one of the 2 that is working: forms.py: class SubDomainForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.required = False domains = forms.ModelMultipleChoiceField(queryset=Domain.objects.all(), label=('domains'), widget=FilteredSelectMultiple(('domains'), False, )) subdomains = forms.ModelMultipleChoiceField(queryset=SubDomain.objects.all(), label=('subdomains'), widget=FilteredSelectMultiple(('subdomains'), False, )) class Media: extend = False css = { 'all': [ '/static/admin/css/widgets.css' ] } js = ( '/static/assets/admin/js/django_global.js', '/static/assets/admin/js/jquery.init.js', '/static/assets/admin/js/core.js', '/static/assets/admin/js/prepopulate_init.js', '/static/assets/admin/js/prepopulate.js', '/static/assets/admin/js/SelectBox.js', '/static/assets/admin/js/SelectFilter2.js', '/static/assets/admin/js/admin/RelatedObjectLookups.js', ) class Meta: model = SubDomain fields = ('domains', 'subdomains', 'name', 'description') widgets = {'description': CKEditorWidget(),} models.py: class SubDomain(models.Model): domains = models.ManyToManyField(Domain, verbose_name='Link to Domain', blank=True) subdomains = models.ManyToManyField('self', verbose_name='Link to other SubDomain', blank=True) name = models.CharField(max_length=50) description = RichTextField() def __str__(self): return f"{self.name}" class Meta: verbose_name_plural = ' SubDomain' Html: <!--- api\formfiller\templates\subdomain_form.html --> {% load static %} {% block head %} <head> {{ form.media }} {{ form.media }} <style> .ck.ck-editor__main > .ck-editor__editable:not(.ck-focused) { width: 800px; height: 300px; } .ck-rounded-corners .ck.ck-editor__main > .ck-editor__editable, .ck.ck-editor__main > .ck-editor__editable.ck-rounded-corner { width: … -
How can I set a default value in an inline admin?
Let's say I have a NarratorAdmin page to display and change details of the Narrator model. It includes a BookInline where the narrator's Books can be changed, added or deleted. Not all of Book's fields are present in the BookInline-- only the most "important" ones. Let's further imagine that Book has a "category" field, with values like print, digital, hybrid, audiobook. When a Book is created from the NarratorAdmin page, I want to automatically set its "category" to "audiobook". "category" is NOT included in BookInline.fields. The user doesn't need to see it and it doesn't make sense for them to change it. I've tried the following methods (all suggested by AI): def get_formset(self, request, obj=None, **kwargs): formset = super().get_formset(request, obj, **kwargs) formset.form.base_fields['category'].initial = "audiobook" return formset (Doesn't work because "category" is not in base_fields) def save_model(self, request, obj, form, change): obj.category = 'audiobook' super().save_model(request, obj, form, change) (After adding some print statements, I don't think this method is actually being called) def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.category = 'audiobook' instance.save() formset.save_m2m() Similar to the above, this one doesn't seem to be getting called when I expected it to. -
Django allowing duplicate records despite having unique_together constraints
My django model has three fields, company_id jurisdiction businessStartDate I have added below constraints, class Meta: app_label = 'payroll' unique_together = ( 'Company_id', 'jurisdiction', 'businessStartDate', ) Despite adding these constraints and using get_or_create to add new records, I am seeing duplicate records being inserted in the table. Here is the snapshot of mysql table, mysql> select Company_id, jurisdiction, businessStartDate from companyjurisdiction; +--------------+--------------+-------------------+ | Company_id | jurisdiction | businessStartDate | +--------------+--------------+-------------------+ | 496395 | CA | NULL | | 496395 | CA | NULL | | 496395 | FED | NULL | | 496395 | MI | NULL | +--------------+--------------+-------------------+ Please suggest what I am doing wrong here? Does having NULL values in businessStartDate column creating this issue? -
Django Ninja Update a FileField
I am trying to create a simple restful API using Django-ninja. Here is the post method to add a new record: @router.post('/add', response={201: WordSchema, 401: DefaultSchema, 404: DefaultSchema}, tags=["Dictionary"]) def add_word(request, lang1: str, lang2: str, word_class: int = None, description: str = None, example: str = None, sound: UploadedFile = None, image: UploadedFile = None): if not request.auth.is_superuser: return 401, {"detail": "Unauthorized"} try: if word_class is not None: word_class = WordClass.objects.get(pk=word_class) word = Word.objects.create( created_by=request.auth, lang1=lang1, lang2=lang2, word_class=word_class, description=description, example=example, sound=sound, image=image ) return 201, word except WordClass.DoesNotExist: return 404, {"detail": "WordClass Does not exist"} This endo point works without a problem. The next step is to create a put endpoint. @router.put('/put', response={200: DefaultSchema, 201: WordSchema, 401: DefaultSchema, 404: DefaultSchema, 409: DefaultSchema}, tags=["Dictionary"]) def put_word(request, item_id: int, lang1: str, lang2: str, description: str = None, example: str = None, word_class: int = None, sound: UploadedFile = None, image: UploadedFile = None): if not request.auth.is_superuser: return 401, {"detail": "Unauthorized"} try: if word_class is not None: word_class = WordClass.objects.get(pk=word_class) word = Word.objects.get(pk=item_id) word.lang1 = lang1 word.lang2 = lang2 word.word_class = word_class word.description = description word.example = example word.sound = sound word.image = image word.save() return 200, {"detail": "Record updated"} except WordClass.DoesNotExist: return … -
imagen_field' attribute has no file associated with it
quiero cargar imagenes en mi plantilla pero recibo el siguiente error imagen_field' attribute has no file associated with it. por favor alguien que me ayude he probadoenter image description here enter image description hereenter image description hereenter image description here -
testing views in django
why this error, a cant find the solution, help def test_retrieve_update_destroy_empresa(self): self.client.force_authenticate(user=self.user) response = self.client.get(reverse('empresa-rud', kwargs={'source': self.empresa.id, 'empresa': self.empresa.id})) self.assertEqual(response.status_code, status.HTTP_200_OK) response1 = self.client.put(reverse('empresa-rud', kwargs={'source': self.empresa.id, 'empresa': self.empresa.id}), data={'nome_fantasia': 'empresa teste', 'perfil': self.perfil_empresa.id, 'status': 'ativo'}) self.assertEqual(response1.status_code, status.HTTP_200_OK) response2 = self.client.delete(reverse('empresa-rud', kwargs={'source': self.empresa.id, 'empresa': self.empresa.id})) self.assertEqual(response2.status_code, status.HTTP_204_NO_CONTENT) (.venv) afira@Ederson:fazendo/api-hidroview (AFIRA-ATUALIZADO)$ pytest empresa/tests/test_views.py ======================================================================================================================= test session starts ========================================================================================================================platform linux -- Python 3.10.12, pytest-7.4.0, pluggy-1.2.0 django: settings: api_hidroview_com_br.settings (from ini) rootdir: /mnt/c/Users/Verdevaldo/Desktop/fazendo/api-hidroview configfile: pytest.ini plugins: cov-4.1.0, django-4.5.2 collected 2 items empresa/tests/test_views.py .F [100%] ============================================================================================================================= FAILURES =============================================================================================================================_____________________________________________________________________________________________________ EmpresaViewTestCase.test_retrieve_update_destroy_empresa _____________________________________________________________________________________________________ self = <empresa.tests.test_views.EmpresaViewTestCase testMethod=test_retrieve_update_destroy_empresa> def test_retrieve_update_destroy_empresa(self): self.client.force_authenticate(user=self.user) response = self.client.get(reverse('empresa-rud', kwargs={'source': 1, 'empresa': 1})) self.assertEqual(response.status_code, status.HTTP_200_OK) E AssertionError: 404 != 200 empresa/tests/test_views.py:46: AssertionError ------------------------------------------------------------------------------------------------------------------------ Captured log call -------------------------------------------------------------------------------------------------------------------------WARNING django.request:log.py:241 Not Found: /v2/1/empresa/1/ ===================================================================================================================== short test summary info ======================================================================================================================FAILED empresa/tests/test_views.py::EmpresaViewTestCase::test_retrieve_update_destroy_empresa - AssertionError: 404 != 200 ============================================================================================================= 1 failed, 1 passed in 152.56s (0:02:32) ============================================================================================================== -
city autocomplete in django form
I have a city field and I need to autocomplete the city when I start typing without using the google maps api <form action="{% url 'CityEvents' %}" method="post"> {% csrf_token %} <input type="text" name="city" id="city"> <button type="submit">Choose</button> </form> -
Django create Polygon from list of lat/long coordinates
I have a list of lat/long coordinates that make up a polygon. How do I instantiate a Polygon, to be used as a PolygonField? -
Strange error when trying to import ASGI into settings.py
I'm doing a project: simple web-chat and I need the help of websockets for continuous connection and data proccesing. Everything would be fine, but an error crashes that it is not possible to import ASGI. How can i fix it? here my setting.py: INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'django_filters', 'rest_framework', 'channels', 'allauth', 'allauth.account', 'allauth.socialaccount', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'chatajax.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'chatajax.wsgi.application' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } SITE_ID = 1 AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD … -
Deploy Next.js 13 & Django & Nginx & Docker
I am a newbie in Docker, please help me deploy my full-stack web application (with Django and Next.js 13), I have successfully deployed only the Django web app, now I want to add a Next.js frontend interface in the same domain than the Django app after the example.com/app url, here is the current configuration for the Django app api/ -- api/ -- -- manage.py -- frontend/ (I know that api/frontend/ is not logic, but that's how it is :) -- -- app/ -- -- package.json -- -- yarn.lock -- nginx/ -- -- Dockerfile -- -- nginx.conf -- -- options-ssl-nginx.conf -- -- nginx-setup.conf/ -- docker-compose.yml docker-compose.yml: services: nginx: build: ./nginx ports: - 80:80 - 443:443 depends_on: - api restart: "on-failure" volumes: - static_volume:/home/app/staticfiles - media_volume:/home/app/mediafiles - certbot_etc:/etc/letsencrypt - certbot_var:/var/lib/letsencrypt - ./nginx:/var/www/certbot api: build: ./api command: sh -c "python manage.py migrate && python manage.py collectstatic --noinput && gunicorn api.wsgi:application --workers 4 --timeout 3600 --bind 0.0.0.0:8000" volumes: - static_volume:/home/app/staticfiles - media_volume:/home/app/mediafiles - certbot_etc:/etc/letsencrypt - certbot_var:/var/lib/letsencrypt - ./nginx:/var/www/certbot expose: - 8000 depends_on: - db restart: "on-failure" db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" certbot: image: certbot/certbot command: certonly --webroot -w /var/www/certbot --email email@example.com -d example.com -d www.example.com --agree-tos --no-eff-email --keep-until-expiring volumes: - … -
Django query not respecting order for ltree field subquery (Postgresql)
Background I have an application that uses a team model that includes a field using the ltree postgres extension, which is a field that allows you to store the entire ancestral chain of an object including itself in a single field (the representation I see is . separated id values). This field type is not supported by Django out of the box, so some custom extensions were added to add proper support for the ancestor/descendant checks that I think are based on some packages available that do some of the same. This ltree field is being used as a path column in our Team table in the database to store team hierarchies. The Problem There is an export option that will generate a CSV copy of the team structure, and as part of that, a given team will have the ancestors display each in their own columns next to other information about the team. When some larger teams are exported, the order of the ancestors is scrambled. Some digging shows that the subquery used to create the list annotation that explodes the path into individual teams is not respecting the ordering provided in the subquery. The basic query that is … -
How can I change the label for a field in model serailizers
I have my model with Django ORM: class MyModel(): contract_version = models.ForeignKey( ContractVersion, verbose_name='Contract', related_name='contract_versions', on_delete=models.PROTECT, ) I also have serializers: class ContractSerializer(ModelSerializer): class Meta: model = Contract fields = ( ... ) inlines = ( 'contracts_versions', ) How can I change the label in this case? Without changing the model, this is needed for the OPTIONS of my query. P.S. I do not need to add this field to the fields -
What is & How to know the default screenshot's window size of browsers in Selenium?
I ran the code below to take 3 screenshots of Django Admin on Google Chrome, Microsoft Edge and Firefox. *I use Django, pytest-django and Selenium: import os import pytest from selenium import webdriver def take_screenshot(driver, name): # time.sleep(1) os.makedirs(os.path.join("screenshot", os.path.dirname(name)), exist_ok=True) driver.save_screenshot(os.path.join("screenshot", name)) @pytest.fixture(params=["chrome", "edge", "firefox"], scope="class") def driver_init(request): if request.param == "chrome": web_driver = webdriver.Chrome() request.cls.browser = "chrome" if request.param == "edge": web_driver = webdriver.Edge() request.cls.browser = "edge" if request.param == "firefox": web_driver = webdriver.Firefox() request.cls.browser = "firefox" request.cls.driver = web_driver yield web_driver.close() @pytest.mark.usefixtures("driver_init") class Screenshot: def screenshot_admin(self, live_server): self.driver.get(("%s%s" % (live_server.url, "/admin/"))) take_screenshot(self.driver, "admin/" + self.browser + ".png") Then, I could take 3 screenshots which have different window size depending on browsers as shown below: chrome.png: edge.png: firefox.png: So, what is & how can I know the default screenshot's window size of the browsers in Selenium? -
Session cookie for multiple domains. Security concerns
I think this is kind of a trivial question, but I got an idea that I want to share and ask if it is even necessary. I have 3 react apps as 3 different subdomains - auth.site.com, client.site.com and admin.site.com, and a django backend at api.site.com. Now it works like this: User logins from auth, through api.site.com Django sets session cookie with Domain=.site.com User is redirected to the allowed react app (client or admin) But... This way I can't set the cookie to specific react app subdomain, because Set-Cookie header is sent from api and browser rejects it if domain is not .site.com Second approach: User logins at auth User is redirected to, for example admin.site.com/internal/setcookie/<long_long_token> (web server sends these /internal/* paths to django instead of react) At that view, django gets the session from this one-time <long_long_token>, and sets the cookie with Domain=admin.site.com. User is redirected to / Considerations First of all, I wonder if can I even use this, will the browser not send cookies to api.site.com when session cookie has a Domain=admin.site.com? Also, I don't like that if user logins and is redirected to client, he can still just change subdomain to admin and will still have … -
How to know if a 500 error is raised in DRF exception handler?
I am creating a custom exception handler in django rest. I want to determine if incoming exception is a 500 exception or related to 500 exceptions. from rest_framework.views import exception_handler def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: response.data['status_code'] = response.status_code return response The problem is response status code is determined only when exception is related to serializer or a explicit response with 500 error code is raised. When I try to raise a python exception like ValueError, the response is None. And there is no way to know if exception is 500 or should be 500. I need to know if exception is a 500 error in my custom exception handler. What should I do?