Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mass Upload Json data into Django Models using Views
I've been working on getting to learn Django and React to broaden my knowledge in Programming. I'm trying to create an API endpoint to Mass upload data from the front end (React) into Django models. Realistically it wont be more than 20 records at a time but I wanted to see if this can be done without having to upload a record individually. The front end would accept a CSV File and convert it into a Json array. Can anyone provide some guidance on how I would create a View to allow me to accept that json array and insert it into my models. I'm using Django, React, and Postgres as my DB. I tried to create some views for this functions but it doesn't really workout. Models: class Products(models.Model): date_added = models.DateTimeField(default=django.utils.timezone.now) on_hold_till = models.DateTimeField(default=django.utils.timezone.now) item_no = models.CharField(max_length=120, default="") description = models.CharField(default="", max_length=256) total_units = models.IntegerField(default=0, blank=True) is_featured = models.BooleanField(default=False) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) avg_cogs = models.DecimalField( max_digits=10, decimal_places=2, default=0.00) profit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) margin = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) mintage = models.IntegerField(default=0, blank=True) pop_known = models.CharField(default="", blank=True, max_length=100) ngc_pop = models.IntegerField(default=0, blank=True) pcgs_pop = models.IntegerField(default=0, blank=True) total_pop = models.IntegerField(default=0, blank=True) finer_known = models.IntegerField(default=0, blank=True) highlights = ArrayField(models.CharField( … -
Django: Call form clean before model clean
I have an Occurrence model that I am putting as TabularInline on the admin page of another model. It has a PointField and a PolygonField, of which at least one must exist. Here is part of the model: class Occurrence(models.Model): name = models.CharField(max_length=254) location = models.PointField(null=True, blank=True) bounding_polygon = models.PolygonField(null=True, blank=True) def clean(self): # Checks if at least one of the spatial fields is filled in if not self.location and not self.bounding_polygon: raise ValidationError('At least one of the spatial fields (point or polygon) is required.') In the TabularInline I wanted to put the name and location but when I add new rows the map of the location does not appear. To get around this problem, I used a form where you can enter the latitude and longitude, which is then converted to the Point of location. Here is my form: class OccurrenceForm(forms.ModelForm): latitude = forms.FloatField( min_value=-90, max_value=90, required=False, help_text="Enter coordinates as an alternative to selecting a point on the map." ) longitude = forms.FloatField( min_value=-180, max_value=180, required=False, ) class Meta(object): model = Occurrence exclude = [] def __init__(self, *args, **kwargs): super(OccurrenceForm, self).__init__(*args, **kwargs) coordinates = self.initial.get("location", None) if isinstance(coordinates, Point): self.initial["longitude"], self.initial["latitude"] = coordinates.tuple def clean(self): data = super(OccurrenceForm, self).clean() … -
How can I apply a common validator to all text inputs in my Django form?
I want to apply a special character whitelist to all non-password user text inputs across my site, so that validation will fail if a non-whitelisted character is entered. All of my forms already inherit from a single base form class, which itself inherits from django.forms.BaseForm. How can I apply this validator to every relevant field on all the forms that inherit from this form? -
patch in serializer django rest
I have 1 parent and 1 child serializers, right now child serializer inherits all fields, functions and methods from the parent serializer. I would like to modify patch request in child serializer, that while request is patch, then some fields will be unavailable for updating, cause there will be completely different two urls. For example in child class there will be unable to update name and surname. class Parent(serializers.ModelSerializer): class Meta(BaseMeta): model = Account fields = BaseMeta.fields + ( 'name', 'surname', 'age', 'city', 'country', 'job', 'family') extra_kwargs = {'name': {'required': True, 'allow_blank': False, 'allow_null': False, 'trim_whitespace': False}, 'surname': {'required': True, 'allow_blank': False, 'allow_null': False, 'trim_whitespace': False}, 'country': {'read_only': True}, 'job': {'required': True, 'allow_blank': False, 'allow_null': False, }, } class Child(ParentSerializer): class Meta(BaseMeta): model = Account fields = BaseMeta.fields + () extra_kwargs = { } -
Django - display the same chart in loop in jinja template with chart.js
I would like to display the same chart (of course with different data and labels) in loop. At this moment I have: <tbody> {% for key, value in game_details.items %} <tr> <td>{{ key }}</td> <td>{{ value.all }}</td> <td>{{ value.win }}</td> <td>{{ value.lost }}</td> </tr> <tr> <td> <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'pie', data: { labels: ['Win', 'Lost'], datasets: [{ label: '# of Votes', data: [{{ value.win }}, {{ value.lost }}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </td> </tr> {% endfor %} </tbody> The first chart is displayed, but when I'm looking in console I can see: Uncaught SyntaxError: Identifier 'ctx' has already been declared (at (index):179:29). So my loop can't create another chart, because ctx is already declared. My goal is to display chart for each iteration over dictionary. I was looking at this post, but it doesn't sole my problem. How can I do it properly? -
django.core.exceptions.ValidationError: ['“2022-05-19 00:00:00.000” value has an invalid date format. It must be in YYYY-MM-DD format.']
i'm trying to make a new object with flutter and django rest framework , the object has a datefield but when i try to make post request and send data from flutter front end to django api i got this error : django.core.exceptions.ValidationError: ['“2022-05-19 00:00:00.000” value has an invalid date format. It must be in YYYY-MM-DD format.'] [17/May/2022 22:18:23] "POST /api/reservations/create/ HTTP/1.1" 500 181841 this is the post method : void creerReservations() async { _setIds(); client.post(Uri.parse("http://10.0.2.2:8000/api/reservations/create/") , body: { "date" : dateRendezvous.toString(), "startTime" :startTime.toString(), "endTime" :endTime.toString() , "description" : ' no description for now', "patient" : _patient_id.toString(), "docteur" : _docteur_id.toString() , "disponible" : "True" }); } Django class : # Create your models here. class Reservation(models.Model): date = models.DateField() startTime = models.TimeField() endTime = models.TimeField() description = models.TextField() patient = models.ForeignKey(User, on_delete=models.CASCADE , related_name="patient") docteur = models.ForeignKey(User, on_delete=models.CASCADE , related_name="docteur") disponible = models.BooleanField( default= True ) def __str__(self): return self.date serializer : class ReservationSerializer(ModelSerializer): class Meta : model = Reservation fields = '__all__' the variable types : DateTime dateRendezvous = DateTime.now(); TimeOfDay startTime = TimeOfDay(hour: 15, minute: 0); TimeOfDay endTime = TimeOfDay(hour: 15, minute: 0); int _patient_id = 0; int _docteur_id = 0; bool? disponible; -
Disable automatic ID table generation functionality in DJango
I'm having a problem trying to get my model to generate a migrations with the ID, which I configured inside the model. class Produtos(models.Model): STATUS_PRODUTOS = [ ('A', 'Ativo'), ('I', 'Inativo'), ] cod_produto = models.BigAutoField(primary_key=True), nome_produto = models.CharField(max_length=155) status_produto = models.CharField(max_length=1, choices=STATUS_PRODUTOS) Whenever I give the command to run the migration creation, and I go to check, it's Django's automatic ID. operations = [ migrations.CreateModel( name='Produtos', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome_produto', models.CharField(max_length=155)), ('status_produto', models.CharField(choices=[('A', 'Ativo'), ('I', 'Inativo')], max_length=1)), ], ), ] I need to know how to disable or remove this configuration from my Django, since, as I've already done the primary auth migrations and everything, I won't need this generation anymore; -
What is name and value attributes on a form Django
I am trying to find out what is name and value attributes in a form? On the example below what is the {{ current_name }} taken from in the form? <form action="/your-name/" method="post"> <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ current_name }}"> <input type="submit" value="OK"></form> -
Selectfield not showing options
I have a field in my modelform where the user can choose the mealtype. But the form input does not work, when I click it, nothing happens. What I want to happen is to display a dropdown with the different meal types. The model looks like this class Recipe(models.Model): ... meal_type = { ('Breakfast', 'Breakfast'), ('Lunch', 'Lunch'), ('Dinner', 'Dinner') } meal = models.CharField(max_length=12, choices=meal_type, null=True) My form looks like this class RecipeForm(forms.ModelForm): ... meal = forms.CharField(widget=forms.Select(attrs={'class':'form-select'})) class Meta: model = Recipe .... I have also tried to use "Choicefield" instead of "Charfield" but I can't get it to work. -
How to send the text in django-select2 field instead of the id at form submission?
This is a two-part question Problem description I have a form with a field that uses ModelSelect2TagWidget (that accepts free-text as an input). when the user enters a number as free-text, it is converted to the object whose id is the number entered as a free-text. For example, if the user enters "11" as free-text and the form is submitted, the entry is automatically converted to the value whose id is 11 in the database On the other hand, if the user chooses one of the available choices (not a free-text), the id of the selected choice in the select2 field is sent in the request as in the screenshot. The problem is when the form is submitted, I have no way to distinguish whether the submitted value is an id or a free-text entered by the user. To solve this problem, I am thinking about sending the text of the input field instead of the id as follows How can I send the text of the selected choice instead of the id in the request? As this is a ModelSelect2TagWidget field, it accepts free-text. Is there a better way to distinguish between the id of a selected choice or … -
Why am I only getting default values when adding something to my database? (Django)
I'm trying to add tasks to my todo list. All of my added tasks are listed on the homepage (home.html) but whenever I try to add something it always sets my input to default (I added a picture at the end). I know I wrote 'default_value' in views but I wanted to check if it's even adding todos without it throwing an error. views.py def newTodo(request): obj = List() obj.taskText = request.POST.get("taskText", "default_value") obj.taskDate = request.POST.get("taskDate", "default_value") obj.taskDerc = request.POST.get("taskDerc", default= 5) obj.save() mydict = { "all_tasks" : List.objects.all() } return render(request, 'newTodo.html', context=mydict) newTodo.html (using Bootstrap) <tbody> {% block content %} <tr> <form action="{% url 'newTodo' %}"> <td scope="row"> <input type="text" class="form-control" id="taskText" name="taskText"></td> <td scope="row"> <input type="text" class="form-control" id="taskDate" name="taskDate"></td> <td scope="row"> <input type="text" class="form-control" id="taskDerc" name="taskDerc"></td> <td><a href="{% url 'home' %}" class="btn btn-success" role="button"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check" viewBox="0 0 16 16"> <path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z" /> </svg> </a> </td> </form> </tr> {% endblock %} </tbody> What am I missing? Any kind of help is appreciated! -
Javascript : display a PDF with a blob from a base64 string
I want to display a pdf on a browser. The pdf content is downloaded fom an azure blob storage and then encoded in base64 string. Then I transfer this content to the html template to decode and display it. Below is my first attempt with the views.py from my django app that works however only for files smaller than 2MB. views.py def displayFILE(request, file_id): context = initialize_context(request) file = UploadFilesAAD.objects.get(pk=file_id) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = download_from_blob(blob_name) encodedstring = base64.b64encode(blob_content.readall()) content = blob_content.readall() context["content"] = str(content) context["encodedstring"] = str(encodedstring)[1:].replace("'","") return render(request, 'archivage/displayFILE.html', context) html {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <object> <embed id="pdfID" type="text/html" width="100%" height="100%" src="data:application/pdf;base64,{{ encodedstring }}" /> </object> </body> </html> I do not want limitation on the file size, so I try to write with Javascript. Firts I convert string encoded to Blob. Then I generate the temporary DOM String base on Blob. Finally, I display it. My code doesn't work but I do not get what is wrong. I am learning Javascript so I am probably missing something. the new html {% load static %} <head> … -
Django smart-selects how to add cutom attributes to select options?
I am newbie to Django and I am working on a project where I have two dropdown lists one includes a list of countries and another for the cities. when the user selects a country from the country dropdown list, the city dropdownlist is updated to show the cities of the selected countries using django smart-selects I need to customize theattributes of the chained select html of cities so that each option in the cities dropdown list will include the information of the relative lat & long of the selected city, So I can have something like this: <select name="city" class="form-control" required="" id="id_city"> <option value="248" data-lat="29.664037" data-long="32.352000"> City 1</option> </select> Any help how to implement this? Thanks in advance -
Django forms integration with legacy UI component library
I'm working on a Django project and would like to incorporate a proprietary UI component library that my company created into my application. The library has CSS utility classes for positioning, font, margin, padding, etc. (similar to Tailwind or Bootstrap). These are simple enough to put into a Django template without overhead. However, I'm struggling with using the library's form/input components (which rely on JSON data as well as HTML). # html <custom-select id="multiple-select-example" label="State" placeholder="Choose your state." multiple ></custom-select> # js var multipleSelect = document.getElementById("multiple-select-example"); multipleSelect.options = [{ text: "Pennsylvania", value: "PA" }, { text: "California", value: "CA" }, { text: "Texas", value: "TX" }]; In a vacuum, it's easy enough to use Django's "json_script" tag to load JSON directly into the '.options' and process the user's data input in JS. But I feel like this misses out on some of the benefits of using Django's built-in Forms (validation, serialization, etc.). How do I get the best of both worlds? Do I have to create custom form fields in Django? Or custom widgets with media assets? I don't know what to do, everything I do is messy. Please help. -
Webshell upload in django webapp
What file can be uploaded on a webapp built on django framework if it's allowing unrestricted file upload? When I uploaded a shell.py it simply rendered as text in the browser but html and javascript are executing fine. -
Validation with checking all model objects. Django
class Questions(models.Model): question = models.CharField(max_length=350) class AnswerOptions(models.Model): answer = models.CharField(max_length=150) yesorno = models.BooleanField(default=False) question = models.ForeignKey('Questions', on_delete=models.CASCADE) I am new to django and would appreciate any suggestions. I really hope for help. How in my case to implement validation in the admin panel? it is necessary to prohibit marking all answers as incorrect and all answers as correct. here the BooleanField field is responsible for this. in the admin.py model, the connection is implemented through “inline”. -
Django dynamically modifying querysets
I've got a Django 2.2.28 application running on Python 3.7.7 and I'm trying to add what I think is an unusual query filter. One of the displays is generated by a queryset that is filtered in the normal way against a PostgreSQL database. This data is presented in using a paginator. I'm being asked to add a filter the data on the display by an additional filter using data that comes from a REST API call (not the database). A simplified presentation to explain what's desired, let's say I have a display with 2 columns, Id and Name that comes from the database: Id Name 1 George 2 Anne 3 Susan 4 Mark The add ask is to add a 3rd column for Status, which comes from a REST API by passing a list of Id values. Adding the Status to the above display would theoretically present this if the list of Ids were passed to the REST API: Id Name Status 1 George True 2 Anne False 3 Susan True 4 Mark False The users would like to filter the display based on the Status (True/False) and still have a full page of results (4). The problem is if … -
'NoneType' object is not subscriptable Rasise Validation Error if same name filled twice Django
I am trying to create a validation that will raise validation error if same name filled twice , but i am getting 'NoneType' object is not subscriptable error. Model.py fruit_name = models.ManyToManyField( "Fruits", blank=True, null=True, verbose_name=_("Fruit Nmaes"), ) form.py class ScenarioForm(forms.ModelForm): def clean(self): fruit_name_set=[] count = int(self.data.getlist('fruit_set-TOTAL_FORMS')[0]) if count > 1: for i in range(count): fruit_name_code = self.data.get(f'fruit_set-{i}-fruit_name')[3] if fruit_name_code not in fruit_name_set: fruit_name_set.append(fruit_name_code) else: fruit_name_set = models.Fruit.objects.filter(pk=fruit_name_code).last() raise ValidationError( "Duplicate Fruit Name not allowed! " ) But I am getting this error, how to solve the error NoneType' object is not subscriptable -
How can I write text under the label of my Django model form?
I am working on a register form on Django. Under my TextFields label I want to write "For multiple purchased units any of the item barcode works." Like below: image How can I add this to my form? -
Allowing users to pay and ship items for each others in Django website
I want to allow users to have the option of shipping an item between two users, one of the related users can ship an item to the other, can anyone please explains to me how it can be done and what packages or tools can help me to achieve it and thank you so much -
i want to integrate an Machine Learning system in my web app using Django Back-end from Nyckel Machine Learning Service?
i send the request to Nyckel Service and get the response back as text but the response i get is invalid format i am working on implement image classification : the result i need to get is this depends on the image i send it through the POST request for Nyckel Service : { "labelName": "harissa", "labelId": "label_684pbumtvbzp3k9q", "confidence": 0.76 } @api_view(['POST','GET']) def addProductByNyckel(request): data = request.data image = data['image'] url = 'https://www.nyckel.com/v1/functions/7aaigszss2ejx7t8/invoke/?format=json' header = { 'Content-type': 'application/json', 'Accept': 'text/plain' } urlimg = 'http://127.0.0.1:8000/media/images/chamia_2lJVXBC.jpg' img = requests.get(urlimg,params=request.GET) m = img.content result = requests.post(url,m, headers=header) dict = result.json() labelName= dict.get("labelName"), labelId = dict.get("labelId"), confidence = dict.get("confidence") return Response(dict ) ` the error message is : **{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-983824a0cb2b204855f4387cf92f2dca-780a95630f9dc3d6-00", "errors": { "$": [ "'0x89' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0." ], "input": [ "The input field is required." ] } }** -
How to pass a number from an html form to Django views
<form action="{% url 'item' %}" method="GET"> {% csrf_token %} Choose an item's id: <input type="number" name="number" value="{{ request.GET.id }}"> <input type="submit"> </form> class SearchResultView(ListView): model = Item template_name = 'item_buy.html' def get_queryset(self): return Item.objects.get(id='') I need to pass an id from the form to the ListView's queryset, however, I don't understand how to call it in the view. Please, tell me how do I need to change the form and the view. -
Django Rest Framework: How to get data from a post request at class based API views?
This is the simple api view: class ReceiveNewData(APIView): def post(self, request): return Response('response') When we are posting some data to somewhere, we can send some data with it. For example: request.post(url, data={//the data will be sent}) Or from the body section in Postman program. The question is: how can I receive any data at my api view like that? -
Django Tutorial. Page not found
I already search for any answer which could help me before write this question, but I haven't found anything that helps. The thing is that I follow the tutorial and I can't see the view that I created. Now I'm going to share my code: project urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls urls.py: from django.urls import path from . import views urlpatterns = [ path(" ", views.index, name='index'), #127.0.0.1/polls/ ] polls views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): HttpResponse("Welcome to de Polls Universe Index") -
Why is my Boostrap-Card header not filling entire width of the card?
I am new to Bootstrap and Django. I am trying to style a card, but card header (background) does not fill entire width of the card. Here is an example: Here is the code: <div class="container"> <div class="grid"> <div class="row"> {% for list, content in content.items %} <div class="card col-md-6 shadow-lg"> <a href="{{user_name}}/{{list}}"> <div class="card-header bg-secondary text-white">{{list}}</div> <div class="card-body"> <ul> {% for row in content %} <li>{{row}}</li> {% endfor %} </ul> </div> </a> </div> {% endfor %} </div> </div> </div>