Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot save a modelform using Django Crispy Forms
I cannot save my form because the payload is not formatted correctly.. I'm using HTMX for rendering the form in a modal here's the code: forms.py class RecipeForm(forms.ModelForm): title = forms.CharField( label="Titolo", ) method = forms.CharField( widget=forms.Textarea(), label="Procedimento", ) tags = CustomTagsMultipleChoice( queryset=Tag.objects.all(), widget=forms.CheckboxSelectMultiple, label="Tag", ) hero_image = forms.ImageField( label="Immagine", ) class Meta: model = Recipe fields = ["title", "method", "tags", "hero_image"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs = { "hx-post": reverse_lazy("recipes:recipe_create"), "hx-target": "#dialog", } self.fields["tags"].required = False self.fields["method"].required = False self.fields["hero_image"].required = False self.fields["tags"].label = False self.helper.layout = Layout( FloatingField("title"), FloatingField("method", css_class="fl-textarea"), "hero_image", InlineCheckboxes("tags"), Div( Submit("submit", "Salva"), Submit("button", "Cancella", css_class="btn btn-danger", data_bs_dismiss="modal"), css_class="text-end", ), ) views.py @login_required def recipe_create(request): if request.method == "POST": form = RecipeForm(request.POST,request.FILES) if form.is_valid(): form.save() return HttpResponse(status=204, headers={"HX-Trigger": "recipeSaved"}) form = RecipeForm(request.POST,request.FILES) context = {"recipe_form": form} return render(request, "recipes/partials/_recipe_create.html", context) form = RecipeForm() context = {"recipe_form": form} return render(request, "recipes/partials/_recipe_create.html", context) _recipe_create.html {% load crispy_forms_tags %} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Aggiungi una ricetta</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button> </div> <div class="modal-body"> {% crispy recipe_form %} </div> </div> if I print request.POST I get this badly formatted payload <QueryDict: {'------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name': ['"submit"\r\n\r\nSalva\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="csrfmiddlewaretoken"\r\n\r\n0DWNbShUV0r8mFSPUNQaSQapC38FQFrMeOtmqFY64H4x3ReOuG7suKqUip7sSpqv\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="title"\r\n\r\ntest\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="method"\r\n\r\n\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g--\r\n']}> the form … -
Why Nginx is Serving my django app in port 8000 instead of 80?
i have created a app using django https://github.com/pyalz/video_app . I run this application now using django compose build django compose up . When i open http://0.0.0.0:8000 its coming with static files. when i open http://0.0.0.0:80 its not showing me static files **Docker compose ** version: '3.7' services: django_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - django_gunicorn volumes: static: Docker File FROM python:3.10.0-alpine RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./video_app /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] Entry.sh #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input DJANGO_SUPERUSER_PASSWORD=$SUPER_USER_PASSWORD python manage.py createsuperuser --username $SUPER_USER_NAME --email $SUPER_USER_EMAIL --noinput gunicorn video_app.wsgi:application --bind 0.0.0.0:8000 NGINX Docker file FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf Default.conf upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } } enter image description here enter image description here Could you please help me resolve this issue -
Django How add math result from form in Model.objects.create
I'm trying to divide one value by another from the form and write the result. But it doesn't work def add_project(request): form_address = AddressForm(request.POST or None) form_project = ProjectForm(request.POST or None) form_detail = ProjectDetailForm(request.POST or None) if request.method == 'POST': if form_address.is_valid() and form_project.is_valid() and form_detail.is_valid(): address_clean = form_address.cleaned_data project_clean = form_project.cleaned_data detail_clean = form_detail .cleaned_data a = Address.objects.update_or_create(**address_clean) p = Project.objects.create( address = a[0], manager = request.user, file = project_clean['file'], sq = project_clean['sq'], rent_tax = project_clean['rent_tax'] ) sq_price = project_clean['rent_tax'] / project_clean['sq'] ProjectDetail.objects.create( project = p, sq_price = sq_price, **detail_clean ) return redirect("crm:homepage") context = {'form_address':form_address, 'form_project':form_project, 'form_detail':form_detail,} return render(request, 'crm/add_project.html', context) I try sq_price = project_clean['rent_tax'] / project_clean['sq'] The print command outputs a number. But Django says it is an error: create_method..manager_method() got multiple values for keyword argument 'sq_price' Traceback project_clean { 'file': 'https://aaa.com/zzz.zip', 'rent_tax': 1548, 'sq': Decimal('325')} -
Django Social account is redirected to gitlab.com instead of gitlab.local
Hello I have installed gitlab locally on my own server. I am trying to make django settings with django social app with the steps specified in the readthedocs readthedocs link to enter through readthedocs gitlab accounts, but for some reason my server connects to gitlab.com when I say connect with gitlab via readthedocs instead of https://gitlab.local. I need to redirect it to my server. How do I do this, the django docs say the following steps but I have no idea how and where to change it. https://django-allauth.readthedocs.io/en/latest/providers.html#gitlab GitLab The GitLab provider works by default with https://gitlab.com. It allows you to connect to your private GitLab server and use GitLab as an OAuth2 authentication provider as described in GitLab docs at http://doc.gitlab.com/ce/integration/oauth_provider.html The following GitLab settings are available, if unset https://gitlab.com will be used, with a read_user scope. GITLAB_URL:Override endpoint to request an authorization and access token. For your private GitLab server you use: https://your.gitlab.server.tldSCOPE:The read_user scope is required for the login procedure, and is the default. If more access is required, the scope should be set here. which file do I need to modify to make the following setting or what is the way to do it? Example: SOCIALACCOUNT_PROVIDERS … -
Conditional Aggregation of Foreign Key fields
I would like to get the count of foreign key objects with django, the foreign key itself will change conditionally. So, something like the example below. Game.objects.annotate( filled=models.Case( models.When( GreaterThan( models.F("size_max"), ( models.Count( models.Case( models.When( participant_type=1, then="players" ), models.When( participant_type=2, then="teams", ), ), ), ), ), then=1, ), default=0, ) ) What I'd like to achieve is this: players and teams are reverse foreign keys to Game. I want to check whether the size_max field of Game exceeds the count of players or teams depending on the participant_type. How would I go about achieving this? Any help would be appreciated. The above query results in an error - it introduces a GROUP BY with the model name in it. So, something like GROUP BY ('Game'), "game"."id" which I have no clue why this happens. -
Django RestFramework - convert list to dict
I'm translating an API in Java to DRF and the consumption will be in a data.py Using DRF API ind = requests.get(base_url + "get_ind?ind_id={}".format(ind)) print(ind.json()) [{ "id": 1, "ind_id": 1, "co_ind": "Some String", "no_ind": "Some String", "ds_ind": "Some String", "ds_not_ind": "", "uni_id": 1, "per_id": [ { "id": 7, "no_per": "Some String", "tip_var": "", "co_per": "Some String", "no_cat": "", "per_id": 7, "uni_id": 1 }, { "id": 9, "no_per": "Some String", "tip_var": "", "co_per": "Some String", "no_cat": "", "per_id": 9, "uni_id": 1 }, ], "co_mod": "Some String" }] I want: Using Java API ind = requests.get(base_url + "get_ind?ind_id={}".format(ind)) print(ind.json()) { "id": 1, "ind_id": 1, "co_ind": "A", "no_ind": "DOMÍCILIOS QUE POSSUEM EQUIPAMENTO TIC", "ds_ind": "Total de domicílios", "ds_not_ind": "", "uni_id": 1, "per_id": [ { "id": 7, "no_per": "Proporção de domicílios que possuem equipamentos TIC", "tip_var": "", "co_per": "DIC_TV", "no_cat": "", "per_id": 7, "uni_id": 1 }, { "id": 9, "no_per": "Proporção de domicílios que possuem equipamentos TIC", "tip_var": "", "co_per": "DIC_RADIO", "no_cat": "", "per_id": 9, "uni_id": 1 }, ], "co_mod": "A" } This is the view.py: class GetIndFilter(SearchFilter): def filter_queryset(self, request, queryset, view): queryset = super().filter_queryset(request, queryset, view) ind_id = request.GET.get('ind_id') if(ind_id != ''): result = Inds.objects.filter(ind_id = ind_id) return result class GetIndViewSet(viewsets.ModelViewSet): queryset … -
Подключение приложения с github в django-проект [closed]
Всем привет, я нуб. Делаю свой проект на Django в свободное от работы время. Я хочу подключить в строку для ввода адреса на странице плагин, который по опенсорсу распространяется на гитхабе. Он использует jquery. Я не могу понять куда мне его втыкать в проекте и где что указывать, чтобы было весело. Просмотрев несколько видео и прочитав несколько статей, я клонировал гит репозиторий в папку со статикой в джанго, а в шаблоне указал к ней путь. И попробовал метод из этого стороннего приложения применить к инпуту. Начал с того, что получаю инпут, около которого текстом написан мой метод, начал шевелить подключение JS кода к шаблону, избавился от ошибок и пришёл к тому же результату. Пожалуйста, помогите, я за деньги готов по зуму созвониться чтобы получить ответ. {% load static %} <!DOCTYPE html> <html> <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script> <script src={% static 'gameslist/jquery/jquery.fias.min.js' %} ></script> <input type="text"> $('text').fias({ oneString: true }); </html> Получаю на странице это enter image description here -
Django/Python/Plotly Icon level
I am working on a dashboard and I would like to use "icon rating" (is there a name for this?). I mean having a range of icons and see if they are full/empty/coloured in a scale of 1 to 4/5 or whatever number of icons. The most usual case is done with stars in many reviews but I would like to do it with other icons related to my dashboard topic. What's the best way to do it? I am using Django/Python/Plotly for this dashboard so tools related to these would be best. -
Django Rest Framework unique field constraint on array
So, I'm trying to make an endpoint where I insert a list of objects. My issue is the behavior and response when inserting duplicates. What I want to accomplish is to: Send the duplicate lead external_id(s) in the error response Insert any other non duplicated object I'm pretty sure this logic (for the response and behavior) could be accomplished in the modifying the serializer.is_valid() method... but before doing that, I wanted to know if anyone had experience with this kind of request.. Maybe there is a "clean" way to do this while keeping the unique validation in the model. Data on OK response: [ { "external_id": "1", "phone_number": "1234567890" } ] Data for a FAIL request (1 is dup, but 2 should be inserted. Expecting a response like "external_id" : "id 1 is duplicated"): [ { "external_id": "1", "phone_number": "1234567890" }, { "external_id": "2", "phone_number": "2234567890" } ] models.py class Lead(models.Model): external_id = models.CharField(max_length=20, unique=True) phone_number = models.CharField(max_length=50) serializers.py class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' def create(self, validated_data): lead = Lead.objects.create(**validated_data) log.info(f"Lead created: {lead.import_queue_id}") return lead views.py class LeadView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @extend_schema(description="Insert campaign data", request=LeadSerializer(many=True), responses=None, tags=["Leads"]) def post(self, request): serializer = … -
Iterator should return strings, not bytes (the file should be opened in text mode)
this is my code.. def import_excel(request): if request.method == 'POST': person_resource = PersonResource() dataset = Dataset() new_person = request.FILES['myfile'] if not new_person.name.endswith('csv'): messages.info(request,'Wrong format') return render(request,'upload.html') imported_data = dataset.load(new_person.read(),format='csv') for data in imported_data: value = Person( data[0], data[1], data[2] ) value.save() return render(request,'upload.html') while importing the csv file to the database getting the error: iterator should return strings, not bytes (the file should be opened in text mode) like this -
Python django Failed to create a virtualenv
I was trying to create a virtual env with python3. But it failed to create new. But the existing virtual env are working fine. Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 82, in _get result = get_wheel( File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\acquire.py", line 23, in get_wheel wheel = from_bundle(distribution, version, for_py_version, search_dirs, app_data, do_periodic_update, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\bundle.py", line 17, in from_bundle wheel = periodic_update(distribution, of_version, for_py_version, wheel, search_dirs, app_data, per, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 35, in periodic_update handle_auto_update(distribution, for_py_version, wheel, search_dirs, app_data, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 69, in handle_auto_update embed_update_log.write(u_log.to_dict()) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\app_data\via_disk_folder.py", line 154, in write self.file.write_text(json.dumps(content, sort_keys=True, indent=2)) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\pathlib.py", line 1154, in write_text with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f: File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\pathlib.py", line 1119, in open return self._accessor.open(self, mode, buffering, encoding, errors, PermissionError: [Errno 13] Permission denied: 'C:\\Users\\DELL\\AppData\\Local\\pypa\\virtualenv\\wheel\\3.10\\embed\\3\\pip.json' fail -
Can we import the modules/functions from stand alone python code to DJango framework?
I have a parent directory under which we have multiple directories where standalone Python codes are developed and these py files are executed with parameters(ex - python --env=prod file_name.py) and in the same parent directory I have the directory of DJango code and the DJango code are importing the modules from standalone python modules. When I try to start the Django server using the command - "python manage.y runserver" I get the message - "manage.py: error: unrecognized arguments: runserver". Can you please help if importing of standalone python modules are allowed or not into the Django and if allowed then how we can achieve it. -
Why docker compose dosent create container with container_name
i create Dockerfile and docker-compose.yml. i build image with tag "django-image" Dockerfile: `FROM python:3 WORKDIR /code-django COPY . /code-django RUN pip3 install -r requirements.txt` docker-compose.yml: services: db: image: postgres container_name: db-money volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: image: django-image container_name: money volumes: - .:/code-django ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db in docker compose i have 2 services,"db" and "web". docker compose creates "db" with "container_name: db-money" and starts it. but compose dosent create anothe container with "container_name: money". why the second "container_name" dosent work?? enter image description here -
unable to install backports.zoneinfo
when i execute 'pip install -r requirements.txt ' this is displayed and i can't download backports.zoneinfo . `(venv) ##########@Air-de-#### ###### % pip install -r requirements.txt ... lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found #include "Python.h" ^~~~~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Successfully built PyYAML Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects (venv) ######@Air-de-###### ####### % pip install backports.zoneinfo ... lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found #include "Python.h" ^~~~~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects` -
Django Sitemap Generates https:// Twice in Development
The example.com/sitemap.xml is returning loc with double https:// making the generated sitemap to be incorrect/unacceptable. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://https://example.com</loc> <changefreq>monthly</changefreq> <priority>1.0</priority> </url> I've tried changing the protocol in the sitemaps.py file from https to http but that only appends http:// in front of the https://example.com/. Any ideas? -
Django 1.11.29. When sending long string on subject, Django inserts \t and extra space after comma
Django 1.11.29. When sending long string on subject, Django inserts \t and extra space after comma. I tried sending emails setting to QP, 8bit. But Django if subject length is more than 70 chars, it inserts extra space and tabulation From nobody Fri Jan 20 13:25:04 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Subject: Earth - Earth population is 4, 652, 123 people and digest is d3ea33dbe135a35fdde8984d1d920b8e6149526ed1fb5c9c656e8834d85d3a4e From: me@me.com To: me1@me.com Date: Fri, 20 Jan 2023 13:25:04 -0000 Message-ID: <20230120132504.88256.54199@medet-Lenovo-ideapad-330-15IKB> Content-Transfer-Encoding: quoted printable Subject: Earth - Earth population is 4, 652, 123 people and digest is d3ea33dbe135a35fdde8984d1d920b8e6149526ed1fb5c9c656e8834d85d3a4e Content-Type: text/html; charset=UTF-8 MIME-Version: 1.0 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tem= por incididunt ut labore et dolore magna aliqua. Suscipit tellus mauris a d= iam maecenas sed enim ut. In vitae turpis massa sed. Dictum varius duis at = consectetur lorem. At volutpat diam ut venenatis tellus in metus vulputate = eu. Vel quam elementum pulvinar etiam non quam lacus suspendisse. Lacus lao= i've tested and tried a lot of things, but i dont know how to resolve to sending long subjects. I also checked and its not helps https://code.djangoproject.com/ticket/7747 i've tested and tried a lot … -
I can't loop trough a dictionnary in my Django Template
I'm trying to loop trough a dictionnary to create a simple table with the keys in a column and the values in the other. So in my view I create the dictionnary vegetables_dict. I loop trhough the "items" of a "cartitem". If the item doesn't alrady exists I created a key with the name of a ForignKey of "item" and a value with its attribute quantity. Otherwise I increment the already existing key with the corresponding quantity def dashboard_view(request): carts = Cart.objects.filter(cart_user__isnull = False) cartitems = CartItem.objects.all() vegetables_dict = {} for item in cartitems: if item.stock_item.product_stockitem.name in vegetables_dict: vegetables_dict[item.stock_item.product_stockitem.name] += item.quantity else : vegetables_dict[item.stock_item.product_stockitem.name] = item.quantity context = { 'carts' : carts, 'cartitems' : cartitems, 'items' : vegetables_dict } return render(request, "maraicher/dashboard.html", context) In the template i Tried : <table> <thead> <tr> <th colspan="2"> Récapitulatif de récole</th> </tr> </thead> <tbody> <th>Produit</th> <th>Quantité</th> <div>{{items}}</div> {% for key, value in items.item %} <tr> <td>{{key}}</td> <td>{{value}}</td> </tr> {% endfor %} </tbody> </table> {{items}} render the dictionnary but the table is empty. Any idea what is happening? I aslo tried {% for item in items %} <tr> <td>{{item}}</td> <td>{{item.item}}</td> </tr> {% endfor %} -
What is the main difference between making a query using Manager.raw() method and connection.cursor() method?
I need to know which one is faster and why, and I also need to know the cases for each one. I try them both but I can't find the difference. -
What is the best experinces to structure a Django project for scale?
Django is great. But as we add new features, as our dev team grows, the software needs to be stable on production, things can get quite messy. We are going to want some common patterns, derived from experience, on how to structure your Django project for scale and longevity. What is your suggestion? Indeed, there are many models and patterns for development, but we want to know your experiences. -
session based django social
I'm using social-auth-app-django for authenticate with google. The process working fine and the user is register in the DataBase. The problem begins when I'm trying to login the users automatically when they register with Google. The users keeps to be unauthenticated in the session. Here is my current configurations using social-auth-app-django and djoser: settings.py: AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend' ) DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True, 'SEND_CONFIRMATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'CREATE_SESSION_ON_LOGIN': True, 'SOCIAL_AUTH_TOKEN_STRATEGY': 'members.social_token.TokenStrategy', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [ 'http://localhost:3000/google' ], 'SERIALIZERS': { 'current_user': 'members.serializers.UserCreateSerializer', } I think the most relevant part is the SOCIAL_AUTH_TOKEN_STRATEGY. Where the members.social_token.TokenStrategy is: from django.contrib.auth import login from django.http import HttpRequest from django.conf import settings from importlib import import_module class TokenStrategy: @classmethod def obtain(cls, user): from rest_framework_simplejwt.tokens import RefreshToken from six import text_type refresh = RefreshToken.for_user(user) request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) session_key = None request.session = engine.SessionStore(session_key) login( user=user, request=request, ) user.is_active = True return { "access": text_type(refresh.access_token), "refresh": text_type(refresh), "user": user, } I can see that the sessionid and the csrftoken is been saved in the browser cookies and in the TokenStrategy the request.user.is_authenticated equals to true. My problem is that for all the following requests the value of the request.user.is_authenticated keeps … -
Overriding django admin get_queryset()
I have two models which is one of them proxy model. In admin I registered both and overrided get_queryset() method but it is not working as expected. admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(language='en') @admin.register(ProxyCategory) class ProxyCategoryAdmin(CategoryAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(language='zh') In admin page ProxyCateegoryAdmin not showing objects, if I remove get_queryset() from CategoryAdmin, it works but wanted filter both of them. Thanks in advance -
Django ViewSet, get data from model without foreign key
My Models def ModelA(models.Model): id = models.CharField(primary_key=True, max_length=50) val_a = models.CharField(db_index=True, max_length=100) val_b = models.CharField(db_index=True, max_length=100) modelB = models.ForeignKey(modelB, on_delete=models.CASCADE, db_constraint=False) def ModelB(models.Model): id = models.CharField(primary_key=True, max_length=50) val_c = models.CharField(db_index=True, max_length=100) val_d = models.CharField(db_index=True, max_length=100) def ModelC(models.Model): id = models.CharField(primary_key=True, max_length=50) val_e = models.CharField(db_index=True, max_length=100) modelB = models.OneToOneField(ModelB, on_delete=models.CASCADE, null=False, blank=False) My ViewSet class ModelAViewSet(ListDataResponseMixin, APIKeyViewSet): endpoint_permissions = [APILicenseKeyPermission.Codes.A] queryset = ModelA.objects.all() serializer_class = ModelASerializer filterset_class = ModelAFilter filter_backends = [DjangoFilterBackend] My Serializer class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = ( "id", "val_a", "val_b" ) When querying ModelA I would like to get val_e from ModelC. I am learning django, and previously when I needed to do something like this, I would use select_related, however, since there is no clear path from ModelA -> ModelC using foreign keys, I am not sure how to proceed. (My base models cannot change). How would I modify my ViewSet to include the needed ModelC data in my queryset? And then for my ModelASerializer I would like to just be able to add in val_e. -
How to get all the observed Elements as we scroll down using the intersection Observer?
Ok, so i am getting Only 6 divs as i load my webpage, and when i scroll down, the other 6 get loaded (Lazy load), but my Observer does not catch it whatsoever, What could be the Problem here ? I have tried the Intersection Observer and load them at the end when all the body Is loaded. My JS Code Using Intersection Observer: var targets = [...document.getElementsByName('item-id')]; const options = { }; let clickedId_test; const observer = new IntersectionObserver(function(entries, observer){ entries.forEach(entry => { if (!entry.isIntersecting) { return; } clickedId_test = entry.target console.log(clickedId_test) }); }, options); targets.forEach(like_button => { observer.observe(like_button); }) My Images Getting 1st 6 ids Even after scrolling only get 1st 6 ids -
1062, "Duplicate entry 'admin1' for key 'username'"
models.py class CustomUser(AbstractUser): user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student")) user_type=models.CharField(default=1,choices=user_type_data,max_length=10) class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() username = models.CharField(max_length=30) email = models.EmailField(max_length=100) password = models.CharField(max_length=100) fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) forms.py class palForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model=palabout fields =['username','password','email','fname','lname','dob','gender','profileImage'] views.py from .forms import palForm def add_form(request): form = palForm(request.POST, request.FILES) username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") if request.method == "POST": form = palForm(request.POST , request.FILES) user=CustomUser.objects.create_user(username=username,password=password,email=email,user_type=1) if form.is_valid() : try: form.save() messages.success(request,"Successfully Added") return render(request,"home.html") except: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html") else: form=palForm() return render (request,"home/pal-form.html",context={"form":form}) Error: Traceback (most recent call last): File "C:\Users\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Desktop\myschool\views.py", line 19, in polabout CustomUser.objects.create_user(username=username,password=password,email=email,user_type=3) File "C:\Users\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 161, in create_user return self._create_user(username, email, password, **extra_fields) File "C:\Users\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 155, in _create_user user.save(using=self._db) File "C:\Users\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 68, in save super().save(*args, **kwargs) File "C:\Users\Anaconda3\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "C:\Users\Anaconda3\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "C:\Users\Anaconda3\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "C:\Users\Anaconda3\lib\site-packages\django\db\models\base.py", line 1047, in _do_insert return manager._insert( File "C:\Users\Anaconda3\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, … -
DRF: Which if better to create custom structure of response in Serializer/ModelSerializer?
I am currently making a simple CRUD application on Django Rest Framework. I need to return a response to the client for any request in a specific structure. For example, if a client makes a POST request to create a new record and it was executed successfully, then API needs to return such structure: { "data": [ { "id": 1, "email": "bobmarley@gmail.com", } ], "error": {} } Let's say the problem is related to the model field. In this case, the API should return such a structure: { "data": [], "error": { "email": [ "This field is required." ] } } If the problem is not related to the model field, then it is necessary to return to the client such a structure where there would be a description of the error: { "data": [], "error": { "non_field_errors": [ "Description of the error." ] } } My current code returns an incorrect structure. Should I configure all this at the serialization level? { "data": [], "error": { "non_field_errors": [ "{'email': [ErrorDetail(string='person with this email already exists.', code='unique')]}" ] } } models.py: class Client(models.Model): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) class Meta: db_table = "clients" def __str__(self): return self.email serializers.py: class …