Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django funcion views, creating a company with user associated
So, i have this problem when im trying to create my "company", when i didnt have user authentication the view worked just fine. Now i've added django allauth, and this screen appears to me: enter image description here So i will leave here my model and my view to create the company Im just a begginner so sry for my bad explanation enter image description here enter image description here -
Is my payment processing secure (TLS) on Django/Heroku using Stripe
I'm using Stripe payment elements on my Django app hosted on Heroku. I have the following setting on: SECURE_SSL_REDIRECT = True What else do I need to do to make my website meet TLS? Do I need a TLS certificate from a site like Let’s Encrypt? -
Django Form Classes sometimes they don't appear?
This is the form below. Sometimes my form-control doesn't appear? I've used JQuery hasclass to check and add it if it fails. I just want to know why as my other forms are the same and work fine? Can't seem to figure out what the issue is. If anyone knows please let me know :) class holder_password_update_form(PasswordChangeForm): def __init__(self, user, *args, **kwargs): self.user = user super().__init__(user, *args, **kwargs) self.base_fields['old_password'].widget.attrs['class'] = 'form-control' self.base_fields['new_password1'].widget.attrs['class'] = 'form-control' self.base_fields['new_password1'].help_text = mark_safe('<p class="text-start" style="padding-left: 10px"> Your password can\'t be too similar to your other personal information, can\'t be a commonly used password, must contain at least 8 characters, 1 uppercase letter, 1 lowercase letter, 1 digit(s), 1 special character. </p>') self.base_fields['new_password2'].widget.attrs['class'] = 'form-control' self.base_fields['new_password2'].help_text = mark_safe('<p class="text-start" style="padding-left: 10px">Enter the same password as before, for verification.</p>') def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user -
Can you make a Django form dropdown box accept a model as its choices?
I have a real estate site where I am trying to be able to upload multiple photos to one 'property' without going through the django admin panel (so I can multi select photos.) Current view for custom built form I am able to choose multiple files, upload them to my 'uploads' folder and able to see them in the admin panel for databases. The issue is that the property name from the form I built doesn't connect the Property object to the Property Photos objects. Its just a null value. When I click on a Property Photo object only then does it assign the Property object to it. Property Photo objects BEFORE Property Photo object Once I click on it and push save Property Photo object After How do I get to be able to select (using a dropdown) a Property object from all my Property objects as a list and assign those photos uploaded to that Property object? Below are my: html form, models.py, views.py, and forms.py photo_upload.html <body> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="fs-1">Photo Upload</div> {{ image_form }} <button>Upload</button> </form> </body> models.py class Property(models.Model): class Meta: verbose_name_plural = 'Properties' address = models.CharField(max_length=150) slug = models.SlugField(unique=True, … -
Is it possible to have an input from a form in a html template be added to the url in a django project?
In the sidebar of my homepage, there is a search box where a user is meant to be able to type in the name of an entry and be taken to that page. So for example, if they type in css they would be taken to http://127.0.0.1:8000/wiki/css where the value inputted is appended to the url. (The home page url is http://127.0.0.1:8000/wiki/.) When I use the get method in the form it ends up searching up /wiki/?q=css instead of just having /css at the end of the url. However, when I use the post method in my form the url remains at http://127.0.0.1:8000/wiki/ with no additional url at the end. How do I append an input to the end of a url? HTML: <h2>Wiki</h2> <form action="/wiki/" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> urls.py: from tokenize import Name from unicodedata import name from django.urls import path from django.http import HttpResponse from . import views urlpatterns = [ path("", views.index, name="index"), path('hello/', views.hello, name='hello'), path('<str:name>', views.entry, name='entry'), path('new/', views.new, name='new'), path('random/', views.randomEntry, name='random') ] views.py: from django.shortcuts import render from django.http import HttpResponse from django import forms import random from . import util def index(request): return render(request, … -
how to check if a date is expired or not django?
I have a model that contains informations about trips and one field is a DateTimeField() like this: class Voyage(models.Model): voyid = models.CharField(max_length=20, primary_key= True) depart = models.CharField(max_length=30) destination = models.CharField(max_length=30) datedep = models.DateTimeField() #the datedep is the time and date of the trip departure And the result is a list of trips so i want to output only the trips that are not expired: (datedep > now), how do i do that? -
django.urls.exceptions.NoReverseMatch: Reverse for 'xyz' not found. 'xyz' is not a valid view function or pattern name
i have problem bcz i get: Powershell: django.urls.exceptions.NoReverseMatch: Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Project Schematic: https://ibb.co/g39qB9k Error during template rendering: https://ibb.co/k5k82V4 html: <a class="navbar-brand" href="{% url 'turbineweb:home_page' %}"> Turbine Power Web</a> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ms-auto"> {% if user.is_authenticated %} <li class="nav-item"><a class="nav-link" href="{% url 'accounts:logout' %}">Logout</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:password_change' %}">Change Password</a></li> {% else %} <li class="nav-item"><a class="nav-link" href="{% url 'accounts:login' %}">Login</a></li> **<li class="nav-item"><a class="nav-link" href="{% url 'accounts:register' %}">Register</a></li>** {% endif %} <li class="nav-item"><a class="nav-link" href="">Turbine Models</a></li> <li class="nav-item"><a class="nav-link" href="">Author</a></li> {% if user.is_company %} <li class="nav-item"><a class="nav-link" href="">My Models</a></li> {% endif %} <li class="nav-item"> Hello, {{ user.username|default:'Guest' }} </li> </ul> </div> views: def home_page(request): return render(request, 'turbineweb/home_page.html') project urls: urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls', namespace='accounts')), path('', include('turbineweb.urls', namespace='turbineweb')), ] accounts urls: app_name = 'accounts' urlpatterns = [ path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='accounts/login.html', authentication_form=LoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path('registration/', RegisterView.as_view(), name='users-registration'), path('password-change/', ChangePasswordView.as_view(), name='password_change'), path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] turbineweb urls: app_name = 'turbineweb' urlpatterns = [ path('home/', views.home_page, name='home_page'), ] -
Django, return a value to the HTML file from a view when using a form
My index.html file contains three forms, each connect to my views.py file and perform some function, everything is working fine but I am not understanding how to get a returned value back to my html page to display it. index.html: <html lang="en"> <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>Index</title> </head> <body> <form action="{% url 'start_or_end_fast' %}" method="POST"> {% csrf_token %} <button type="submit" name='start_fast' value='start_fast'>Add Fast</button> </form> <form action="{% url 'start_or_end_fast' %}" method="POST"> {% csrf_token %} <button type="submit" name='end_fast' value='end_fast'>End Fast</button> </form> <form action="{% url 'start_or_end_fast' %}" method="POST"> {% csrf_token %} <button type="submit" name='duration' value='duration'>Fast Duration</button> </form> <!-- DISPLAY FAST DURATION ON THE PAGE --> {% if duration %} <p>Fasting for {{duration}} </p> {% endif %} </body> </html> The third form is a button, when I press it the duration prints in the terminal. views.py code to do that: #If pressing Fast Duration button, show the duration difference between the current fast start_date_time and the current time elif request.method == 'POST' and 'duration' in request.POST: time_difference() return render(request,'startandstoptimes/index.html') else: return render(request,'startandstoptimes/index.html') def time_difference(): #Get the current date and time current_time = datetime.now().strftime(("%Y-%m-%d %H:%M:%S")) time_now = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S") #find the current fast that has not finished yet … -
Send Uint8List Image from Flutter to Django ImageField
Good day. I have an image of a signature, im using signature: ^5.0.1 for Flutter. I need to save it in to the ImageField. I haven't been able to save it in Django. this is my code inside flutter signaturePic(String imgName, SignatureController controller)async{ String completeUrl = '$rootApi/reports/signature_pic/'; var uri = Uri.parse(completeUrl); var request = http.MultipartRequest("POST", uri); Uint8List? signatureFile = await controller.toPngBytes(); if (signatureFile != null){ final multipartFile = http.MultipartFile.fromBytes(imgName, signatureFile); request.files.add(multipartFile); request.headers["authorization"]='TOKEN ${temp.apiKey}'; } } in Django 4.0 im using djangorestframework==3.13.1 class SignaturePicView(APIView): def post(self, request): try: for title, value in request.data.items(): items = title.split('__') is_return = True if items[5] == 'True' else False SignaturePic.objects.update_or_create( user=User.objects.get(id=request.user.id), unique_identifier=title, is_return=is_return, defaults={ 'image': value, } ) return Response(status=status.HTTP_201_CREATED) except ValueError as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST, data=e) this is the model in django class SignaturePic(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) date = models.DateField(auto_now_add=True) unique_identifier = models.CharField(max_length=220, null=True, blank=True) image = models.ImageField(upload_to='signatures/', null=True, blank=True) is_return = models.BooleanField(default=False) def __str__(self): return f"{self.unique_identifier} -> {self.date}" when it saves this is what I get. : �PNG IHDR�_>���sRGB���sBIT|d�IDATx��y|T�ـ���Lf&��KH�dGd�E(�@+�'"R-����+X~Z�¯h� |,� ���;(a��d�Lf2���1i��,!�I&�}��s����ߓ;�s�9�VKʃ�#Һ.@ �)��� ��؏���ٛ����p��� ��� �����>|e@�&s w��98s��:���=Hb��ۊ �������jDRI�W!KN�i���ױgeb;��H,�}����T�A�� ���h�T�~��:��0�X*���p�܊+�\����\? ��Uo�}&�J�*m } ނ3-}W�S�1���HRFh�4<�9���)Μ��!������������D�A,Eޤ���D�aH����`ٹ�ҵ�@��nЋ�; Gٶ/"��'�7.�l�;(Zt'~�"�q-~t� N�[t��Ll�� �( ��3ǽ�X���u�K��u�;��E?��[�'����[�0���cx�O����^��ts�k����!d�i$<�u�a�=W�Q��},�pZ�7����h{��Q��v-����!�m�8�--{��|A�z���9��{+�_��- 8-����8f>��Ի�8�-�9��kH��U�q�%����XD�U���וǥ�����&V)���)L���F��6$�̬�4 �S���8�e�BlY��R����2=��"�k^�X^�E��M%�s�lӇ�g�#5V�zA�z���e�Q�ͧ��b���~Xb�����V��M�[xe�I��"�=�ĉb��&,�a��A�1݀���@jhZ��E˧�vE�^$�����A���l��8���un?�>��{YrZ��,|��,��H���\U�8�8Q���̛��[xU�@��h٣ƱM�>�+�[ͻ7y1Rc�j�ĉ�gva��!��;P��~�ԝ�ql����G��E��c��'ͻ�(� N�<�����E�.F��~�k�L�y�`���W���YrI/f�l�@�C���M�uv7�C�t^�0fb��ǒ�L0��%O���~�o0<�F��V �S��X�}�u�'H�F\!�ID�1��!�I[��K���ف4���V��>6<�+ĩ�Ґ0�>�_n@����9F�6��'�`^;��q-H��YJzXs� NıY�u�2\yP��n��hz�ko�y,�R~��(Zt#y�ʈH�8�$�U�{��ၸ��J�<��[(Y� ���d+����}%�y~� Np�ڊy�;�/�8�-b��\� oR��=d��h�ۃțv�H�"�F�n;���q�+��țt"n�"����=���,��Ǚ���C?⵰��8aºo)e�߮l���A���A, {.g�vL+^@���,�5q�j�H��� A�b����V�|U��F�A�N�[������6��i+���T�������\=���)dI��G�A�k|�r���;,�7#��n�T��U/c?������ӣ$�\�|�_/Dz�C����1}��X�� �s\唬�����D���(���6��:�m}ۡ����hz?)�7�l�?"��A�*�<����xM��U�<4�� �H.������7��!oօ��/���TD�UA�*P��%��@�6����"v�qdo�xu��|�#��3���^Dr�A��`^?����5G��)O�>b�J��5�}��vS��E5�lIq�y�|ʶ�@����:"y�>�O��l�F�E�ح_��qn�y�|ʶ��0 �.G�kBD�x��0}��+ǐh�0��G��NqnA�Ǔ���DV��=�>}� … -
How can i print PDF with xhtml2pdf Django library on Heroku, when make deploy in Heroku doesn't work?
The library xhtml2pdf of Django doesn't work in Heroku, in local project works perfectly print PDF documents and credential after deploy Heroku not print PDF. The static files works because load the css and image just can't i print PDF references to be resolved using Django’s STATIC_URL and MEDIA_URL settings, xhtml2pdf allows users to specify a link_callback parameter to point to a function that converts relative URLs to absolute system paths. template/admin/credential.hmtl <!-- base.html --> {% load static %} <!doctype html> <html lang="es"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/material-design-iconic-font/2.2.0/css/material-design-iconic-font.min.css" integrity="sha256-3sPp8BkKUE7QyPSl6VfBByBroQbKxKG7tsusY2mhbVY=" crossorigin="anonymous" /> <title>Sentir Humano</title> <style> @page { size: A4; @frame content_frame { /* Content Frame */ left: 0pt; width: 587pt; top: 0pt; height: 700pt; } background-image: url('{% static "front/img/credential_front.png" %}'); } .test { font-size: 13px; } .person_id{ text-align: right; margin: 70px 50px 0px 205px; padding-top: 45px; } .first_name{ margin: 70px 0px 20px 45px; } .creator{ margin: 0 0px 0px 45px; } .date{ margin: 20px 0px 0px 45px; } .afiliado{ font-size: 14; margin-left: 45px; } </style> </head> <body> <table> <thead> <td class="test"> <p class="person_id">{{customer.person_id }}</p> <p class="first_name">{{ customer.first_name|upper }} {{ customer.last_name|upper }}</p> … -
My objects dublicate each other in django template
I'm trying to do my Django web-app and can't to overcome a problem. I need to split my model objects on two divs for correct display, but my dish objects just duplicate each other. I've tried to find info how to split my dishes objects on two parts and give them to html code, but it didn't works. Also there is can be a python templates solution, but I don't know how to resolve it, because the pure html code of project is something I never seen before (there is left-list and right-list classes for dishes columns, therefore we need to split our dishes dict somehow). There is 2 for loops because of the first row tag creates two col-lg-6 on left and right sides (this can be seen in the last image of page code of default template), maybe it's a bad idea. views.py: from django.shortcuts import render, redirect, HttpResponse from django.urls import reverse from .forms import ReserveForm from .models import ChefsModel, DishesModel # Create your views here. def reserve(request): chefs = ChefsModel.objects.all() dishes = DishesModel.objects.all() error = '' if request.method == 'POST': form = ReserveForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: error = 'Invalid form' else: form = … -
Ajax post multiple inputs
I have html input fields with the name personals. I use the [] such that I can have multiple inputs on the same name and post that. Before I was using a normal submit form. And I got it in my Django backend with getlist('personal[]') Everything worked as expected. As information: the codes are not complete. Just the most important lines are shown. My html code before <input type="text" name="personals[]" id="personals[]" placeholder='Email'> <input type="text" name="personals[]" id="personals[]" placeholder='Phone'> My view before def build(request): if request.user.is_authenticated: if request.method == 'POST': name = request.POST.get('name') personals = request.POST.getlist('personals[]') Now I am using Ajax to submit it, without reloading the page. It does not work anymore with personals[] therefore I have changed it too personals just without the parenthesis. The problem is, that personal contains only the first input. But not all the others. It is important to use the same input name (in this case personals) because I use some dynamic input fields, where the users can add more fields. Therefore I don't want to change the name to for example personals1 and personals2. My html code now <input type="text" name="personals" id="personals" placeholder='Email'> <input type="text" name="personals" id="personals" placeholder='Phone'> My view now def build(request): if … -
hCaptcha Doesn't Render When Window is Too Small
I am using hCaptcha with Django. I am using the django-hcaptcha plugin. It renders and works properly except when the screen is too small. This is what is looks like normally: but when the screen is to small, this is what it looks like: I can't figure out any settings to configure this. How can I make sure the hCaptcha still renders even if the screen is smaller? -
do django urls need "/" at the end of it?
I'm using the newest form of django and I'm just wondoring whether or not urls need a "/" at the end: path('home', Home.as_view(), name='home'), vs. path('home/', Home.as_view(), name='home'), Is there any difference between the two? -
My objects in django-templates duplicate each other
I'm trying to do my Django web-app and can't to overcome a problem. I need to split my model objects on two divs for correct display, but my dish objects just dublicate each other. I've tried to find info how to split my dishes objects on two parts and give them to html code, but it didn't works. Also there is can be a python templates solution, but I don't know how to resolve it, because the pure html code of project is something I never seen before (there is left-list and right-list classes for dishes columns, therefore we need to split our dishes dict somehow). views.py: def reserve(request): chefs = ChefsModel.objects.all() dishes = DishesModel.objects.all() error = '' if request.method == 'POST': form = ReserveForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: error = 'Invalid form' else: form = ReserveForm() return render(request, 'main/index.html', {'form':form, 'error':error, 'chefs':chefs, 'dishes':dishes, }) def index(request): return reserve(request) My Django template + HTML: <article id='tabs-1'> <div class="row"> {% for i in n %} <div class="col-lg-6"> <div class="row"> <div class="{% cycle 'left' 'right' %}-list"> {% for dish in dishes %} {% if dish.tabs == 'Breakfast' %} <div class="col-lg-12"> <div class="tab-item"> <img src="{{ dish.image.url }}" alt=""> <h4>{{ dish.name }}</h4> … -
What Python package to do mapping like Zillow? [closed]
We currently have lots of address data with longitude and latitude. I want to display data in the same way as Zillow does with a map on the left and property information on the right. I also need: additional property info is possible when clicking a point filters on the top property images on the right of filtered results Zillow is using Google Maps API, but we can use either that or Open Street Maps. What is the easiest way to do that on a Django server with a React front end? Packages or strategy is deeply welcome. -
How to add to Django Rest framework
Currently I have the following: backend/urls.py from django.contrib import admin from django.db import router from django.urls import path, re_path, include from pages import views from rest_framework import routers from reactUI import reactViews router = routers.DefaultRouter() router.register(r'reactCluster',reactViews.reactUIClusterView,'reactUI') urlpatterns = [ path('admin/', admin.site.urls), path('', views.homeView, name='home'), re_path(r'^getdata/',views.homeView), re_path(r'^loadAPI/',views.loadAPI), path('api/', include(router.urls)), ] backend/reactUI/reactViews.py from django import views from django.shortcuts import render from rest_framework import viewsets from .serializers import reactUIClusterSerializer from .models import reactUICluster # Create your views here. class reactUIClusterView(viewsets.ModelViewSet): serializer_class = reactUIClusterSerializer queryset = reactUICluster.objects.all() #helps with crud ops backend/reactUI/models.py from django.db import models from pandas import describe_option class reactUICluster(models.Model): title = models.CharField(max_length=200) physicalCPU = models.IntegerField() virtualCPU = models.IntegerField() #maybe add a list feild in cluster class def __str__(self) -> str: return self.title backend/reactUI/serializers/py from rest_framework import serializers from .models import reactUICluster class reactUIClusterSerializer(serializers.ModelSerializer): class Meta: model = reactUICluster fields = ('id', 'title', 'physicalCPU', 'virtualCPU') Front end in react import React, { Component, useState } from "react"; ~bunch of random other imports let counter = 0; function RefreshList() { const [row, setRow] = useState([]) const payload = { title :'a', physicalCPU:'b', virtualCPU:'c' } const axiosPost = () => { axios.post("http://localhost:8000/api/reactCluster/",payload).catch((err) => console.log(err)) } const axiomCall = () => { console.log("FF"); axios .get("http://localhost:8000/api/reactCluster/") … -
request.user.group returns auth.Group.None for Django custom user model
Created custom user model, initially without PermissionsMixin, then realized, that I will need it, and added. Makemigrations, migrate - done. class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] first_name = models.CharField(max_length=50, blank=True, null=True) middle_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) [..] Solution, works partially. I can add user to the group, db is updated, can see the relation, but user.groups returns None. What am I doing wrong? How to troubleshoot it? for group in Group.objects.filter(): print(group, group.id) request.user.groups.add(Group.objects.get(id=2)) print(Group.objects.get(user=request.user)) print(request.user.groups) gives output: individual_customers 1 business_customers 2 staff 3 business_customers auth.Group.None -
How do I iterate through my django model to be able to generate the weather info for each city? The db is showing info for the first city name only
Note: The output of the weather info doesn't contain info for all of the city names after iteration. It is only returning info for the first city name in the database. Note: The output of the weather info doesn't contain info for all of the city names after iteration. It is only returning info for the first city name in the database. models.py from django.db import models from pytz import timezone # Create your models here. class city(models.Model): name=models.CharField(max_length=40) def __str__(self): return self.name class weather(models.Model): City=models.ForeignKey(city, null=True, on_delete=models.CASCADE) country=models.CharField(max_length=40) timezone=models.CharField(max_length=40) temperature=models.FloatField() humidity=models.FloatField() status=models.CharField(max_length=40) def __str__(self): return self.country serializers.py from rest_framework import serializers from .models import weather,city class CitySerializers(serializers.ModelSerializer): class Meta: model=city fields='__all__' class WeatherSerializers(serializers.ModelSerializer): class Meta: model=weather fields='__all__' views.py from django.shortcuts import render import requests from .models import weather,city from .serializers import WeatherSerializers from rest_framework.decorators import api_view from rest_framework.response import Response from geopy.geocoders import Nominatim # Create your views here. @api_view(['GET']) def weatherinfo(request): Cit=city.objects.all() geolocator=Nominatim(user_agent="christopherleon237@gmail.com") key= '1824949f0261346c55b64d82f091072a' for obj in Cit: #cit=city.objects.get(city,id=obj) location=geolocator.geocode(obj) coordinates=(location.latitude,location.longitude) lat=coordinates[0] long=coordinates[1] url='https://api.openweathermap.org/data/2.5/weather?lat={}&lon= {}&appid={}'.format(lat,long,key) city_weather=requests.get(url).json() weather_data=weather.objects.create( City=obj, country=city_weather['sys']['country'], timezone=city_weather['timezone'], temperature=city_weather["main"]["temp_max"], humidity=city_weather["main"]["humidity"], status=city_weather["weather"][0]["description"], ) serializer=WeatherSerializers(weather_data, many=False) return Response(serializer.data) Note: The output of the weather info doesn't contain info for all of the city names after iteration. It … -
Reading and Writing to different S3 buckets with s3boto3storage and django
I've been working off a series of tutorials and have my django photo gallery uploading images to an AWS S3 bucket named "sitename-org" using S3Boto3Storage. I have an AWS Lambda that creates a thumbnail from it and puts it in a different bucket named "sitename-org-resized". I cannot figure out how to make a thumbnail member in Photo class that pulls the image (same filename) from the -resized bucket. This was my latest attempt. class Photo(models.Model): exclude = ('thumbnail',) title = models.CharField(max_length=100) image = models.ImageField(null=False, blank=False, upload_to='gallery_photos') date_uploaded = models.DateTimeField(default=timezone.now) thumbnail = models.ImageField(storage=S3Boto3Storage(bucket_name='sitename-org-resized'), null=True, blank=True) uploader = models.ForeignKey(User, on_delete=models.CASCADE) album = models.ForeignKey(PhotoAlbum, on_delete=models.SET_NULL, null=True, blank=True, related_name='photos') description = models.TextField() def save(self, *args, **kwargs): # super().save(*args, **kwargs) thumbnail = self.image -
django kanban type board sorting at volume
I have a django app with tasks stored in a database, similar to a kanban board type layout and each record has a column and order for where they are in the list. The problem is this list can get to hundreds or thousands of records in one column, on changing column based on where the user places the card the column is updated and order is recalculated/set for all records in that column. Is there a more efficient way than a heavy process updating thousands of records to set order? -
Alternative of DISTINCT ON in Sqlite database
Suppose, I got the following model named table ,say |title | author |version | ....| |:-----| :------|:------:|----------- |python| someone| 1.0 | .... | |python| someone |2.0 | .... | |c++ | random | 1.0 | .....| | c | me | 1.0 | .... | |c | me |2.0 | .... | What I want here is a table with no repeating values in the title field . I've tried with table.objects.distinct("title") I came to no that this is only supported in postgress. Is there any alternative of this on sqlite database? -
Running drowsiness detection python file by clicking a button using django
I am doing a capstone project related to a drowsiness detection system, I have written a python file that pops up the web camera and detects drowsiness from the face. I have made a Django website to run this detection system. I want that this python file that just pops up the web camera and detects drowsiness of a person run by clicking an HTML button but I'm unable to find that, how can I make this possible -
How Can I Use This MongoDB Object In Django Field ( Djongo, MongoDB, PyMongo ]
What Is Name Of This MongoDb Object On Django Or Djongo Fields? -
Why does .save() still take up time when using transaction.atomic()?
In Django, I read that transaction.atomic() should leave all the queries to be executed until the end of the code segment in a single transaction. However, it doesn't seem to be working as expected: import time from django.db import transaction my_objs=Obj.objects.all()[:100] count=avg1=0 with transaction.atomic(): for obj in my_objs: start = time.time() obj.save() end = time.time() avg1+= end - start count+= 1 print("total:",avg1,"average:",avg1/count) Why when wrapping the .save() method around a start/end time to check how long it takes, it is not instantaneous? The result of the code above was: total: 3.5636022090911865 average: 0.035636022090911865 When logging the SQL queries with the debugger, it also displays an UPDATE statement for each time .save() is called. Any ideas why its not working as expected? PS. I am using Postgres.