Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to translate the url in Django Admin?
I'm trying to translate the entire Django Admin including the url from English to French. This is my django-project below. *I use Django 4.2.1: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-models.py | |-admin.py | └-apps.py |-my_app2 └-locale └-fr └-LC_MESSAGES |-django.po └-django.mo And, this is core/settings.py below: # "core/settings.py" MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('fr', _('French')) ) And, this is core/urls.py below: # "core/urls.py" from django.contrib import admin from django.urls import path from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( path('admin/', admin.site.urls) ) And, this is my_app1/models.py below: # "my_app1/models.py" from django.db import models from django.utils.translation import gettext_lazy as _ class Person(models.Model): name = models.CharField(max_length=20, verbose_name=_("name")) class Meta: verbose_name = _('person') verbose_name_plural = _('persons') And, this is my_app1/apps.py below: # "my_app1/apps.py" from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class MyApp1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_app1' verbose_name = _('my_app1') And, this is locale/fr/LC_MESSAGES/django.po below: # "locale/fr/LC_MESSAGES/django.po" ... #: .\core\settings.py:140 msgid "English" msgstr "Anglais" #: .\core\settings.py:141 msgid "French" msgstr "Français" ... #: .\my_app1\apps.py:7 msgid "my_app1" msgstr "mon_app1" #: .\my_app1\models.py:6 msgid "name" … -
I'd like to convert a little code from Flask for use in Django
In Flask I have a simple combobox and when I select an item, it is printed in the textbox (using simple conditions). All very simple. I'm new to Django and learning, so I'm having a hard time using this Flask code in Django, because I don't know where and how to use it. Of course the language is the same, but I change the frameworks. I'll show you the code I use in both Flask and Django. In Django I pasted the def dropdown function into app1/views.py. I created app1/forms.py page where there is combobox and textbox. In index.html I don't know how to set the code. I don't know if I did these things correctly. Can you help me please? Thank you Here is the code I use in Flask: Flask: app.py colours = ["Red", "Blue", "Black", "Orange"] @app.route('/') def index(): return render_template("index.html", colours=colours, chosen="Black") @app.route("/combobox", methods=["GET","POST"]) def dropdown(): picked = request.form['colours'] if picked == 'Red': message = "<<< You chose red" elif picked == 'Blue': message = "<<< You chose blue" elif picked == 'Black': message = "<<< You chose black" else: message = "<<< Oh no, you chose orange" return render_template("index.html", colours=colours, chosen=picked, message=message) Flask: index.html <form … -
When I wanna dockerize, I get: django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")
I am attempting to dockerize a Django project that features a MySQL database and nginx. When I run the docker-compose up --build command, I receive the error message django.db.utils.OperationalError: (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)"). Here's my docker-compose.yml file: version: '3.7' services: app: build: ./app env_file: - .env container_name: app restart: always expose: - 8000 command: bash -c "python3 manage.py collectstatic --noinput && python3 manage.py migrate --noinput --fake-initial && \ gunicorn -b 0.0.0.0:8000 veblog.wsgi" environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_HOST=sqldb mem_limit: 1g depends_on: - sqldb # - nginx volumes: - ./volumes/app:/app - type: bind source: ./volumes/media target: /app/media - type: bind source: ./volumes/static target: /app/static nginx: build: ./nginx container_name: nginx restart: always ports: - 8000:80 sqldb: image: mysql:latest container_name: sqldb restart: always depends_on: - nginx expose: - 3306 environment: - MYSQL_DATABASE=${NAME} - MYSQL_USER=${USER_NAME} - MYSQL_PASSWORD=${PASSWORD} - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD} - MYSQL_INITDB_SKIP_TZINFO=true - MYSQL_INIT_COMMAND=SET GLOBAL host_cache_size=0; volumes: - type: bind source: ./volumes/dbdata target: /var/lib/mysql - /usr/share/zoneinfo:/usr/share/zoneinfo:ro This is my Dockerfile in the app directory: FROM python:3 ENV PYTHONDONTWRITEBYCODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /app WORKDIR /app COPY . . RUN apt update RUN apt install gcc python3-dev musl-dev -y RUN pip install --upgrade pip … -
Django Foreignkey or onetoone models create,edit,view within an Modelform
Hy all, I am building an HR management system, i have below models class EmployeeDetails(models.Model): EMP_NO = models.CharField(max_length=6,primary_key=True,validators=[Validation]) EMP_First_Name = models.CharField(max_length=50,null=False,blank=False,validators=[Validation]) passport = models.OneToOneField('PassportDetails',on_delete=models.CASCADE,related_name='employee_passport',null=False,blank=False) visa = models.ForeignKey(Visa_Details,on_delete=models.CASCADE,null=False,blank=False) class PassportDetails(models.Model): Passport_No =models.CharField(max_length=20,null=False,primary_key=True,validators=[Passport_Validation]) class Visa_Details(models.Model): VISA_NO=models.CharField(max_length=19,null=False,primary_key=True,validators=[Visa_Validators])# in admin panel we can see below buttons and features enter image description here i want same feature for my below custom buttons enter image description here i tried using inline-forms, calling models normal way but it requires URL/int:passport_id/ but when rendering it wont load it because when creating a new employee details their wont be any id, i hope iam clear. <th>Passport No:</th> <td> {{ form.passport }} </td> <div class="Add" > <a href="#" data-tip="Add Passport" onclick="PassportAction('ADD')" id="AddClick"> <box-icon name='plus-medical' color="green" size="xs"> </box-icon> </a> </div> <div class="Edit"> <a href="#" data-tip="Edit Passport" onclick="PassportAction('EDIT')" id="EditClick"> <box-icon name='edit-alt' color="green" size="xs" class="Ico"> </box-icon> </a> </div> <div class="Show"> <a href="#" data-tip="Show Passport" onclick="PassportAction('VIEW')" id="ViewClick"> <box-icon name='expand-vertical' color="green" size="xs" class="Ico"> </box-icon> </a> </div> <script> function PassportAction(action){ var selectedPassport = document.getElementById('id_passport').value; var linkElement=null; var newHref=''; if(action=='ADD'){ linkElement=document.getElementById('AddClick'); newHref="{% url 'AddPassport' %}" } else if(action=='EDIT'){ linkElement=document.getElementById('EditClick'); newHref="{% url 'EditPassport' %}?passport_id=" + selectedPassport; }else if(action=='VIEW'){ linkElement=document.getElementById('ViewClick'); newHref="{% url 'ViewPassport' %}?passport_id=" + selectedPassport; } linkElement.href = newHref; alert(selectedPassport); } </script> My Main Goal: I want to … -
Connection Django + Celery + RabbitMQ with Docker
Im having some issues to run celery tasks in my django project, I am currently using rabbitmq as the broker. When I run the "docker compose up" and everything is on, if I run "celery status" inside the django container it fails with "kombu.exceptions.OperationalError: [Errno 111] Connection refused", but if I run it on my machine it works giving me the worker, how can I fix this? Here is my docker compose: version: "3" services: db: image: postgres networks: - django volumes: - postgres_db:/var/lib/postgresql/data ports: - 5432:5432 environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres rabbitmq: image: rabbitmq:3-management-alpine networks: - django volumes: - rabbitmq_data:/var/lib/rabbitmq/ - rabbitmq_log:/var/log/rabbitmq ports: - 5672:5672 - 15672:15672 celery_worker: build: context: . dockerfile: worker.dockerfile command: celery -A loan_manager worker --loglevel=info networks: - django environment: - CELERY_BROKER_TRANSPORT_URL=amqp://guest:guest@rabbitmq:5672// - DATABASE_NAME=postgres - DATABASE_USER=postgres - DATABASE_PASSWORD=postgres - DATABASE_HOST=db depends_on: - rabbitmq django_app: build: . command: > sh -c "python3 manage.py makemigrations --noinput && python3 manage.py migrate --noinput && python3 manage.py shell < ./utils/create_superuser.py && python3 manage.py runserver 0.0.0.0:8000" networks: - django ports: - "8000:8000" environment: - CELERY_BROKER_TRANSPORT_URL=amqp://guest:guest@rabbitmq:5672// - DATABASE_NAME=postgres - DATABASE_USER=postgres - DATABASE_PASSWORD=postgres - DATABASE_HOST=db depends_on: - db - rabbitmq volumes: postgres_db: rabbitmq_data: rabbitmq_log: networks: django: Here are the docker files for … -
I cannot run python manage.py in VS code after changing my computer username
When I run python manage.py runserver in vs code. I get the message below. "No Python at 'C:\Users\user\AppData\Local\Programs\Python\Python310\python.exe'". I remembered changing my window username, I don't know if that is the cause. Could you give me an idea on how to fix this problem. Thank. -
Django get records using OuteRef filtering by max value
I have a Django model called CGDSStudy with fields name, url, and version: class CGDSStudy(models.Model): name = models.CharField(max_length=300) url = models.CharField(max_length=300) version = models.PositiveSmallIntegerField(default=1) Multiple versions of the same study can exist with the same URL, but I only want to retrieve studies of the last version. Here are three failed attempts: Attempt 1: from django.db.models import Max, OuterRef, Exists cgds_studies = CGDSStudy.objects.all() cgds_studies = cgds_studies.filter( Exists(CGDSStudy.objects.annotate(max_version=Max('version')).filter(url=OuterRef('url'), max_version=OuterRef('version'))) ) This attempt retrieves all studies instead of the studies from the last version. Attempt 2: cgds_studies = cgds_studies.filter( version=Max(CGDSStudy.objects.filter(url=OuterRef('url')).values('version')) ) This attempt raises the error "cgdsstudy.version" must appear in the GROUP BY clause or be used in an aggregate function. Attempt 3: cgds_studies = cgds_studies.filter( version=CGDSStudy.objects.filter(url=OuterRef('url')).annotate(max_version=Max('version')).values('max_version')[0] ) This attempt raises the error This queryset contains a reference to an outer query and may only be used in a subquery.. -
Django won't add the default language prefix in URL at startup
This is my first question here after 3 years of programming with Django, during which i always did all i could to solve problems by doing research. This time i'm really stuck... My issue is with a recent Django website ( url: h t t p s : // bucegipark. ro ) that should automatically add the language prefix when you access it (like for example going to this link), but it suddenly STOPPED doing that around a month ago and really cannot find the issue. I reset all language internalization settings twice. I should mention that with debug set to True it redirects to url with language prefix just fine, the issue comes up in production. When no prefix is shown after the url, database info is not either loaded. After starting the website, if i choose a language using the dropdown list i built, it redirects to that url with chosen language prefix. It does the same when i click the brand logo which has the {% url 'home' %} url attached to it and redirects to the homepage with the language prefix just fine. So theoretically, the urls.py code works fine i guess, the problem lies in … -
Trying to make an icon work while modifying a django template
How can make this icon show in my modified django template: I tried using font awesome link but it did not work the template was downloaded online and i am currently modfying it hence me encountering this issue. i triend downloading other fonts online but then none is the same as this -
Cannot translate only a model label in Django Admin
I'm trying to translate the entire Django Admin from English to French. This is my django-project below. *I use Django 4.2.1: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-models.py | |-admin.py | └-apps.py |-my_app2 └-locale └-fr └-LC_MESSAGES |-django.po └-django.mo And, this is core/settings.py below: # "core/settings.py" MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('fr', _('French')) ) And, this is core/urls.py below: # "core/urls.py" from django.contrib import admin from django.urls import path from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( path('admin/', admin.site.urls) ) And, this is my_app1/models.py below: # "my_app1/models.py" from django.db import models from django.utils.translation import gettext_lazy as _ class Person(models.Model): name = models.CharField(max_length=20, verbose_name=_("name")) class Meta: verbose_name = _('person') verbose_name_plural = _('persons') And, this is my_app1/apps.py below: # "my_app1/apps.py" from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class MyApp1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_app1' verbose_name = _('my_app1') And, this is locale/fr/LC_MESSAGES/django.po below: # "locale/fr/LC_MESSAGES/django.po" ... #: .\core\settings.py:140 msgid "English" msgstr "Anglais" #: .\core\settings.py:141 msgid "French" msgstr "Français" ... #: .\my_app1\apps.py:7 msgid "my_app1" msgstr "mon_app1" #: .\my_app1\models.py:6 msgid "name" msgstr "nom" #: … -
how can I create an E-commerce CART system using python Django
I am developing an E-commerce website and encountering difficulties in implementing a cart system. please, Can anyone guide me through the process of implementing a cart system or provide some helpful resources? Thank you. -
python/django - convert 2 unequal querysets into "context" dictionary for passing on to template rendering in detail view
new to python/django framework. have got 2 querysets ('a' and 'b') using ldid=3 a=Ld.objects.filter(id=ldid).values() b=Ld.objects.get(id=ldid).ldref.all().values() Result: type of a and b is <class 'django.db.models.query.QuerySet'> a is <QuerySet [{'id': 3, 'docref': '228689', 'deno': 'ESGF387054', 'dedt': '20200905', 'bjno': 'ESGF387054', 'bjdt': '20200905', 'ccode_id': 3, 'gcode_id': 6, 'smcd_id': 3, 'cmcd_id': 1, 'schmcd_id': 6, 'invno': '2015407629', 'invdt': '20200905', 'item': 'MOBILE', 'brnd': 'VIVO', 'pref1': 'X50 KC472228', 'pref2': '', 'invamt': '34990', 'intper': '0', 'intamt': '0', 'emitot': '18', 'emiamt': '1944', 'emiano': '6', 'emiaamt': '11664', 'lnamt': '23327', 'lnbal': '23328', 'ddt': '20201010', 'cldt': '', 'szdt': '', 'szrem': '', 'lstatus': '', 'ndeno': '462DDFGF387054', 'ntdue': '23328', 'ntrcpt': '21384', 'nbal': '1944'}]> b is <QuerySet [{'id': 3, 'rtref': '2196146', 'ldref_id': 3, 'rtno': 'E504744', 'rtdt': '20210605', 'emi': '1944', 'pen': '0', 'remlt': 'false'}, {'id': 4, 'rtref': '2196147', 'ldref_id': 3, 'rtno': 'E504745', 'rtdt': '20210605', 'emi': '1333', 'pen': '0', 'remlt': 'false'}, {'id': 5, 'rtref': '2196148', 'ldref_id': 3, 'rtno': 'E504746', 'rtdt': '20210605', 'emi': '1545', 'pen': '0', 'remlt': 'false'}]> need to convert them to single dictionary, introducing a new key 1,2,3,4 etc. and values the dictionaries from the queryset. something like `context = { 1 : {'id': 3, 'docref': '228689', etc.,}, --> from a 2 : {{'id': 3, 'rtref': '2196146', 'ldref_id': 3, 'rtno': 'E504744', etc.,}, ` for use as context … -
Migration failed in Wagtail 5.0.1 on MSSQL
after install wagtail, i have some problems how to use mssql in wagtail cms? i have error when migration wagtail when use mssql, im use wagtail v5 and django v4.2.2 its error log django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The index 'content_object_idx' is dependent on column 'content_type_id'. (5074) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]ALTER TABLE ALTER COLUMN content_type_id failed because one or more objects access this column. (4922)") is it possible use mssql for wagtail cms database? how to Solve migration to MSSQL on wagtail cms ? -
deciding a sofware stack angular+django+vite? [closed]
I work for a firm that gave me the task to select a software stack that suits our needs i already have some idea of what it is going to be but i am the only technical people in the firm so i need advice. I just got out of school so its kinda overwelming. What we need -One MPA (so ssr and seo) -Two SPA on the same domain as the MPA -A backend that works with mssql and the frontend Because it is a pretty big enterprise project and my devs are in inda and familiar with angular i want to use angular with primeNG on top. For the backend i think django will be my choice becauce it works with our database and the build in functionalities seem very nice. I would also like to use vite for faster developing time but i am not sure if it will suit my needs. The main question is can i use angular for the MPA so ssr and angular for the SPA's on the same domain, it opens a new tab when a link is clicked to the SPA. I need to hydrate some parts of pages of the … -
Django: request.POST contains only the last form in my formset
When I run pprint(request.POST), it only returns the data of the last form of my formset. Why is this happening? Here is my code. My models.py: class Order(models.Model): date = models.DateField(unique=True, blank=True, null=True) first_course = models.CharField(null=True, blank=True, unique=False, max_length=30) first_course_quantity = models.IntegerField() second_course = models.CharField(null=True, blank=True, unique=False, max_length=30) second_course_quantity = models.IntegerField() dessert = models.CharField(null=True, blank=True, unique=False, max_length=30) dessert_quantity = models.IntegerField() drink = models.CharField(null=True, blank=True, unique=False, max_length=30) drink_quantity = models.IntegerField() def __str__(self): return f"Date of order: {self.date}" My forms.py: class DisabledOptionWidget(forms.Select): def render(self, name, value, attrs=None, renderer=None): html_code = super(DisabledOptionWidget, self).render(name, value, attrs, renderer) html_code = html_code.replace(f'<option value=""', f'<option value="" disabled') return html_code class OrderForm(forms.ModelForm): first_course = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("first_course", flat=True))], widget=DisabledOptionWidget, required=False) first_course_quantity = forms.IntegerField(min_value=0) second_course = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("second_course", flat=True))], widget=DisabledOptionWidget, required=False) second_course_quantity = forms.IntegerField(min_value=0) dessert = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("dessert", flat=True))], widget=DisabledOptionWidget, required=False) dessert_quantity = forms.IntegerField(min_value=0) drink = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("drink", flat=True))], widget=DisabledOptionWidget, required=False) drink_quantity = forms.IntegerField(min_value=0) date = forms.DateField(required=False) class Meta: model = Order fields = "__all__" def save(self, commit=True): if commit: … -
Django issue with validating data in form
So I've been working my way through this tutorial, and I've run into a problem I can't figure out. I'm hoping someone can show me the way. I have a new user registration form I'm working on, and I can't get the data to validate with form.is_valid(). In views.py, the if form.is_valid() is supposed to validate the data inputted into the form, but instead it returns "Invalid" no matter what. I'm relatively new to Python and Django, so any assistance would be appreciated. views.py: # main/views.py from django.http import HttpResponse from django.contrib.auth import login from django.shortcuts import redirect, render from django.urls import reverse from main.forms import CustomUserCreationForm # Create your views here. def main(request): return render(request, 'main.html', {}) def dashboard(request): return render(request, 'users/dashboard.html') def admin(request): return render(request, 'admin') def login(request): return render(request, 'registration/login.html') def register(request): if request.method == 'GET': return render( request, 'users/register.html', {'form': CustomUserCreationForm} ) elif request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return HttpResponse('<h1>Validated!</h1>') # return render(redirect(reverse('dashboard'))) else: return HttpResponse('<h1>Invalid</h1>') forms.py: # main/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): fields = UserCreationForm.Meta.fields + ('email',) register.html: <!-- main/templates/users/register.html --> {% extends 'main.html' %} {% block content %} … -
friends help me my login system doesnt function doesnt redirect to dashboards and there is no detected errors, below are codes
please help login system doesnt function i cant login in my django system class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) username = models.CharField(max_length=150, unique=True, null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) -
django messages wont show up in template
Okey this has been asked aloooot but no answer has helped, tried tutorials and asked my student collegues for help but no one can answer why. They have looked and says it looks fine, that it could be something wrong with my django itself. I'm trying to just show a successful logged in message on my django app. I can't make it work. Please bare with me, my first django project and im a student that suffers real bad from imposter syndrome, play nice :) My folder setup home <--app projectfolder media static with images and css folder users <-- app So to start off i use djangos built in auth system. Works great on the site. Using djangos own form for login and logout. Whats really weird is that the div dosent even show up when i render the page and check inspect, nothing in console either. views.py in users from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect def login_user(request): """ Login form and messages """ if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, "You have been … -
Django socket communication
I have a Django server with a list of devices and their corresponding MAC addresses. I have also created firmware for these devices, and I want to license them using my Django webserver in order to prevent the firmware from being copied onto other chips. The problem I'm facing is that the data will be sent to my web backend every 10 minutes (which could be reduced to 1 minute in the future). Additionally, I want the communication between the devices and the web server to be two-way, so that I can disable the devices at any time by sending a message. I'm unsure of how to handle this situation. Would Django channels be a useful solution in this case, and if so, how can I implement them? The firmware is written in C++. -
How can I edit the contents of a datalist element based on a selection made in another dropdown
I'm writing a section of a Django template file for inputting multiple fields using dropdown menus. Two of the sections are 'State' and 'County'; currently the county dropdown list is just a datalist of all the counties in the entire country, but I would like to use some Javascript to rewrite the datalist whenever a selection is made in the State dropdown option to show only the counties in that particular state. Any suggestions are appreciated! -
Overidding dj-rest-auth Registration Serializer
I am trying to override the register serializer, I want to add a name field but the default view still shows this is my configuration in settings.py ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'none' REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'accounts.serializers.CustomRegisterSerializer' } my url looks like this urlpatterns = [ path('', include('dj_rest_auth.urls')), path('registration/', include('dj_rest_auth.registration.urls')), ] while my serializer from dj_rest_auth.registration.serializers import RegisterSerializer class CustomRegisterSerializer(RegisterSerializer): name = serializers.CharField(max_length=100) email = serializers.EmailField() class Meta: model = get_user_model() fields = [ 'name', 'email' ] -
How to type hint self.client.patch in django.test.TestCase?
I am wondering what type hint to use as the output of _request in the following Django test case: from django.test import TestCase class SomeTestCase(TestCase): def _request(self, id: int, update_data: dict[str, Any]) -> ?: url = reverse('path', kwargs={'id': id}) return self.client.patch(url, update_data) ... -
Django-Rest - How to create URL & View to extract "GET" query parameters in different formats?
I have an application that is sending a GET request in the form of /myapi/details/?id="myid". Currently my Django-Rest server is setup to receive requests as follows: urls.py urlpatterns = [ path('/details/<str:id>/', views.details.as_view()), ] views.py class details(APIView): def get(self, request, id): //id contains the data This works fine when sending a GET request as /myapi/details/"myid". To try and also receive requests with /?id="myid" I added path('/details/?id=<str:id>/', views.details.as_view()), to urlpatterns, but sending the request still hits the other URL regardless of the order. What would be the correct way to go about this? Ideally, I would like to accept both /"myid" and /?id=<str:id> formats. -
How to filter table with class name in html?
If class = "node focused" , how can i filter the data with its id in table table-bordered table-sm table-active in base.html i want to see deatils only selected node in my table. {d.1} = div id <div id="TEM01" data-parent="ATK" class="node focused"><div class="title" style="width:200px"><i class="oci oci-leader symbol"></i>ATK</div> <div id="TEM02" data-parent="ATK" class="node"><div class="title" style="width:200px"><i class="oci oci-leader symbol"></i>ATK</div> chart.js below nodeClickHandler: function (event) { this.$chart.find('.focused').removeClass('focused'); $(event.delegateTarget).addClass('focused'); }, css below .orgchart .node.focused { background-color: rgba(217, 83, 79, 0.8); } base.html below. <body> <div id="chart-container"></div> {% block content %} {% endblock %} <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.orgchart.js' %}"></script> <script src="{% static 'js/bootstrap.js' %}"></script> <div id=" row justify-content-md-center"> <div class="col-sm"> <h5 align="center"><i><span style="background-color: #262626" class=" badge badge-info">Node Information </span></i> </h5> <table class="table table-bordered table-sm table-active"> <tr> <th>DVS</th> <th>DWH</th> <th>AO_Trap</th> <th>BO_Trap</th> <th>Info</th> </tr> <tr> <tbody> {% for d in alltables %} <tr> <td>{{d.1}}</td> <td>{{d.1}}</td> <td>{{d.2}}</td> <td>{{d.3}}</td> </tr> {% endfor %} </tbody> </tr> </table> -
Django rest framework and fetch don't work
I am trying to make a simple api where a user writes something in an input, presses a button and a new instance is added in a database. To do this I am using react and django rest framework. App.js function handleClick() { fetch("http://127.0.0.1:8000/post", { method: "POST", body: { title: name, name:name } }) } return ( <> <form> <input type='text' value={name} onChange={handleChange} /> <button onClick={handleClick}>OK</button> </form> </> ); views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response() But when I press the button I get manifest.json:1 GET http://127.0.0.1:8000/manifest.json 404 (Not Found) and manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. in javascript. In django I get manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. Also I am using npm run build for javascript and manifest.json is in public folder.