Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is the sqlite database (the default django database) good enough?
I am building this ecommerce app with django, and I was thinking if the default database (sqlite) was fine enough? My django app is going to have around 200 different products, and for payments I will use stripe API. I do not expect too much traffic when the app is up, since it's a website only for the country I live in with 6 million inhabitants. So can I settle with the sqlite database? -
How to resolve this "Invalid default value for a django.models field error"?
I am creating a student model which records homework details of a student. It works in a way that student has been given work to do at home with some deadlines of days or hours. When I migrate, I get this error I am getting this error File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1067, "Invalid default value for 'deadline_type'") for my this model class WorkHour(models.Model): DAYS= 'D' HOURS= 'H' STATUS = [ ('D', 'Days'), ('H', 'Hours') ] student= models.ForeignKey(Student, on_delete=models.CASCADE) date= models.DateField(verbose_name='Date') deadline_type= models.CharField(max_length=256,choices=STATUS,default= DAYS, verbose_name= "Days/Hours") deadline_time = models.IntegerField(verbose_name='Deadline',default=1) either I add default value in deadline_type, It gives me the above error. I have done the same thing in my other models too. I din;t know what I am doing wrong here. -
Print users' data inside a template in Django
I'm new to Django and I'm trying to print users' information such as email, first name, username in a template that should work as "My Profile Page". For some reason, the only thing I'm able to print is the username of the logged-in user with {{request.user.username}} Users are registered using the UserCreationForm If I try to print the email with {{request.user.email}} or {{user.email}} nothing is shown. My settings.py is the default one TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Hey everyone I have problem in sorting queryset in Django
So, I am learning Django and trying to make a site similar to AirBNB. I have models called lisitngs that has latitude and longitude stored in CharField. My model is as follows: class Listing(models.Model): class BathRoomType(models.TextChoices): ATTACHED = 'Attached Bathroom' COMMON = 'Shared Bathroom' class RoomVentType(models.TextChoices): AC = 'Air Conditioner' NO_AC = 'No Air Conditioner' class LisitngType(models.TextChoices): ROOM = 'Room' APARTEMENT = 'Apartement' HOUSE = 'Full House' user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) city = models.ForeignKey(RoomLocation, on_delete=models.CASCADE) exact_address = models.CharField(max_length=255) lat = models.CharField(max_length=300, blank=False, null=False, default="0") lng = models.CharField(max_length=300, blank=False, null=False, default="0") description = models.TextField() price = models.IntegerField() listing_type = models.CharField(max_length=20, choices=LisitngType.choices, default=LisitngType.ROOM) kitchen_available = models.BooleanField(default=False) kitchen_description = models.TextField(null=True, blank=True) bedrooms = models.IntegerField() max_acomodation = models.IntegerField() bathroom_type = models.CharField(max_length=20, choices=BathRoomType.choices, default=BathRoomType.ATTACHED) no_bathrooms = models.IntegerField() room_type = models.CharField(max_length=30, choices=RoomVentType.choices, default=RoomVentType.AC) main_photo = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_1 = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_2 = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_3 = models.ImageField(upload_to='room_images', default='default_room.jpg') is_published = models.BooleanField(default=False) date_created = models.DateTimeField(default=timezone.now, editable=False) slug = AutoSlugField(populate_from=['title', 'listing_type', 'bathroom_type', 'room_type']) rating = models.IntegerField(default=5) approved = models.BooleanField(default=False) total_bookings = models.IntegerField(default=0) def __str__(self): return self.title In my homepage what I want to do is show the listings which are nearby me. For that I have a function named as near_places. This near_place function … -
django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported
I am trying to run our django-python project. When i am running this command python manage.py makemigrations it is showing error django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Django==4.0.1, djongo==1.3.6, pymongo==3.12.1, djangorestframework==3.11.1 DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'xxxxxxDB', 'HOST': 'mongodb+srv://dbadmin:xxxxxadmin@cluster0.mn4rg.mongodb.net/xxxxxxDB retryWrites=true&w=majority', 'USER': 'dbadmin', 'PASSWORD': 'xxxxxxxxxx', "authMechanism": "SCRAM-SHA-1", } } -
DRF - enable single object lookup without filter
Using default DRF Viewsets with the following models and model serializers: class Company(Model): active = BooleanField() class Person(Model): company = ForeignKeyField(to=Company) My filter for Companies: class CompanyFilter(filters.FilterSet): ... @property def qs(self): parent = super().qs if 'active' not in self.data: return parent.filter(active=True) return parent I would like to: hide inactive companies by default have a proper navigation from all persons, even to companies that are deactivated According to DRF docs: Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. If I introduce the filter mentioned, a user navigating from person to his company will get a 404 if this company is inactive. He would need to set a GET parameter on a single object lookup which is impossible to know. -
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.