Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't Populate Database by excel file in Django ( Management Command )
Management Command (populatedb.py) import pandas as pd from django.core.management.base import BaseCommand from django.apps import apps class Command(BaseCommand): help = "Creating model objects according the file path specified" def add_arguments(self, parser): parser.add_argument('--path', type=str, help="file path") parser.add_argument('--model_name', type=str, help="model name") parser.add_argument('--app_name', type=str, help="django app name that the model is connected to") def handle(self, *args, **options): file_path = options['path'] _model = apps.get_model(options['app_name'], options['model_name']) df = pd.read_excel(file_path) header = list(df.columns) for row in df: _object_dict = {key: value for key, value in zip(header, row)} _model.objects.create(**_object_dict) Terminal Error: ValueError: Cannot assign "'a'": "State.country" must be a "Country" instance. -
Django filter specific attributes from API response
I'm working with TMDB API and i want to get the specific video from a dictionary of videos that is the main trailer of a movie. movie_video_request = requests.get("https://api.themoviedb.org/3/movie/" + str(movie_id) + "/videos?api_key=" + TMDB_API_KEY) movie_video_results = movie_video_request.json() movie_videos = movie_video_results['results'] newDict = dict() for key,value in movie_videos.items(): if key == 'name' and value == 'Official Trailer': newDict[key] = value return render(request, 'Movie Details.html', {'newDict ':newDict }) My API response "results": [ { "iso_639_1": "en", "iso_3166_1": "US", "name": "Walking Corpses Clip", "key": "GGe_h2MWMrs", "site": "YouTube", "size": 1080, "type": "Clip", "official": true, "published_at": "2022-01-29T17:00:39.000Z", "id": "61f77629bb105700a0b16a3f" }, { "iso_639_1": "en", "iso_3166_1": "US", "name": "Official Trailer", "key": "JfVOs4VSpmA", "site": "YouTube", "size": 1080, "type": "Trailer", "official": true, "published_at": "2021-11-17T01:30:05.000Z", "id": "61945b8a4da3d4002992d5a6" }, { "iso_639_1": "en", "iso_3166_1": "US", "name": "The New Spider-Man Title is…", "key": "iqyPvdsOWKk", "site": "YouTube", "size": 1080, "type": "Teaser", "official": true, "published_at": "2021-02-24T17:44:20.000Z", "id": "60378fdcd132d60040a45d96" } ] I want my result to be that of the Official Trailer {key": "JfVOs4VSpmA"} so that I can place it in an <a href> tag <a href="https://www.youtube.com/watch?v={{ newDict.value }}"> <p> Watch Trailer </p> </a> I'm getting an error Exception Value: 'list' object has no attribute 'items' -
React Native FormData not being sent to Django API
I have created a simple Register page in Expo CLI but when I try to send the data to my Django Server it is not receiving the actual content like email password etc. I have tested this API with Postmen its working fine there, any idea what might be causing this? Here is the working example from Postmen Postmen Working Api Calls Here is the Console Log Output From the vscode terminal And my Register.js Code import { View, Text, StyleSheet, KeyboardAvoidingView, Image, } from "react-native"; import React from "react"; import { Button, SafeAreaView } from "react-native"; import { TextInput, TouchableOpacity } from "react-native-gesture-handler"; import * as ImagePicker from "expo-image-picker"; import axios from "axios"; import { auth_URL } from "../config/env"; const Register = ({ navigation }) => { const [image, setImage] = React.useState(null); const [userData, setUserData] = React.useState({ username: "", email: "", password: "", confirm_password: "", }); const pickImage = async () => { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [4, 3], quality: 1, }); console.log(result); if (!result.cancelled) { setImage(result.uri); } }; var data = new FormData(); data.append("username", userData.username); data.append("email", userData.email); data.append("password", userData.password); data.append("re_password", userData.confirm_password); data.append("image", { uri: image, type: "image/jpeg", name: "image.jpg", }); const handleSubmit … -
Save Logs inside Django container to AWS S3
Hey i have a docker Django app deployed on AWS. i am having trouble figuring out a way to store the logs generated inside the container, whenever i build it again the logs are delete. i want to store the logs to S3 maybe using a CRON job. one thing i can do is docker-compose -f docker-compose.prod.yml exec web tail django.log > django.log this gets the logs out. but there is also a directory that has sub directories that has logs for scrappy. they also need to be stored on s3 once a day. any guide will help. thanks! -
EditUserForm() create a new user insted of editing the correct one in Django
I'm new to Django and I'm building my first website. I'm now in the phase of creating the register/edit profile pages. I have correctly created my register page but I'm having a hard time creating the edit profile page. My profile has the classic fields username, first name, last name, email, password. On my edit page, I would like to be able to modify only the email field. For some reason, instead of editing the current user, my edit profile page creates a new user with every field blank except for the one I've edited. My code can be found below. urls.py urlpatterns = [ path('register', views.register_user, name="register"), path('account', views.account_user, name="account"), ] views.py @unauthenticated_user def register_user(request): if request.method == "POST": form = RegisterUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, "Registration Succesfully") # ogni utente è associato ad un gruppo univoco Group.objects.get_or_create(name=username) group = Group.objects.get(name=username) group.user_set.add(user) user.save() else: pass else: form = RegisterUserForm() return render(request, 'authenticate/register_user.html', { 'form': form, }) @authenticated_user def account_user(request): if request.method == "POST": form = EditUserForm(request.POST) if form.is_valid(): form.save() else: pass else: form = EditUserForm() return render(request, 'authenticate/account.html', { 'form_edit': form, }) forms.py class RegisterUserForm(UserCreationForm): email = … -
django: how to render and redirect page together at same time
I have a home page (OnlinePricing.html) as form for user to input some information. After input some required information, if the user click the button "Get Pice", the price will be shown in the botton page (here I am using htmx to partially refresh the home page). if the user click the button "Order Now", it will need to redirect to the new page called CreateOrder.html at path: "homepage/order/", where the price will be shown in this new page. below is the full codes. The current problem is related to the function of CreateOrder in veiws.py. When click "Order Now", the page redirect but with some wrong information: NoReverseMatch at /order/ Reverse for 'CreateOrder' with keyword arguments '{'kwargs': {'pickup_address': 'xxx', 'delivery_address': 'xxx', 'distance': xxx, 'charge': xxx}}' not found. 1 pattern(s) tried: ['order\\/\\Z'] #views.py def OnlinePricing(request): result = 0 pickup_date = "" pickup_address = "" delivery_address = "" weight = 0 volume = 0 height = 0 stack = "" FTL = "" time_window = "" dist = "" charge = "" navi_load = "" navi_unload = "" error_message = "" try: if request.method == "POST": # print("REQUEST ", request.POST) pickup_date = request.POST.get('pickup_date') pickup_address = request.POST.get('pickup_address') delivery_address = request.POST.get('delivery_address') weight = … -
Django downloading excel file return object name instead of excel file
I have a website where we download a xl file i have my view as below instead of returning the excel file its returning the text file with name of the object inside it how do i solve this views.py: @api_view(['GET',]) def my_view(request): file = model.objects.first() response = HttpResponse(file, content_type=' application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel', ) return response urls.py: path('temo/fill',views.my_view,name = 'my-view') -
django-filter no exception message supplied
when i try to use my django-filter MultipleChoiceFilter I get a 'No exception message supplied' But my other filter works fine, anyone has any idea why? my filter.py: choices = (('white','white'),('red','red')) class filtering(django_filters.FilterSet): title = django_filters.CharFilter(field_name='title',lookup_expr='icontains') color = django_filters.MultipleChoiceFilter(choices=choices) class Meta: model = Cars fields = ['title','color'] -
Django channels served with gunicorn with --preload can't connect to unix socket
I'm working on a web app that uses django channels for websocket communication. On production im using gunicorn with uvicorn workers, behind Nginx, proxying via unix socket. My objective is to have code executed only once (to log configuration and schedule jobs with APScheduler), when the app starts. Considering this asgi.py file: import os from django.core.asgi import get_asgi_application from .startup import run_at_startup os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tcpy.settings') django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import tcpy.routing application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter( tcpy.routing.websocket_urlpatterns ) ), }) run_at_startup() I found that using --preload argument in gunicorn, makes the run_at_startup function run only once per boot. The problem is that gunicorn cannot connect to the unix socket. If i take the --preload, everything works fine but run_at_startup will run once per worker process (i dont want that). This is my systemd configuration file to create the socket ( /etc/systemd/system/tr_gunicorn.socket ): [Unit] Description=Testrune unix-socket for http communications (nginx<>gunicorn) [Socket] ListenStream=/run/tr_gunicorn.socket SocketUser=testrune SocketGroup=www-data [Install] WantedBy=sockets.target And this is the file that launches gunicorn ( /etc/systemd/system/tr_gunicorn.service ): [Unit] Description=Testrune Webserver Requires=tr_gunicorn.socket After=network.target [Service] EnvironmentFile=/etc/testrune/environment.env User=testrune Group=www-data WorkingDirectory=/home/testrune/tcpy_srv/testrune/tcpydev/tcpy/ ExecStart=/home/testrune/tcpyenv/bin/gunicorn tcpy.asgi:application -w 2 -k uvicorn.workers.UvicornWorker --bind unix:/run/tr_gunicorn.socket --forwarded-allow-ips='*' --preload Restart=on-failure [Install] WantedBy=multi-user.target These … -
how to create a like a contest db and set , get data in to that in django?
I don't get the idea how create such like one , and how to get and set data in to that. actually what i exact need is : models.py class Contest(models.Model): title = models.CharField(max_length=50) want to create lot of Contests using this models after that user can select that contests using the Contest title . also want to show their name based on User name . class Contest_Candidates(models.Model): image = models.FileField( upload_to="contest_candidates/",) owner = models.ForeignKey(User, on_delete=models.CASCADE) contest = models.ForeignKey(Contest, on_delete=models.CASCADE,) def likes_count(self): return self.likes.all().count() also want to show each post get likes: class CandidateLikes(models.Model): like = models.CharField(max_length=10) user =models.ForeignKey(User,on_delete=models.CASCADE,related_name='candidate_likes') contest_candidates = models.ForeignKey(Contest_Candidates, on_delete=models.CASCADE, related_name='likes') in a user view : contest # contest_name 1 first contest 2 second contest when a user click the first contest , user can post based on . in a admin view: contests : 1 first contest 2 second contest when click the first contest want to show all users who posted in first contest. also want to show their like count. if click the second contest want to show all users who posted in second contest ... i don't know explain this. how to do this ? what to write in the views.? . what … -
How to delete data by force using djnago orm?
I have multiple table connected to each other and one table that is connect to that network. Now I want to delete the first table and all the data related to that foreign key. -
django form only requesting GET
I'm new to Django and I was working in custom user registration form but everytime when I tried to register the form only sends GET request and it doesn't register it just reloads the page Here is my code template register.html {% extends 'main.html' %} {% block content %} <div class="content-section"> <form method="POST">{% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {% for field in registeration_form %} <p> {{field.label_tag}} {{field}} </p> {% endfor %} </fieldset> <div class="form-group"> <input class="btn btn -outline-info" type="submit"> </div> </form> <div class="norder-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign in</a> </small> </div> </div> <style> .content-section { margin-right: auto; margin-left: auto; display: block; width: 400px; margin-top: 100px; margin-bottom: 60px; } input { opacity: 0.3; border-radius: 20px; padding: 10px; width: 80%; display: block; margin-right: auto; margin-left: auto; margin-bottom: 10px; box-shadow: none; color: #fff; border: none; background-color: #5d5d5d; transition: 1s; border: 2px solid transparent; } </style> {% endblock content %} -
Why can't I use SoftDeletableModel and TimeFramedModel together in Django model?
I need a model that should be soft deletable (not actually deleting from DB) and should have start and end timestamps. I've used SoftDeletableModel and TimeFramedModel from django-model-utils library for this purpose. This is my models.py from model_utils.models import TimeFramedModel, SoftDeletableModel class Quiz(SoftDeletableModel, TimeFramedModel): """ Model for quiz """ total_questions = models.PositiveSmallIntegerField(_("Total no of questions")) duration = models.PositiveSmallIntegerField(_("Duration (in mins)")) This works fine in shell as well as in the APIs. But I'm not able to see any data in Django admin. I tried using one of them at a time, and it works fine. I checked the data using shell as below: >>> from apps.quiz.models import Quiz >>> Quiz.objects.all() <SoftDeletableQuerySet [<Quiz: Mathematics Quiz>, <Quiz: Mathematics Weekly Quiz>, <Quiz: Monday GK Quiz>]> And this is what I see in Django admin: Now I've two questions here: What is the reason I get no data in admin panel when using both together? How can solve this issue while using these prebuilt model classes only? (If its possible) Any help is really appreciated. Thank You !! -
Is it possible to pass a value from HTML page to Django view using GET method?
I have a base sidebar that contains two items page1 and page2. When the user clicks on an item, it will render the corresponding page. I also have a filter in the sidebar that allows the user to filter the results on the page by type. I am able to see to appropriate results on the page when I choose a filter, but my aim is to make the system remember the last filter selection so when the user chooses a new page, it will automatically show the results by the last selected filter. can this be done by sending the variable 'type' through the GET method? or any other solution would be appreciated. in base.html, Rendering a New Page via Get method <div id="page" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <a class="collapse-item" href="page1">Page1</a> <a class="collapse-item" href="page2">Page2</a> </div> </div> in base.html, Filtering the current page via POST method <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Filter By Type:</h6> <form name="modality" action="" id='type' method="post" enctype="multipart/form-data"> {% csrf_token %} <input class="collapse-item" name ='type' type="submit" value="type1" onclick="this.form.submit()"> <input class="collapse-item" name ='type' type="submit" value="type2" onclick="this.form.submit()"> <input class="collapse-item" name ='type' type="submit" value="type3" onclick="this.form.submit()"> </form> </div> </div> django view: @login_required(login_url='login') … -
How can I get Live feed using python and ngrok
I am working on python and trying to get live feed using OpenCV. I am getting connection refused error like ([tcp @ 0x7f5708007bc0] Connection to tcp://8.tcp.ngrok.io:XXXXX?timeout=0 failed: Connection refused). here is the code :- from django.shortcuts import render from django.shortcuts import render, HttpResponseRedirect from django.http import HttpResponse from pyngrok import ngrok import requests import urllib.request as urllib2 import cv2 import numpy as np import imutils # Create your views here. def home( request ): text='welcome' videostatus = '' cap = cv2.VideoCapture("rtsp://8.tcp.ngrok.io:XXXXX/xULB2YaQYlDGmrGs") FRAME_WIDTH = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) FRAME_HIGTH = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) print('Frame Size: ', FRAME_WIDTH, 'x', FRAME_HIGTH) if cap.isOpened(): ret, frame = cap.read() videostatus = "rtsp feed is working" else: ret = False videostatus = "not working! please check your rtsp feed" while ret: ret, frame = cap.read() cv2.imshow('Camera', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() return HttpResponse(text) Please help me to get proper response. -
Getting ID of the Category from foreign key But I want title attached to Category Model
I don't want id to serialized in the api when i fetch data of the product model, but just want attached title to the category model For now this is how the data look like. GET /api/v1/catalogue/1/ { "id": 1, "name": "iPhone 13", "image": "/mediafiles/products/2022/01/30/product-placeholder.png", "timestamp": "2022-01-30T22:52:11.259452+05:00", "updated": "2022-01-30T22:52:11.259452+05:00", "variant": "8gb Ram / 256 Storage", "product_brand": 1, "product_category": [ 1 ] } As u see the product_category giving me the set of id's instead of title. these are the two models class Category(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='Categories/%Y/%m/%d', null=True, blank=True, default='/category-placeholder.png') ... class Product(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='products/%Y/%m/%d', null=True, blank=True, default='/product-placeholder.png') product_category = models.ManyToManyField( Category, related_name="product_category") product_brand = models.ForeignKey( Brand, on_delete=models.CASCADE, related_name="product_brand" ) ... So I don't know how to put title inside product_category set instead of there id's -
filter a request in django serializer with the current logged-in user
Help please, So, I am making a request with a serializer and what I need is to filter the response by current logged-in user. I was thinking about doing the request using serializerMethodField but it's a read-only type so I could not do anything with it after. Specially this code line which is necessary for my form, because it will retrieve all wallet linked to the current user into a select field, won't work : to = serializers.PrimaryKeyRelatedField(queryset=serializers.SerializerMethodField('get_user_wallets')) I thought also about the way of castrate the return type that I will get from get_user_wallets method into something that I can use as a queryset. But it seems not easy to do it. Maybe someone has a better approach of doing what I want. Bellow is the code : class TransactionSerializer(serializers.HyperlinkedModelSerializer): to = serializers.PrimaryKeyRelatedField(queryset=serializers.SerializerMethodField('get_user_wallets')) class Meta: model = Transaction fields = ['amount', 'to'] def get_user_wallets(self, obj): request = self.context.get('request', None) if request: wallet = Wallet.objects.filter(user_id=request.user.pk) return wallet Thank you for your answers and suggestions. -
Python string encode not working for rest api headers
I am sending a blob string in the rest API headers as a token. Which I want to access and covert it into btyes bob = request.META.get('HTTP_BLOB_TOKEN') bob_encoded = bob.encode() String raw blob \x01\x02\x02\x00xM\xc3\xa3\xc2\x98\xc2\xac\xc3\xb7\xc3\x87\xc2\xaf\x7f\xc2\x95q\xc3\x85R\xc3\x8ae\xc3\x80\xc2\xa9\xc3\x90\xc3\x85\xc2\xa9\x15\xc3\x82=\xc2\xa0N\xc2\x88\xc3\xaf#5x=\x01%\x0e\xc2\xa8aT\xc3\x8a\xc3\x81\xc3\x92"\xc2\xa0\x04N$GF\x00\x00\x00h0f\x06\t\xc2\x86H\xc2\x86\xc3\xb7\r\x01\x07\x06\xc2\xa0Y0W\x02\x01\x000R\x06\t\xc2\x86H\xc2\x86\xc3\xb7\r\x01\x07\x010\x1e\x06\t`\xc2\x86H\x01e\x03\x04\x01.0\x11\x04\x0c\xc2\x9e\x12\xc3\x82\xc2\x8bi\xc2\xb7\xc3\x93+\x18\xc3\xbfs\xc2\x97\x02\x01\x10\xc2\x80%p\xc2\xb3\xc2\x9b\x03%X\xc3\x8a\xc2\xad\xc3\xb1Cbi=w\xc3\xa9\xc3\x9f\xc2\xb0\x18nK7\xc2\x9a\xc3\x90\xc3\x9e\xc3\xb3HB\xc3\xbd\xc3\x94\x07\xc3\xba\xc3\x83\x1c\xc3\x8f\xc3\x96\x0e2* Expected blob in byte b'\x01\x02\x02\x00xM\xc3\xa3\xc2\x98\xc2\xac\xc3\xb7\xc3\x87\xc2\xaf\x7f\xc2\x95q\xc3\x85R\xc3\x8ae\xc3\x80\xc2\xa9\xc3\x90\xc3\x85\xc2\xa9\x15\xc3\x82=\xc2\xa0N\xc2\x88\xc3\xaf#5x=\x01%\x0e\xc2\xa8aT\xc3\x8a\xc3\x81\xc3\x92"\xc2\xa0\x04N$GF\x00\x00\x00h0f\x06\t\xc2\x86H\xc2\x86\xc3\xb7\r\x01\x07\x06\xc2\xa0Y0W\x02\x01\x000R\x06\t\xc2\x86H\xc2\x86\xc3\xb7\r\x01\x07\x010\x1e\x06\t`\xc2\x86H\x01e\x03\x04\x01.0\x11\x04\x0c\xc2\x9e\x12\xc3\x82\xc2\x8bi\xc2\xb7\xc3\x93+\x18\xc3\xbfs\xc2\x97\x02\x01\x10\xc2\x80%p\xc2\xb3\xc2\x9b\x03%X\xc3\x8a\xc2\xad\xc3\xb1Cbi=w\xc3\xa9\xc3\x9f\xc2\xb0\x18nK7\xc2\x9a\xc3\x90\xc3\x9e\xc3\xb3HB\xc3\xbd\xc3\x94\x07\xc3\xba\xc3\x83\x1c\xc3\x8f\xc3\x96\x0e2'* Current output b'\x01\x02\x02\x00xM\xc3\xa3\xc2\x98\xc2\xac\xc3\xb7\xc3\x87\xc2\xaf\x7f\xc2\x95q\xc3\x85R\xc3\x8ae\xc3\x80\xc2\xa9\xc3\x90\xc3\x85\xc2\xa9\x15\xc3\x82=\xc2\xa0N\xc2\x88\xc3\xaf#5x=\x01%\x0e\xc2\xa8aT\xc3\x8a\xc3\x81\xc3\x92"\xc2\xa0\x04N$GF\x00\x00\x00h0f\x06\t\xc2\x86H\xc2\x86\xc3\xb7\r\x01\x07\x06\xc2\xa0Y0W\x02\x01\x000R\x06\t\xc2\x86H\xc2\x86\xc3\xb7\r\x01\x07\x010\x1e\x06\t`\xc2\x86H\x01e\x03\x04\x01.0\x11\x04\x0c\xc2\x9e\x12\xc3\x82\xc2\x8bi\xc2\xb7\xc3\x93+\x18\xc3\xbfs\xc2\x97\x02\x01\x10\xc2\x80%p\xc2\xb3\xc2\x9b\x03%X\xc3\x8a\xc2\xad\xc3\xb1Cbi=w\xc3\xa9\xc3\x9f\xc2\xb0\x18nK7\xc2\x9a\xc3\x90\xc3\x9e\xc3\xb3HB\xc3\xbd\xc3\x94\x07\xc3\xba\xc3\x83\x1c\xc3\x8f\xc3\x96\x0e2'* -
Djano email with ics file doesn't adding event in google calendar
I am developing a web application. In there I am creating a zoom meet and send it with email. So i created ics file using django ics this package. The email is getting successfully. And there is an ics file as attachment. But it does not make an event in my google calender. My code is # Creating ICS file for calender invite calendar = Calendar() event = Event() event.name = meet.title event.begin = meet.meet_start_date_time event.end = meet.meet_end_date_time event.organizer = partner_user.email event.uid = meet.zoom_uuid event.url = meet.join_url calendar.events.add(event) filename_event = 'invite-%d.ics' % meet.id with open(filename_event, 'w') as ics_file: ics_file.writelines(calendar) email = EmailMultiAlternatives(subject, plain_message, from_email, [to]) email.attach_alternative(html_message, 'text/html') email.attach_file(filename_event, 'text/calendar') email.send(fail_silently=True) os.remove(filename_event) I am using a stack overflow answer answer as a reference. Can anyone help me to solve this. Thanks in advance. -
Django and channels, expose model data via websockets after save
I am new to websocket and channel with django. In my django project i would to expose saved data after a post_save event occur in a specific model via websocket. I have django 3.2 and i install: channels==3.0.4 channels-redis==3.3.1 then in my settings.py i add channels to my app list and set: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { 'hosts': ["redis://:myredishost:6379/0"], }, 'ROUTING': 'backend.routing.channel_routing', } } chenge my application from WSGI to ASGI: ASGI_APPLICATION = "backend.asgi.application" then i try to create the routing.py file like this: from channels.routing import route from alarms.consumers import ws_connect, ws_disconnect channel_routing = [ route('websocket.connect', ws_connect), route('websocket.disconnect', ws_disconnect), ] and connect and disconnect methods (insert every connected user ubto User group for now): from channels import Group def ws_connect(message): Group('users').add(message.reply_channel) def ws_disconnect(message): Group('users').discard(message.reply_channel) now i have an Results_Alarms model: # Model of Alarms data class Results_Alarm(models.Model): id = models.AutoField(primary_key=True) var_id = models.ForeignKey('modbus.ModbusVariable', null=True, on_delete=models.SET_NULL) calc_id = models.ForeignKey(CalcGroup, null=True, on_delete=models.SET_NULL) templ_id = models.ForeignKey(AlarmsTemplate, null=True, on_delete=models.SET_NULL) a_trigger = models.CharField(max_length=200, verbose_name="Alarm trigger") dtopen = models.DateTimeField(verbose_name="Date of error") e_status = models.ForeignKey(AlarmStatus, null=True, on_delete=models.SET_NULL) dtclose = models.DateTimeField(verbose_name="Date of resolution", null=True, blank=True) u_involved = models.ForeignKey('accounts.CustomUser', related_name='oumanager', on_delete=models.CASCADE, null=True) ... I also create the signals.py file for manage the post_save event: … -
Django/authentification: how to make login page = home page?
I develop Django web app using Django authentification backend. It works without having to define any views or forms, only template to 'bootstrap' it. But I would like to change 'navigation' url and probably 'redesign' template using django-crispy-form. But the first step is make user directly access Login page when the 'root' url (https://<my_domain>/) is enter in the navigation adress bar. Currently, user access home page of my web app that contain a login button that redirect to https://<my_domain>/registration/login Do I need to override all authentification views (and forms for design) and change url as needed? Or is there an easiest way, maybe using settings.py to make user redirect to login page from root url? project - app - core - settings - base.py - ... - views.py - urls.py - app1 - forms.py - views.py - templates - app1 - registration # <= currently no forms.py nor views.py - templates - registration - login.html - password_change_done.html - ... - static - templates - layout - base.html - home.html core/urls.py urlpatterns = [ path('', views.home, name='home'), # <= 'root' url # path('registration/', include('registration.urls')), # <= registration views override path('registration/', include('django.contrib.auth.urls')), ] core/settings.py LOGIN_URL = 'home' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = … -
How to add both integer field and choices in a single attribute of a model class in django?
I want to add both choices of days and hours in my assigned_time field, along with adding how many days or how many hours. Here is what I tried that doesn't work. Here is my model.py class Timesheet(models.Model): DAYS= 'D' HOURS = 'H' STATUS= [ ('D', 'Days'), ('H', 'Hours') ] employee= models.ForeignKey(Employee, on_delete=models.CASCADE) date= models.DateField(verbose_name='Date') designation=models.ForeignKey(Designation, on_delete=models.CASCADE) projects= models.CharField(max_length=256, verbose_name='Project Name') assigned_time= models.IntegerField(verbose_name='Assigned Hours/days', choices=STATUS, default=DAYS) time_spent=models.IntegerField(verbose_name='Spent Hours/Days', choices=STATUS, default=DAYS) description=models.TextField(max_length=1000, verbose_name='Description') def __str__(self): return f'{self.employee.user.first_name} {self.employee.user.last_name} {self.project}' Check for assigned_time or time_spent field. I want to do the same thing on both as I explained above. Here is my admin.py @admin.register(Timesheet) class TimesheetAdmin(admin.ModelAdmin): list_display=('first_name', 'last_name', 'date', 'assigned_time', 'projects', 'time_spent', 'description', 'designation_name') def first_name(self, obj): return obj.employee.user.first_name def last_name(self, obj): return obj.employee.user.last_name def designation_name(self, obj): return obj.designation.designation_name Here is the image of what I am getting What should I do to add both things in a single field? -
Will upgrading the class of the DB instance speed up my lambda application
I have a Django application that is connected to a PostgreSQL database located on AWS RDS. Right now, because it's still in development we use a small tier (db.t3.small) which has 2vCPUs, 2GiB RAM and 2.085 Mbps. My application is running smooth and fast, except for one model because it has over 6 million rows. It takes about 25 seconds to load even when working on localhost. When I then switch to a local postgreSQL database on my computer with the same data it takes around 3s to load So I'm wondering, if I upgrade to db.t3.medium or even db.t3.large that both double in RAM size from his previous tier. will this make any diffrence in speed for my application -
How to deploy Django project on Heroku
Its been 2 days since i have trying to deploy my django project on heruko everytime it give me some kind of error so is there anyone who know how to deploy django project on heruko My requirement.txt file is asgiref==3.4.1 certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.6 cryptography==3.4.8 defusedxml==0.7.1 Django==3.2.7 django-allauth==0.45.0 django-countries==7.2.1 django-crispy-forms==1.14.0 idna==3.2 oauthlib==3.1.1 Pillow==9.0.0 pycparser==2.20 PyJWT==2.1.0 python3-openid==3.2.0 pytz==2021.1 requests==2.26.0 requests-oauthlib==1.3.0 sqlparse==0.4.2 stripe==2.65.0 urllib3==1.26.7 and currently I am using python version 3.9.5 and I am using sqlite3 database which is default database for everynew python project IF any need anykind of information just ask me in the comments -
Django rest framework group by
I want to group by my data on the basis of ingredient_id so that it does not repeat in response, as you can see am querying on the basis of ingredient_id which is a foreign key so it can be repeated in the database. But I want all the ingredient data to be once and then the supply_chain information around it. model.py class SupplyChainStops(models.Model): ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE) stop_name = models.CharField(max_length=1024, null=True, blank=True) stop_longitude = models.CharField(max_length=500, null=True, blank=True) stop_latitude = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return f'{self.stop_name}' query @api_view(['GET']) def supply_chain_response_detail(request, id): ingredient_detail = SupplyChainStops.objects.filter(ingredient_id=id).all() serializer = SupplyChainStopsSerializer(ingredient_detail, many=True) return Response(serializer.data) Serializer class IngredientSerializer(serializers.ModelSerializer): ingredient_category = IngredientCategorySerializer() supplier = SuppliersSerializer() origin = OriginSerializer() allergies = AllergiesSerializer(many=True) class Meta: model = Ingredients fields = '__all__' class SupplyChainStopsSerializer(serializers.ModelSerializer): ingredient = IngredientSerializer(many=False) class Meta: model = SupplyChainStops fields = '__all__'