Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Getting the error : ImportError: cannot import name 'to_const'
getting the following import error in my Django application, is there a workaround ? from graphene.utils.str_converters import to_camel_case, to_const ImportError: cannot import name 'to_const' -
how to put radio button from admin.py?
one question is that I am using admin.py to make my profile edition page; I had to do it like this to add more fields and customize it. Everything works fine, except for one thing: I don't know how to format a form field (it's called country) to be a radio button and have the options "canada", "USA" and "other" does anyone have an idea? how to do it? I am using UserCreationForm and UserChangeForm but I don't know how to edit forms that are already preset admin.py class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form=UserChangeForm model=CustomUser list_display = ['pk','email','username','first_name','last_name'] add_fieldsets = UserAdmin.add_fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip')}), ) fieldsets = UserAdmin.fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip')}), ) admin.site.register(CustomUser) -
MyPy, Django, VSCode. ModuleNotFound Error
I really need your help here! I am using VSCode and MyPy extension to type check the Django code that I am writing. I have installed all the necessary requirements for Django like: pip install mypy pip install django-stubs-ext pip install django-stubs I have installed the extension for the VSCode to check my code as well. However, whenever I try to use this extension it outputs the following error: ModuleNotFoundError: No module named 'md_project.settings' I have attached the screenshots of the .ini and .json files of my project. Moreover, I have attached the screenshot of the project tree. I just dont know whats going on with the MyPy. By the way, I am using Windows 10. mypy.ini settings.json project tree -
How to send 'image' via POSTMAN? (Django Image Field)
I'd like to send image via postman like this and save to 'media' directory but don't know how to do this. enter image description here And these are my codes that I use. models.py class Article(models.Model): emotion = models.TextField() location = models.TextField() menu = models.TextField() weather = models.TextField() song = models.TextField() point = models.IntegerField() content = models.TextField() image = models.ImageField(default = 'media/coffee_default.jpg', upload_to = "%Y/%m/%d") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created = models.DateTimeField(default = now) liked = models.BooleanField(default = False) num_liked = models.IntegerField(default = 0) views.py @api_view(['POST']) @permission_classes([]) def post_articles(request): user = request.user body = json.loads(request.body) article = Article( emotion = body['emotion'], location = body['location'], menu = body['menu'], weather = body['weather'], image = body['image'], song = body['song'], point = body['point'], content = body['content'], user = user) article.save() serializers = ArticleSerializer(article) return JsonResponse({ "success": True, "data": serializers.data }) serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['emotion', 'location', 'menu', 'weather', 'song', 'point', 'content', 'image', 'user', 'created', 'liked', 'num_liked'] -
Pycharm - FastAPI issue with static files
I am struggling to reference my static css files in my template index.html file In my head tag in index.html I have: <link href="{{ url_for('static', path='./styles.css') }}" rel="stylesheet"> It is giving me this error "Cannot resolve directory" In main.py I have the files mounted like so: app.mount("/static", StaticFiles(directory="static"), name="static") Folder Structure: ├── Project_name ├── main.py ├── static │ ├── styles.css ├── Templates │ ├── index.html What could be the cause of this, how can I specify the correct path?