Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I pass a user model object through Strawberry Django GraphQL types and schema to save an object
I am trying to create a mutation (utilising Strawberry Django GraphQL) to save a record in a database that handles the User Model to fill the creator field. Here is what I have: models.py: class Record(models.Model): name = models.CharField(max_length=20) description = models.CharField(max_length=200) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) types.py: ... from .models import Record as RecordModel @strawberry.django.type(AuthUserModel) class User: id: auto name: auto username: auto email: auto @strawberry.django.type(RecordModel) class Record: id: auto name: auto description: auto @strawberry.django.field def creator(self, info: Info) -> 'User': return UserModel.objects.filter(id=info.context.request.user.id) @strawberry.django.input(RecordModel, partial=True) class RecordInput: id: auto name: auto description: auto creator: auto shcema.py: @strawberry.type class Mutation: createRecord: Record = mutations.create(RecordInput) I can track that everything is passed to the Django InitRecord model save() function, except the 'creator' field. I am not sure how I can pass it to save the records instance. It threw me an error: "Error (timestamp) schema (number) NOT NULL constraint failed: initrecord.creator_id". -
Reducing audio , video size on upload Django
I got a test server where I have features like uploading audio and video on a post . The feature is working perfectly but using a lot of space as some videos has more than 80MB while my system has only 1Gb of storage. How can I reduce my audio video size on upload maintaining no upload restriction. I am using Django and drf on backend . I looked into ffmpeg & pydub but couldnt find anything to reduce the audio bitrate or video quality. Is there anything else I should look into ? or ffmpeg will work (if ffmpeg works, please give me some example links so that I can implement before integrating to my test server) Thanks Any suggestion regarding this will be helpful -
2checkout IPN example validation response in Python
2checkout provides example code for IPN response validation for wide verity of languages except for Python, if someone is looking for Python ( Specifically Django ) example code, Iv'e provided the answer below, cheers! -
Can't send multiple signals for multiple user
I'm just implementing signals, and it's working for one user only. Whenever I try to add user more than one it doesn't sending them signals. If I add one user only it successfully works and sends them a signal. I just could not figure out how? besides I'm using notification - Hq library to sending them notifications. The below code is working for one user only. Models.py def post_save_receiver(sender, instance, created, *args,**kwargs): if created and not instance.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, instance.content) if m: try: recipient = User.objects.get(username=m.group('username')) except (User.DoesNotExist, User.MultipleObjectsReturned): pass else: notify.send(instance.author, recipient=recipient, actor=instance.author, verb='mention you in a post', target=instance, nf_type='tagged_by_one_user') post_save.connect(post_save_receiver, sender=post) If someone adds @username in a post, they get a signal that someone mentioning him but it's working only for one user. I want to implement that for multiple users. -
Object POST form HTML to Python - posted as string
JS func <script> function tbpost(){ var TableData = new Array(); $('#bill tr').each(function(row, tr){ TableData[row]={ "itemname1" : $(tr).find('td:eq(0)').val() , "qty1" :$(tr).find('td:eq(1)').val() , "price1" : $(tr).find('td:eq(2)').val() , "amt1" : $(tr).find('td:eq(3)').val() } }); document.getElementById("od").value=TableData; } </script> Button to call the function <button type="button" class="btn btn-fill btn-primary" onclick="tbpost()" >Save</button> trying to save the output of the func here <input id="od" name="od" class="form-control total" readonly> django-python views.py ob=request.POST['od'] this is the output which i get in python, which is full of string [object Object],[object Object],[object Object],[object Object] Eg: ob[0]='[' ob[1]='o' i need output like ob.itemname1=[ 'xxx', 'yyy'] ob.qty1=[ 'xxx', 'yyy'] etc -
how to register a model item as a view in django
I have a model named Product class Product(models.Model): date = models.DateField(blank=True, null=False, default=timezone.now) name = models.CharField(max_length=40, blank=False, null=True, default="") item_in_stock = models.IntegerField(blank=False, null=True, default=0) price = models.FloatField(blank=False, null=True, default=0.0) supplier = models.ForeignKey(Supplier, null=True, on_delete=models.CASCADE, blank=False) def __str__(self): return self.name and in my django admin panel i want to add a model item from my product model into the side panel like here in ADMININFO but instead of All Products i want to have a product item. for example if i have a product named Shoes i want it to show on the side bar under ADMININFO and when you click it it shows you it's values? Thanks in advance.❤️ -
Need to display binary to Image in Django
I need to display Binary code from my Mysql Db as image in Django. views.py def editclient(request) clientid= request.POST['clientid'] brachcode= request.POST['brachcode'] if request.post and 'button2' in request.POST: client_images_view(request,brachcode,clientid) else: #somecode When client_images_view is called in the above view it should display the image from the Mysql(which is in binary code stored as blob) def client_images_view(request,brachcode,clientid): context = { 'username': request.session['user_name'], 'userrole': request.session['role'], 'dt': request.session['dt'], 'image':None } client_details = Client.objects.get(brachcode=brachcode, clientid=clientid) photo = client_details.photo import base64 image = base64.b64encode(photo.getvalue()) image = image.decode('utf8') context['image'] = image return render(request.decode('utf-8'), 'client_images.html', context) When I run this code it shows this error AttributeError at /managerial/client_edit 'bytes' object has no attribute 'getvalue' -
Django Foreign key relationships should be User to Model or Model to user?
I am new to django and trying to make an ecommerce website for practice. There is a Cart model which currently has a ForeignKey to the User. Which way should be more efficient? Should I create a UserProfile model which would have a Cart as the ForeignKey or should I keep it like this? I am thinking the former should be faster as when I will display the cart to the user, it will have to search and filter through all carts if I keep it as is. But the tutorials I am watching are setting up their models in which Cart has a ForeignKey to the User. Kindly guide me here. -
adding a navigation bar item in django admin panel
I want to add a custom navigation item to django admin panel without creating a model like the one here how can i do that? -
Django : How to select object dynamically according to the user's input in content type field?
In custom content type model , the value of content type and object id are to be given. content type is a drop down type ,listing all models. but object id has to be entered manually. I want to achieve a method that whenever a user select the content type, a list should be shown, showing all the object corresponding to that content type.So that user can select an object from that list and object id will be dynamically allocated. How it can be done in Django admin form? -
How to insert data into two model from one viewset action in django rest framework
I have two models Purchase and Transaction. I need to insert data into Transaction model whenever data insert into Purchase model. A purchase must have a corresponding transaction. Purchase Model is- class Purchase(models.Model): date = models.DateField(blank=True) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=True, blank=True ) quantity = models.FloatField() amount = models.FloatField() from_head = models.ForeignKey(Head, on_delete=models.CASCADE, null=True, blank=True) from_subhead = models.ForeignKey(SubHead,on_delete=models.CASCADE,null=True,blank=True,) to_head = models.ForeignKey(Head, related_name="purchase_to_head", on_delete=models.CASCADE, null=True, blank=True,) to_subhead = models.ForeignKey(SubHead,related_name="purchase_to_subhead",on_delete=models.CASCADE,null=True,blank=True,) Transaction Model is- class Transaction(models.Model): class TypeList(models.TextChoices): IN = "IN" OUT = "OUT" class PaymentType(models.TextChoices): CASH = "CASH" DUE = "DUE" date = models.DateField(blank=True) purchase = models.ForeignKey( Purchase, on_delete=models.CASCADE, null=True, blank=True ) sale = models.ForeignKey(Sale, on_delete=models.CASCADE, null=True, blank=True) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=True, blank=True ) type = models.CharField(max_length=10, choices=TypeList.choices) payment_type = models.CharField(max_length=10, choices=PaymentType.choices) amount = models.FloatField() from_head = models.ForeignKey(Head, on_delete=models.CASCADE, null=True, blank=True) from_subhead = models.ForeignKey(SubHead, on_delete=models.CASCADE, null=True, blank=True,) to_head = models.ForeignKey(Head, related_name="trans_to_head", on_delete=models.CASCADE, null=True, blank=True,) to_subhead = models.ForeignKey(SubHead, related_name="trans_to_subhead", on_delete=models.CASCADE, null=True,blank=True,) Purchase and Transaction Serializer are- class PurchaseSerializer(serializers.ModelSerializer): class Meta: model = Purchase fields = "__all__" class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = "__all__" Purchase and Transaction Viewsets are- class PurchaseView(viewsets.ModelViewSet): serializer_class = PurchaseSerializer queryset = Purchase.objects.all() class TransactionView(viewsets.ModelViewSet): serializer_class = TransactionSerializer queryset = Transaction.objects.all() How can I … -
Can't login in admin panel with superuser or with normal users with custom User Model
I created a AbstractUser model in Django which adds some custom fields, but now whenever I create a user (whether by calling User.create_user() or with python manage.py createsuperuser), the user is created fine with a hashed password, but I cannot use the password to login. When I try to login on the admin console, I get "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." I cannot for the life of me figure out what is going wrong since in my database, the correct username + a hashed password appear when I create a user. This is my user Model from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, password, avg_recipe_rating=None, num_ratings_received=0, num_recipes_created=0): user = self.model(username=username) user.set_password(password) user.num_ratings_received=num_ratings_received user.num_recipes_created=num_recipes_created user.avg_recipe_rating=avg_recipe_rating user.save(using=self._db) return user def create_user(self,username, password, avg_recipe_rating=None, num_ratings_received=0, num_recipes_created=0): return self._create_user(username, password, avg_recipe_rating, num_ratings_received, num_recipes_created) def create_superuser(self,username, password, avg_recipe_rating=None, num_ratings_received=0, num_recipes_created=0): return self._create_user(username, password, avg_recipe_rating, num_ratings_received, num_recipes_created) class User(AbstractUser): user_id = models.AutoField(primary_key=True) avg_recipe_rating = models.FloatField(blank=True, null=True) num_ratings_received = models.IntegerField(null=False) num_recipes_created = models.IntegerField() last_login = None groups = None user_permissions = None first_name = None last_name = None email = None … -
nginx 403 Forbidden when render big file
I build a wee website where i upload some jupyter notebook as html files in order to show some works example. First notebook i uploaded is less the 1MB size and uploaded and rendered fine, then i tried to upload a bigger file, 4mb, and got a 413 error size to big, after checking online i added to my nginx.conf the line client_max_body_size 10M; and now it upload correctly but still got a nginx 413 error permission denied when render the file. If i upload a less then 1MB file everything works fine, so my guess is there is still something missing in the conf file in order to enable render of bigger file my nginx.conf is: events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; … -
How can we add extra fields to the predefined user model in django?
I want to know, that can we add extra fields to the predefined user model in Django or not? If Yes, then how can we do that can anyone here can explain me. Like I want to add the following fields Address zip code phone Number And secondly, when I register a user it takes email, username, and password from me but when I login it takes the username and password, what I want is that it uses email and password to login. -
How to read coordinate from the DB and map a pointer on the map using django
As a newbie with python, I am thinking of doing a project, where I have a table of e.g shops, with their names, longitude, latitude, and shop manager. I want to design a django project where the coordinates (longitude, latitude) will be used to place a pointer on the map to indicate the location on the map, and if hovered, it will show the shop details. I can go as far as if clicked on, the will display the shop page with details, etc. -
Django restframework search function doesn't return the desired output?
I want to use Django search feature while trying to implement it. The implemented code doesn't work View.py file class SearchView(generics.ListAPIView): permission_classes = [IsAuthenticated] queryset = BlogDetails.objects.all() search_fields = ["blog_title"] filter_backend = [filters.SearchFilter] serializer_class = SearchSerializer Serializer.py class SearchSerializer(serializers.ModelSerializer): class Meta: model = BlogDetails fields = ("blog_title","blog_author") So I made a request like this localhost:8000/search/search-blog/?search=jane But it displays all the blogs that are in database and not the result which has jane in its title and I have added django-filters in INSTALLED_APPS But still it doesn't work! -
django csrf authentication error when trying to connect react
I am trying to build the backend with django and frontend with react. I stumbled accross a 403 error when I try to login an existing user. Everything compiles but login always results in fail. When I inspect the network tab I see there is a 403 error. when I access correct auth info In the error page it says that I should add the csrf template tag before my input tags but I can't add them because react doesn't recognize it. The error is gone if I don't use react but I have to use it. What are my options if I want to implement this in react? App.js: import { BrowserRouter as Router, Switch } from "react-router-dom" import Auth, { useAuthActions } from "use-eazy-auth" import { AuthRoute, GuestRoute } from "use-eazy-auth/routes" import { ConfigureRj } from "react-rocketjump" import { map } from "rxjs/operators" import { ajax } from "rxjs/ajax" import Login from "./pages/Login" import AddressBook from "./pages/AddressBook" const login = (credentials = {}) => ajax({ url: "/core/token/", method: "POST", headers: { "Content-Type": "application/json", }, body: credentials, }).pipe( map(({ response }) => ({ accessToken: response.access, refreshToken: response.refresh, })) ) const me = token => ajax.getJSON("/core/me/", { Authorization: `Bearer ${token}`, … -
Is there a way to add django models dynamically?
I am creating models in Django using an array of strings. E.g. let there be an array of strings named arr arr = ['one','two','three','four'] Then I have to create four models in django named FooOne, FooTwo, FooThree, FooFour. All of them have the same fields. Is there any way where I wont have to create these models manually, i.e., I just update the array of strings and run a script and the models will be created for me automatically ? I am using MySQL as the database. -
Django Rest Framework and the Frontend
I want to use Django Rest Framework as an API and am looking for a way to "couple" the frontend / HTML/CSS/JS to it. To put it in perspective, I am used to the way Django "usually" does it, by naming HTML templates and 'rendering' them when going to a particular URL. Now, with DRF, it appears that this functionality has fallen away and everywhere I look it's just "react.js or vue.js" as the answers to consume the API. What are my options for the front end? Can I not just do it all within the 'usual' Django framework, simply, as it was done before. And why do no resources talk about this? Thanks, let me know if you require further info. -
i am gettin an error "[Errno 5] Input/output error" while running an api on django
Django API Code: def post(self,request)-> JsonResponse: try: self.email = request.data['email'] self.mobile = request.data['mobile'] self.password = request.data['password'] except Exception as e: return JsonResponse(create_failure('400',f"invalid payload {e}","fail")) try: res = {} jwt_token = '' if self.email: password = Customer.objects.get(email=self.email).password username = Customer.objects.get(email=self.email).username print(password) if check_password(self.password,password) : jwt_token = make_jwt_token({'username':username}) else: return JsonResponse(create_failure('500',f"Invalid password","fail")) elif self.mobile: password = Customer.objects.get(mobile=self.mobile).password username = Customer.objects.get(mobile=self.mobile).username if check_password( password,self.password) : jwt_token = make_jwt_token({'username':username}) else: return JsonResponse(create_failure('500',f"Invalid password","fail")) res['token'] = jwt_token except Exception as e: return JsonResponse(create_failure('400',f"error in verifying the password {e}","fail")) return JsonResponse(create_success('User Verified',res)) Error while running it on the postman { "StatusCode": "400", "Message": "error in verifying the password [Errno 5] Input/output error", "ReplyCode": "fail", "Data": [] } Above code is working fine on the local machine, but it creates this error when I deploy it to the server. I am using cpanel for the hosting which uses CentOS -
How to replace the in-built Django admin side pages with your own template pages?
enter image description here Thanks -
ASCII codec can't encode character and can only concat str
I'm trying to send a request in Django: res = self.client.get("/test/", {"var":"test"+u"\u200B".encode('utf-8')}) However, I keep getting the error message: can only concatenate str (not "bytes") to str When I remove .encode('utf-8') I get: UnicodeEncodeError: 'ascii' codec can't encode character '\u200b' in position 3: ordinal not in range(128) Any ideas? -
Django values function rename key of dict
In my databases design id | key | value 1 | ABC | 123 and what i trying to do data.objects.filter(id__in=list).values('key', 'value') and it return [{'key': 'ABC', 'value': '123'}, ... ] but instead of that, i want to do [{'ABC': '123', ... ] Noted: The result list will be 800k rows, because of the performance issues, i try to avoid using loop and want to use django feature to make it like this. -
Infinite scroll not re-rendering with cache after removing updateQuery
Frameworks: Apollo / GraphQL / Django Scenario: I am using useQuery from apollo/client to fetch data. I have an infinite scroll created to listen for the scroll after which fetchMore is called. I can update the cache properly with updateQuery, but this is going to be deprecated as I get this error: react_devtools_backend.js:2560 The updateQuery callback for fetchMore is deprecated, and will be removed in the next major version of Apollo Client. Here is the working code to fetch and update the cache on each scroll: const handleGetMore = async () => { console.log("fetch"); if (!pending) { try { pending = true; await fetchMore({ variables: { isGm: true, offset: data?.getUsers?.length, limit: 12, }, updateQuery: (prev, { fetchMoreResult }) => { if (!fetchMoreResult) return prev; return Object.assign({}, prev, { getUsers: [...prev.getUsers, ...fetchMoreResult.getUsers], }); }, }); pending = false; } catch (error) { console.log("handleGetMore Error:", error); } } }; So, I updated my cache, as that seems to be the method going forward, to look like this: import { InMemoryCache } from "@apollo/client"; import { offsetLimitPagination } from "@apollo/client/utilities"; export const cache = new InMemoryCache({ typePolicies: { getUsers: { fields: { getUsers: offsetLimitPagination(), }, }, }, }); Problem: The UI does not … -
Can django authentication work with horizontal scaling?
I heard that session based authentication are not horizontally scalable. You somehow need a central system which saves the session. Is this same with django's default authentication system? There are other authentication methods too, like JWT (Which can easily scale horizontally). The problem with JWT is that they have more security risk than a standard authentication system. Can django's default authentication work without any problem in a multi server setup which has a load balancer distributing the load?