Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM filter by a list and then get the last created item
How to write the most efficient Django ORM query for the following scenario? I need to get items based on a list of accountIds, but it will return duplicate records with the same accountId because accountId is not the primary key. Then I will need to remove the duplicates by only returning the last created record in the queryset. I can use a for loop to loop through the list of accountIds and filter by each accountId and then order by the created date and get the latest one. However, with this approach, I will be calling the database so many times. There are more than 200 account Ids. Are there better ways of doing this? -
Django google recaptcha validation in a template without form
I want to stop click fraud on my website with redirecting user to recaptcha page but the problem is I can't put my validation code in views.py because I'm returning the rendered page so how I can get the response from captcha and then validate the response. robot_detection.py: def ref(result): if(result == True): return escape(external_url) if(result == False): return [False, external_url] if(result == 0): return "product not found" views.py: @csrf_exempt def robot(request, seller_id): seller = Seller(request) result = seller.ref(seller_id, request.GET.get('url', 0)) response = JsonResponse({'result':result} ,safe=False , status=200) if len(result) > 1: if result[0] == False: response = render(request, 'captcha.html') response['Access-Control-Allow-Origin'] = '*' return response response = redirect(result) response['Access-Control-Allow-Origin'] = '*' return response captcha.html <!DOCTYPE html> <html> <head> <title> im not a robot </title> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <meta charSet="utf-8" /> <meta httpEquiv="content-language" content="fa" /> <meta name="language" content="fa" /> <meta httpEquiv="Content-Type" content="text/html;charset=UTF-8" /> </head> <body> <div > <form method="post"> {% csrf_token %} {{ form.as_p }} <script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script> <div id='sub' class="g-recaptcha" data-sitekey="" ></div> </form> </div> </body> </html> captcha validation code: recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': "", 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) captcha_response = urllib.request.urlopen(req) captcha_result = json.loads(captcha_response.read().decode()) if captcha_result['success']: response = … -
Append an object to a list with django GenericViewSet
I wrote a many-to-many field for my model but when I try to write an updated view with generic-view-set don't append the new obj just replace it,how can I write to append the new obj to list, my model: class Portfolio(models.Model): name = models.CharField(max_length=50, blank=False, null=True, default='portfolio') user = models.ForeignKey('accounts.User', on_delete=models.DO_NOTHING, related_name='investor') assets = models.ManyToManyField(Assets, related_name='portfolio_assets') def __str__(self): return self.name Serializer class PortfolioUpdateSerializer(serializers.ModelSerializer): class Meta: model = Portfolio fields = ['id', 'name'] View class PortfolioAssetsUpdate(mixins.UpdateModelMixin, viewsets.GenericViewSet ): queryset = Portfolio.objects.all() serializer_class = PortfolioAssetsUpdateSerializer def put(self, request, pk): return self.update(request, pk) Now my problem is when I update my portfolio, a new object replaces to old one, I need to append new to old,I really don't have any idea -
Value of a cell equal to value in another table in Django & Sqlite
I have two tables - Goal & Plan. Plan table has a column "Year". Goal table also has a column "Year". I want value of Goal table's year to be equal to Plan table's year by default. Plan and Goal have 1 to many relationship. As you can see, in the second row of Goal table, the value of "Year" field is set manually while value of first row should be default and it should be 2022 because the plan Id 13's year field value is 2022. Also, when I change the Plan Id 13's year from 2022 to - say 2024 - it should propagate into Goal table too. Is it achievable at all in database or I need to handle it in application layer? -
Save object with a name instead of a class name in Django database
I have a strange problem. check the image here. You can see in the registration table it save each entity with the name 'Registration Object' not with the username. What I want is this. THe code is here models.py from django.db import models # Create your models here. class Registeration(models.Model): name = models.CharField(max_length=200, null=False, blank=False) email = models.EmailField(max_length = 254,null=False, blank=False) department = models.TextField(max_length=200, null=False, blank=False) password=models.TextField(max_length=60) def _str_(self): return self.email -
How to add an extra dictionary to ModelViewset response?
using the model class Sim(modesl.Model): iccid = models.CharField(max_length=64) carrier = models.CharField(max_length=50) status = models.CharField(max_length=100) class Meta(object): app_label = "app" verbose_name = "Sim" class JSONAPIMeta: resource_name = "sim" external_field = "id" using the view : class SimView(viewsets.ModelViewSet): queryset = Sim.objects.all() serializer_class = SimSerializer using serializer: class SimSerializer(serializers.ModelSerializer): class Meta: model = Sim fields = "__all__" for /get/ { "links": { "first": "some link", "last": "some link" "next": null, "prev": null }, "data": [ { "type": "sim", "id": "1", "attributes": { "carrier": "Vodaphone", "iccid": "12345678912345678912", "status": "UnManaged", } } ], "meta": { "pagination": { "count": 1, "limit": 20, "offset": 0 } } } Now I want a dictionary "license_info" to be sent in the response which should appear only once in response, so the response may look like: { "links": { "first": "some link", "last": "some link" "next": null, "prev": null }, "data": [ { "type": "sim", "id": "1", "attributes": { "carrier": "Vodaphone", "iccid": "12345678912345678912", "status": "UnManaged", } } #Either add here { "license_info":"some value" } ], "meta": { "pagination": { "count": 1, "limit": 20, "offset": 0 } } #Or Add here "license_info":{ "some key value pairs" } } I tried to make license_info as property but this was getting repeated for … -
Bootstrap - How to center the contents of a navbar with a collapse button?
Currently have this navbar <!--Ignore--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container-fluid d-flex justify-content-center"> <a class="navbar-brand text-center" href="{% url 'Home' %}"><img class="center" src="{% static '/images/PawPrint.png'%}" alt="" width=30px></a> </div> </nav> <!--Main navbar--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container-fluid d-flex justify-content-center"> <a href="">Home</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> {% comment %} <div class="collapse navbar-collapse" id="navbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> </ul> </div> {% endcomment %} </div> </nav> Which centers Home the way I want it to But then when I want to properly add my things under the collapse button it shifts to the left despite the justify-content-center on the container <!--Logo "Navbar"--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container-fluid d-flex justify-content-center"> <a class="navbar-brand text-center" href="{% url 'Home' %}"><img class="center" src="{% static '/images/PawPrint.png'%}" alt="" width=30px></a> </div> </nav> <!--Main navbar--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container-fluid d-flex justify-content-center"> {% comment %} <a href="">Home</a> {% endcomment %} <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> </ul> </div> </div> </nav> How do I properly center the contents of a navbar? -
How to upload an image withouth form.is_valid in django
I need to know is there a specific way to upload an image without form.is_valid in django . Can someone please help me to solve this. Thanks -
Can't use Django website on subdomain with WordPress on main domain, GoDaddy
I have build a booking system using django and I have successfully hosted the website on my subdomain(appointment.xyz.com). Next I build a Website for the same organisation using WordPress and hosted on the main Domain (www.xyz.com). When I again loaded my booking website hosted on sub domain,the website won't load and shows this error: Forbidden You don't have permission to access this resource. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request. What am I missing here? The problem started when I install WordPress on my Main domain.All I did was just install WordPress from cPanel. Please help! -
Django: Get list of checked elements from a select2 field
I have a select2 multiple select dropdown list and I gave it a name="specialties_kw". The <option> value has the ID of the selected object. In my Django view, I get the data from that dropdown by calling request.POST.get('specialties_kw'). What I get as data is the id of the last selected item, and not all of them. I want to get the list of all the IDs that are checked. Here are my codes: HTML: <div class="form-group"> <label class="form-label">Extra specialties</label> <select multiple="multiple" class="filter-multi" name="specialties_kw"> {% if cdoctor.specialties.all is None %} <option selected="selected" value="0">N/A</option>{% endif %} <option selected="selected" disabled="disabled">{{ cdoctor.primary_specialty }}</option> {% for s in ospecialties %} <option {% if s in cdoctor.specialties.all %} selected="selected" {% endif %} value={{ s.id }}>{{ s.title }}</option> {% endfor %} </select> </div> DJANGO VIEWS: specialties = Specialty.objects.all() ospecialties = Specialty.objects.filter().exclude(title=doctor.primary_specialty.title) ... os = request.POST.get('specialties_kw') print(os) # gives me the ID of the last checked element -
Is it necessary to explicitly indicate the WORKDIR for each command in my Dockerfile?
I have the following file structure: Dockerfile: # syntax=docker/dockerfile:1 FROM python:3.8-slim-buster WORKDIR /home/pos COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY /src /src CMD ["python", "src/manage.py", "runserver"] I expect that the content of the src/ folder will be copied to the same path in the container (home/pos/src/) but only the requirements.txt are copied to that path, the content of the /src folder is being copied to the "root" (/), so I need to change the command to: COPY /src /home/pos/src It is necessary to set the WORKDIR for each command? -
rest api flutter get method works while post doesnt
ihave this error from server response ihave this error from server response this is the models and api u can find full source code here https://github.com/alihassan75/project // To parse this JSON data, do // // final task = taskFromJson(jsonString); import 'dart:collection'; import 'dart:core'; import 'package:flutter/foundation.dart'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; //List<Task> taskFromJson(String str) => List<Task>.from(json.decode(str).map((x) => Task.fromJson(x))); //String taskToJson(List<Task> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class Project { Project({ this.id, required this.project_name, this.created_at, // required this.start_date, //required this.end_date, required this.user, }); int? id; final String? project_name; DateTime? created_at; // final DateTime? start_date; //final DateTime? end_date; int user; factory Project.fromJson(Map<String, dynamic> json) => Project( id: json["id"], project_name: json["project_name"], created_at: DateTime.parse(json["created_at"]), // start_date: DateTime.parse(json["start_date"]), //end_date: DateTime.parse(json["end_date"]), user: json["user"], ); Map<String, dynamic> toJson() => { "id": id, "project_name": project_name, "created_at": created_at?.toIso8601String(), // "start_date": start_date?.toIso8601String(), //"end_date": end_date?.toIso8601String(), "user": user, }; } class ProjectProvider with ChangeNotifier{ ProjectProvider(){ this.fetchProject(); } List<Project> _project = []; List<Project> get project { return [..._project]; } void addProject(Project project) async { final response = await http.post(Uri.parse('http://mostafahamed.pythonanywhere.com/project/api'), headers: {"Content-Type": "application/json"}, body: json.encode(project)); if (response.statusCode == 201) { project.id = json.decode(response.body)['id']; _project.add(project); notifyListeners(); print('sucess'); } else { print(response.body); throw Exception('Failed to add project'); } } void deleteProject(Project project) async { final … -
update data without refreshing the page in django
I have this code in the model of project django. I used @property to calculate the timer and return it. I used it in my templates But it doesn't update unless you refresh the page. how can I update it without refreshing the page. It is possible to do this with ajax, but I don't know how to do it because I haven't learned ajax yet. @property def checking(self): self.timeend = self.timestart + timedelta(hours=self.time) if self.status == "Live": timer = self.timeend - datetime.now(timezone.utc) return timer -
Django Web interface with a upload button
You have received a text file with the company's sales data. We need to create a way for this data to be imported into a database Your task is to create a web interface that accepts file uploads, normalize the data and store it in a relational database. enter image description here -
Django DRF - Entire Other User Profile return in API call
I have a UserSerializer (I used a CustomUser model) class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['id', 'first_name', 'last_name', 'email', 'is_typeA', 'is_typeB'] read_only_fields = ['id', 'email', 'is_typeA', 'is_typeB'] I have a profile model for each user type, and a serializer as well. class TypeASerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TypeAProfile fields = ['user_id','user','course', 'ndex', 'created_at'] read_only_fields = ['id', 'created_at'] class TypeBSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TypeBProfile fields = ['user_id', 'user', 'course', 'rating', 'created_at'] read_only_fields = ['id', 'created_at', 'rating'] I have an endpoint to get the logged in users profile. class MyProfile(APIView): def get(self, request, *args, **kwargs): serializer = get_user_profile(request.user) return Response(serializer.data) def patch(self, request, *args, **kwargs): if request.user.is_typeA: typeauser = TypeAProfile.objects.get(user_id=request.user.id) user_updates = request.data.pop('user') serializer = TypeASerializer(typeauser, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() user_serializer = UserSerializer(typea.user, data=user_updates, partial=True) user_serializer.is_valid(raise_exception=True) user_serializer.save() return Response(serializer.data) elif request.user.is_typea: typebuser = TypeBProfile.objects.get(user_id=request.user.id) user_updates = request.data.pop('user') serializer = TypeBSerializer(typebuser, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() user_serializer = UserSerializer(typebuser.user, data=user_updates, partial=True) user_serializer.is_valid(raise_exception=True) user_serializer.save() return Response(serializer.data) serializer = UserSerializer(request.user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) My endpoint is : /profile. This return: { "user_id": 1, "user": { "id": 1, "first_name": "John", "last_name": "Smith", "email": "email@email.com", "is_typeA": false, "is_typeB": true }, "course": "Udemy-123", "index": 2 "created_at": … -
How to execute cron function in linux alpine using docker
I am trying to run my django application using a docker image with a scheduled cron job. My Dockerfile is the following FROM python:3.8-alpine3.10 WORKDIR /OuterDirectory ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PORT=8000 RUN apk update && apk add --update alpine-sdk RUN apk add --no-cache tini openrc busybox-initscripts COPY requirements.txt requirements.txt RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN apk add --update npm COPY . /OuterDirectory/ RUN npm install RUN mkdir cron RUN touch cron/cronlog.log WORKDIR /OuterDirectory/Projectname EXPOSE 8000 CMD python manage.py crontab add && python manage.py runserver 0.0.0.0:8000 In django settings I have properly added it to my INSTALLED_APPS. CRONJOBS = [ ('* * * * *', 'api.cron.testfunc', '>> ../cron/cronlog.log 2>&1'), ] Everything in the docker image builds with no error. I am 99% sure the issue is something to do with alpine linux and how to configure/get cron running on it but I am unable to find any resources. If anyone has any tips, please do help me I've been trying for a while lol -
Opearator calculations insid a django template
Inside a Django template I have such a phrase: <h4>{{ webinar.name or 'Not title' }}</h4> leading to this error: Could not parse the remainder: ' or 'Not title'' from 'webinar.name or 'Not title'' This is because Django does not like to calculate operators inside a template. It seems that django-mathfilters does not have an or operator. I also do not like to use {% if ... %} either. Because this is a MWE. I have faced with other cases that I cannot get around them so easy. -
Ldap error when try to runserver, Django/Python
I can't seem to find much information about my topic online so I figured I'll ask. I'm trying to set up an app on Django and when I try to 'runserver' I get the following error. It runs with no problem when I remove the ldap configurations but when I add it back in I get this error. Anyone have an idea what can be causing this to break? I'm using Ubunut 20.04 on a windows machine. -
Inline styles working but not in style head (working on CS50 project 2)
I am working on CS50 Project 2 and have a webpage that displays active listings. I want to add some changes to the css, but it nothing happens when I add changes to the style in the head, but inline styles work. How do I make it work in the head style? {% extends "auctions/layout.html" %} <head> {% block style %} <style> .text { font-size: 10%; } </style> {% endblock %} </head> {% block body %} <h2>Active Listings</h2> {% for listing in listings %} <img src ="{{ listing.image }}" style = "height: 10%; width: 10%;"> <h4 class = "text" style = "color: aqua;">{{ listing.title }}</h4> <h6>Description: {{ listing.description }}</h6> <h6>Category: {{ listing.category }}</h6> <h6>Price: ${{ listing.bid }}</h6> {% endfor %} {% endblock %} This is the code. The font size doesn't change, but it will change colors because of the inline style. -
Database planning
I am trying to implement a Pharmacy drug database. I thought about it as follows: In the database schema, there will be a Commercial drug table called "Drug", another table for the manufacturing company called "Company" and a third one implementing the Scientific drug name and dose called "Scientific_Drug". The Drug will have a many-to-many relation with the scientific drug. In fact, multiple scientific drug entries can be included in one Commercial drug entry. I am using Python django models.Model to implement this database schema. I wounder how to implement a multiple entries of scientific drug names provided that many commercial drugs can have variable counts of scientific drug entries. Is there a way of doing this in Python django? My primary code is as follows: class Company(models.Model): name = models.CharField(max_length=70, null=False) launch_date = models.DateField('Launch Date') history = models.TextField(max_length=10000) def __str__(self): return self.name class Scientific_Drug(models.Model): name = models.CharField(max_length=70, null=False) dose = models.PositiveIntegerField(null=False) def __str__(self): return self.name class Drug(models.Model): drug_name = models.CharField(max_length=255, blank=False) drug_dose = models.DecimalField("Dose", decimal_places=2) drug_form = models.CharField(max_length=255, blank=False) drug_price = models.DecimalField("Price", decimal_places=2) release_date = models.DateField('Release Date') expiry_date = models.DateField("Expiry Date") ingredient = models.ManyToManyField(Scientific_Drug) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.drug_name Thanks in advance. -
json value in d3.js
I want to load json data from JSONField, I load the file inside js and I got an uncaught and a 404 not found error, it seems it read the value as an object but in the console I can see the data loaded as a json var jjson = {{proyecto.ifc_json|safe}}; console.log(typeof(jjson)) // = object var jsoo = JSON.stringify(jjson); console.log(typeof(jsoo)) // = string var jsonn = JSON.parse(jsoo); console.log(typeof(jsonn))// = object I got an error loading any of those in the d3.json method d3.json(jjson, function(error, flare) { if (error) throw error; root = d3.hierarchy(flare); root.x0 = 0; root.y0 = 0; update(root); }); cant figure whats the problem, thanks -
Get the count of model attribute through ListVIew
How do I get the Count of a specific attribute of an object model using ListView? I know that {{page_obj.paginator.count}} displays the total objects in the template. Is there a way to do the same for a specific attribute of the object? -
multiple times in multiple days
I want to create a model which will have multiple users and every user will have to choose multiple times in one day or multiple times in multiple days with the state of every time (available or not) and auto-update these times weekly -
How to save from html select to sql in django
I want to save from HTML select to SQL but "Cannot assign "'27'": "UserProduct.category" must be a "Category" instance." I get an error. What am I doing wrong? sell.html <div class="form-group"> <p>Yerləşdirdiyiniz məhsul "İkinci əl məhsullar" kateqoriyasında görünəcək.</p> <select class="input search-categories" name="up_category"> <option value="0">Kateqoriya seç</option> {% for category in category %} {% if category.active %} {% if category.parent_id %} <option value="{{category.id}}">{{category.name}}</option> {% else %} <option value="{{category.id}}" style="font-weight: bold;">{{category.name}}</option> {% endif %} {% endif %} {% endfor %} </select> </div> views.py def sell(request): category = Category.objects.all() context = {'category': category} if request.POST: product_name = request.POST.get('product_name') up_category = request.POST.get('up_category') keywords = request.POST.get('keywords') descriptions = request.POST.get('descriptions') main_image = request.POST.get('main_image') price = request.POST.get('price') detail = request.POST.get('detail') image1 = request.POST.get('image1') image2 = request.POST.get('image2') image3 = request.POST.get('image3') if product_name == '' or up_category == 'Kateqoriya seç' or keywords == '' or descriptions == '' or price == '' or price == str or detail == '': messages.warning(request, 'Bütün xanaları doldurduğunuzdan əmin olun!') else: newUserProduct = UserProduct(user=request.user, name=product_name, category=up_category, keywords=keywords, descriptions=descriptions, detail=detail, main_image=main_image, image1 = image1, image2 = image2, image3 =image3 ) newUserProduct.save() messages.warning(request, 'Məhsulunuz satışa çıxdı.') return render(request, 'forms/sell.html', context) return render(request, 'forms/sell.html', context) models.py class UserProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=False) name = models.CharField(max_length=100) category … -
Adding Flutterwave in to django template and view
I have created flutterwave developer account, as you can see down here i have setup everything except template and views.py file settings.py file FLUTTERWAVE_SECRET_KEY = 'my-keys' FLUTTERWAVE_PUBLIC_KEY = 'my-keys' i don't know how to write the amount to charge for each user and also don't know what to put inside my template and views.py file. is anybody who wish to help me please?