Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Matching Primary key with url in Django. When I am trying to enter the url: (localhost:8000/detail/S1111111A/) it always shows a mismatch error
Below is my view, url and model. I have stored some values in my database, and I make patientNRIC as the primary key, now I wanted to access the respective patient details through their patientNRIC, however, I could not do that, it always show me the error of mismatch. plss helllpp meeeee. Thanks #view.py from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import PatientDetail from .serializer import PatientSerializer # Create your views here. @api_view(['Get', 'POST']) # @csrf_exempt def patient_list(request): if request.method == 'GET': patientdetails = PatientDetail.objects.all() # serialization serializer = PatientSerializer(patientdetails, many=True) # return Json return Response(serializer.data) elif request.method == 'POST': #data = JSONParser().parse(request) serializer = PatientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['Get', 'PUT','DELETE']) @csrf_exempt def patient_detail(request,patientNRIC): try: patientdetails = PatientDetail.objects.get(patientNRIC) except PatientDetail.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": # serialization, getting one data only serializer = PatientSerializer(patientdetails) # return Json return JsonResponse(serializer.data) elif request.method == "PUT": data = JSONParser().parse(request) serializer = PatientSerializer(patientdetails, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': patientdetails.delete() return HttpResponse(status=204) #url.py from django.urls import path from .views import … -
How can I show gender names in HTML template
Whenever I am signup for a customer on my website all the data are shown on my dashboard but in the gender field, showing me a number. Check the below image to better understand: models.py class Customer(models.Model): GenderChoice = ( ("0","Male"), ("1","Female"), ) first_name = models.CharField(max_length=20, null=True) last_name = models.CharField(max_length=20, null=True) address = models.CharField(max_length=500, null=True) phone = models.CharField(max_length=10, null=True) gender = models.IntegerField(choices=GenderChoice, default=1) email = models.CharField(max_length=100, null=True) password = models.CharField(max_length=8, null=True) Thanks! -
How to serialize string geojson in Django when part of multipart?
I am sending a multipart POST. One field of the data sent is footprint which is string geojson. I converted it to string since it cannot be send as a dict object unlike when sent POST as json. self.thumbnail = open('apps/data/thumb.png','rb') self.footprint = """{"type": "Polygon", "coordinates": [[[121.79168701171875, 16.909683615558635], [122.12539672851561, 16.909683615558635], [122.12539672851561, 17.19983423466054], [121.79168701171875, 17.19983423466054], [121.79168701171875, 16.909683615558635]]]}""" self.data = { 'thumbnail': self.thumbnail, 'footprint': self.footprint, } self.client.post('/data_management/capture_group_products/', data=self.data, format='multipart') I am using a Field Serializer in Django to extract the geojson and input to a GeometryField. class FootprintSerializer(serializers.Field): def to_internal_value(self, data): geom_data = data #geom_data = json.dumps(geom_data) print(geom_data, type(geom_data)) return GEOSGeometry(geom_data) #footprint = FootprintSerializer(source='*') When I input it to GEOSGeometry, when the data is in string, I get the error: ValueError: too many values to unpack (expected 2) {"type": "Polygon", "coordinates": [[[121.79168701171875, 16.909683615558635], [122.12539672851561, 16.909683615558635], [122.12539672851561, 17.19983423466054], [121.79168701171875, 17.19983423466054], [121.79168701171875, 16.909683615558635]]]} <class 'str'> But when I use json.dumps(geom_data), I also get backslashes from the geojson and get the error: ValueError: String input unrecognized as WKT EWKT, and HEXEWKB. Backslashed geojson: "{\"type\": \"Polygon\", \"coordinates\": [[[121.79168701171875, 16.909683615558635], [122.12539672851561, 16.909683615558635], [122.12539672851561, 17.19983423466054], [121.79168701171875, 17.19983423466054], [121.79168701171875, 16.909683615558635]]]}" <class 'str'> I also have tried: geom_data = json.dumps(json.loads(geom_data)), and also did not work. Had error like the first … -
how to convert date with format 01/01/2019 08:36 to python datetime object?
if dict_value: field_type = col.get_internal_type() # logger.info(field_type) if field_type == 'DateTimeField': dict_value = each_data.get(uploaded_header) Here in variable dict_value , i am receiving date as 01/01/2019 08:36, I need the format to converted to python datetime field value and passed back to the dict_value. How is it possible? -
Re populate images when ValidationError occurs
Good day SO. I would like to ask when trying to upload images and a ValidationError happens. As per 2011 SO Answer, this is a browser thing when trying to upload images and getting a validation error, the uploaded images are removed. Do you have any workarounds with this? If not, any suggestions? Ideas? -
How to get image url from embed tag of RichText field?
I have a RichText field in wagtail project in which the images are stored in block text as: [{'type': 'text', 'value': '<p>Image below:</p><p></p><embed alt="Screenshot from 2021-04-01 18-55-15.png" embedtype="image" format="left" id="55"/><p></p>', 'id': 'de338256-7af9-48b1-9b5a-1dda81b80e83'}] It is showing perfectly on wagtail cms, but I want to return this data in api. How do I convert the <embed> to <img>? -
Large quantity of Videos to be stored?
recently I am building a web app. since I am new to deploying and hosting; I was wondering how and where to store all the video's that my app works on them? my web app has one feature that let users upload a video of their profiles. I don't know where to store them? maybe AWS S3? or is there any other better way of doing this? -
Django project not send data to database
I'm trying to create a register and login system in the Django framework, but there some problem with sending the data to the database, I have been checked the internet for any solution but I don't found the problem in the code !! -
I have models.py file. I am not sure how to write test for it? What to test? Can anyone please help and write test for it? #django #python
How to write tests for models.py file? from django.db import models from django.conf import settings from django.utils import timezone from django.contrib.auth.models import User class Profile(models.Model): #new user = models.OneToOneField(User, on_delete=models.CASCADE) institute = models.CharField(max_length=200, null=True) department = models.CharField(max_length=200, null=True) def __str__(self): return 'Email:{} Department:{} Institute:{}'.format(self.user.email, self.institute, self.department) class Access(models.Model): user = models.ManyToManyField(User) endpoint = models.CharField( max_length=20, choices=( ('pubmed', 'pubmed'), ('foster', 'foster'), ('med_apps', 'med_apps'), ('mayerson_transcripts', 'mayerson_transcripts'), ('all', 'all') ), unique=True ) def __str__(self): return self.endpoint class Request(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) created_time = models.DateTimeField(default=timezone.now) url = models.CharField(max_length=1000) def start(self): self.created_time = timezone.now() self.save() def __str__(self): return 'url:{} time:{}'.format(self.url, self.created_time) Need to run the test in Visual Studio Code. Also, I have seen a lot of examples for writing tests, but again got confused. It seems like I need to work on basics. -
Django: Use block in multiple places?
This is the template I've written {% extends 'base.html' %} {% load static %} {% block body %} <div class="row hide-on-mobile" style="height: 100vh"> <div class="col-auto p-5"> <img src="{% static 'logo.svg' %}" class="mb-5 hide-on-mobile" style="height: 84px"/> {% block form %} {% endblock %} </div> <div class="col bg-brown p-5"> <div class="d-flex flex-column justify-content-between" style="height: 100%"> <h1 class="text-blue mb-3">It's always Ups<br>and Downs</h1> <img src="{% static 'investing_illustration.svg' %}" class="auth-illustration"/> </div> </div> </div> <div class="hide-on-desktop" style="height: 100vh; position: relative"> <div class="d-flex flex-column bg-brown h-100 p-3 align-items-start"> <img src="{% static 'logo.svg' %}" class="mb-3 hide-on-desktop" style="height: 56px"/> <p class="text-blue mb-3">It's always Ups<br>and Downs</p> <img src="{% static 'investing_illustration.svg' %}" class="auth-illustration"/> </div> <div style="position: absolute; bottom: 0; z-index: 99; background: white; width: 100%"> <div class="d-flex flex-column p-4"> <p class="mb-4">Login</p> {% block form %} {% endblock %} </div> </div> </div> {% endblock %} The form block is used two times..because when I inherit the template I want to write only once..but display it in two different places in the same page. In this case, I've written different layouts for mobile and desktop show the user actually sees only once. However, this code doesn't work and gives the following error: django.template.exceptions.TemplateSyntaxError: 'block' tag with name 'form' appears more than once How … -
How to return 2 models in django
I have 2 models that I want to render to my html code and I tried doing this: form = CreateNewList() empName = employeeName.objects.all return render(response, "main/home.html", {"form":form}, {"empName":empName}) but it does not work. Is there a way to do this? -
Django Postgres JSONB and using a JSONB index
So we have a value stored in a JSONB column which I need to query on. I created an index for it like so create index user_notification_policy_id on user_notification using btree (((extra->'policy_id')::int8)); The explain plan is using the index if the query is formatted as so ("user_notification"."extra" -> 'policy_id')::text = '12345678'); How can I get Django to create a where clause like that? I've been trying to use extra but without luck return self.extra( where='("extra"->"policy_id")::int8 = %s', params=[policy_id] ) results in E ValueError: unsupported format character ')' (0x29) at index 1061 Django 2.2.16 -
django rest framework recursive models endpoints structure
I have three models like this (Simplified). class Locker(CoreModel): def __str__(self): return self.name topic = models.CharField( verbose_name=_('topic'), help_text=_("locker description"), null=True, max_length=1024 ) name = models.CharField( verbose_name=_('name'), help_text=_("locker name"), max_length=100, validators=( MinLengthValidator(2), ) ) owner = models.ForeignKey( to=settings.AUTH_USER_MODEL, related_name='owned_locker_set', verbose_name=_('owner'), on_delete=models.CASCADE ) class Folder(CoreModel): def __str__(self): return self.name name = models.CharField( verbose_name=_('name'), help_text=_('name of the folder'), max_length=256 ) parent = models.ForeignKey( to='self', verbose_name=_('parent'), on_delete=models.CASCADE, null=True ) locker = models.ForeignKey( to='lockers.Locker', verbose_name=_('locker'), on_delete=models.CASCADE, editable=False ) class Upload(CoreModel): def __str__(self): return self.name name = models.CharField( verbose_name=_('name'), help_text=_("upload name"), max_length=100, validators=( MinLengthValidator(2), ) ) locker = models.ForeignKey( to='lockers.Locker', verbose_name=_('locker'), on_delete=models.CASCADE, editable=False ) parent = models.ForeignKey( to='lockers.Folder', verbose_name=_('folder'), on_delete=models.CASCADE, null=True ) file = PrivateFileField( verbose_name=_('file'), help_text=_("raw file"), upload_to='uploads/', storage=private_storage ) as you can see, the structure is recursive. Ideally, from the frontend, I would want to make a single request to return all the files and folders the locker has at the root level (parent is None). Then, I would also like to make requests to get all the files and folders inside of a specified folder ( when the user opens a folder at the frontend). I am using Django Rest Framework right now. However, I cannot think of a way to achieve this … -
How to run Django with SAP HANA as database?
I would like to use SAP HANA as a database for my Django project. But unable to find a good document on how to connect Django and SAP HANA. Please suggest your opinion on this. Thank in advance :-) -
How can i get the average value of datas which is collected from endnode?
Hi everyone i am working on a project which is concerns endnode(sensor), IoT UI, and db simply. I'll try to summarize it. I have some endnodes which are supply some datas for me (temperature, humidity etc.) and i am showing them on and user-interface which is developed by django framework. Datas are collected for every 4 minutes(approximately). I want to show the daily average datas (for last 5 days) in my UI at the end of the day. I will show you my codes and my results following; models.py class DailySicaklikNemData(models.Model): endnode = models.ForeignKey(EndNode, on_delete=models.PROTECT, db_constraint=False) devEUI = models.CharField(verbose_name="Device EUI", max_length=255) company = models.ForeignKey(Company, on_delete=models.PROTECT, db_constraint=False) iaq = models.CharField(verbose_name="iaq", max_length=255) quality_condition = models.CharField(verbose_name="Quality Condition", max_length=255) date = models.DateField(verbose_name="Lora Data Send Time", default=datetime.now,blank=False) def __str__(self): return self.endnode.name class Meta: db_table = "temp_hum_daily_data" verbose_name = "Temp-Hum" verbose_name_plural = "Temp-Hum" ordering = ['-id'] views.py def sicaklikNemEndNode(request, devEUI): user = CheckUser(request) if user == 'none': return redirect('/user/login/') user_device = request.user_agent endnode = get_object_or_404(EndNode, devEUI=devEUI) data = getSicaklikNemEndNodeValue(endnode) dailyiaqdatas = DailySicaklikNemData.objects.filter(endnode=endnode).values('date', 'quality_condition').order_by('-date').annotate(iaq=Avg('iaq'))[:5] weather = getWeather(request) return render(request, "monitoring/sicaklik_nem_endnode.html", {'endnode': endnode, 'data': data, 'weather': weather, 'dailyiaqdatas': dailyiaqdatas, 'user_device': user_device}) and lastly html <div class="d-flex flex-row"> {% for data in dailyiaqdatas %} <div class="col text-center mt-3"> <p … -
Getting Mysql Connection Error with docker compose
I am trying to setup my development env using docker & docker compose.I am using Django with Mysql & phpymyadmin.Whener I run docker-compose up command my mysql & phpmyadmin images setups properly but my Django app fails & throws this error, django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '192.168.1.221' (115)") Here is my yaml file. version: '3.1' services: db: image: mysql restart: always environment: MYSQL_HOST: localhost MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: test MYSQL_ROOT_HOST: '%' ports: - "3308:3306" phpmyadmin: image: phpmyadmin/phpmyadmin:latest restart: always environment: PMA_HOST: db PMA_USER: root PMA_PASSWORD: root ports: - "8080:80" web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver" container_name: demo volumes: - .:/data ports: - "8000:8000" depends_on: - db networks: base: Here is my Dockerfile for django app. # Dockerfile FROM python:3.8 # install nginx RUN apt-get update && apt-get install nginx vim -y --no-install-recommends RUN pip install mysql-connector COPY nginx.default /etc/nginx/sites-available/default # RUN ln -sf /dev/stdout /var/log/nginx/access.log \ # && ln -sf /dev/stderr /var/log/nginx/error.log # The enviroment variable ensures that the python output is set straight # to the terminal with out buffering it first ENV PYTHONUNBUFFERED 1 # create root directory for our project in the container RUN … -
What is the difference between request.POST.get and request.GET.get in django
What is the difference between request.POST.get and request.GET.get in Django. I understand that when you use request.POST.get, you are trying to get data from front-end. In what situations will you require request.GET.get -
How to concatenate inputs of two charfields and store the result in another model in django?
This is my models.py.Here I want to create a username field such that it is concatenation of first name and registration ID of the users For Example: If, FirstName = Harry RegistrationID = 32pzc12 Then, Username=Harry_32pzc12 class User(models.Model): FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) RegistrationID = models.CharField(max_length=6) EmailID = models.EmailField(primary_key=True) Password = models.CharField(max_length=200) ProfilePicture = models.ImageField() MobileNumber = models.CharField(max_length=10) DateOfBirth = models.DateField() UserType = models.CharField(max_length=10,choices=UserTypeOptions) Description = models.TextField() -
How to replicate an entry in /etc/hosts file in Django/Heroku application? [duplicate]
I have a web URL which I can access only after I have added an entry into the /etc/hosts file which was <IP> <URL> But now I want to replicate the same thing in an online django application on heroku. How do I replicate this with code, either some library on python or some procedure on heroku? -
Django: Pass an url id to another url
I'm newer for Django. I'm trying to pass a id from 1st url to 2nd ur. In the list, the url has already have a id named order_id, I want to use this order_id to open another url to create a new content with this id. path('list-ordercontent/<order_id>', OrdercontentListView.as_view(), name='list-ordercontent'), path('create-ordercontent/<order_id>', create_ordercontent, name='create-ordercontent'), view.py class OrdercontentListView(ListView): model = Ordercontent template_name = 'store/list_ordercontent.html' context_object_name = 'ordercontent' def get_queryset(self): model = Ordercontent order = self.request.resolver_match.kwargs['order_id'] return model.objects.filter(order=order) in list-ordercontent.html, I tried to use same order_id to pass the variable I wanted, but it' incorrect. I want to know how to use the order_id into the another url, in my program it's the url for creating. <a href="{% url 'create-ordercontent' order_id %}">Add Product</a> -
How use Exists in Django 2.2
How to use or Exists in DJANGO 2.2 select distinct pcode as papercode, pname, from pap p inner join change syl on syl.syllabusyr=p.year where syl.admnyr='2021' and (pcode like '"HIN2"%' or exists(select * from paper_dep_maps where pcode =p.pcode and course_id='HIN' and paper_dep_maps.pcode like'___2%')) -
Django admin template overriding not working on hosting
In general, I have such a structure project |project/ |myapp/ |templates/ |admin/ |myapp/ |change_form.html in the html file this code {% extends "admin/change_form.html" %} {% block field_sets %} {# your modification here #} {% endblock %} everything is fine on the local server but when uploaded to the hosting, there are no changes. What is the problem ? -
How can i filter parent data on the basis of children data using django rest frameworks?
Suppose I've two models called A, B Eg: class A(models.Model): ............ ............ class B(models.Model): a = models.ForeignKey(A, ............) ............ Now I want to create filterset so that i can filter data from model A using on the basis of model B objects informations, I'm trying to achieve some thing like this but it is only working for field available in model A, Here is code snippets class ProductFilterSet(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr='gte') max_price = filters.NumberFilter(field_name="price", lookup_expr='gte') category = filters.ModelMultipleChoiceFilter(queryset=Category.objects.all()) company = filters.ModelMultipleChoiceFilter(queryset=Company.objects.all()) size = filters.ModelMultipleChoiceFilter(queryset=VariationSize.objects.all()) class Meta: model = Product fields = ['category', 'min_price', 'max_price', 'company', 'size'] It is working fine for min_price, max_price, category and company, But I'm getting invalid name in case of size because size field is only exists in model B. Here is screenshot snippets -
How to use model Field name in foreign key attribute limit_choice_to
I have 3 Models 1.CustomUser 2.ABC 3.XYZ CustomUser Model is an extended User Model. ABC Model class ABC(models.Model): class_name = models.CharField(max_length=255) profile_id = models.ForeignKey(CustomUser) class XYZ(models.Model): # This profile_id field is for knowing which user has created the following data profile_id = models.ForeignKey(CustomUser) processor = models.ForeignKey(ABC, limit_choices_to = {"profile_id": profile_id}) I want to add data in XYZ Model based on the profile_id field. The user who has created data in ABC Model can only add data in the XYZ model. Suppose User A didn't add data in ABC Model. but trying to add data in XYZ Model. If there is no instance of USer A in model ABC it should give validation error through Model only. I want to do this validation at Model Level. That's why I am using limit_choices_to. Thanks in Advance. If my question is not understandable. Please let me know -
How to add data from django database to autocomplete?
I am new to web development and I found this HTML code online that creates a dropdown input. I want to change the array that contains for all the countries to the names inside my database. this is the html that contains all the countries: var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central Arfrican Republic","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cuba","Curacao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauro","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & Caicos","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States of America","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"]; models.py: class employeeName(models.Model): employee = models.CharField(max_length=200) total_Hours_Worked = models.CharField(max_length=8, default="Empty") def __str__(self): return self.employee views.py def dropdown(response): form = employeeName() return render(response, "main/dropdown.html", {"form":form}) How do I insert the employee names into the countries array?