Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to catch API call errors in pyhton/Django?
I have a Django app and a workflow like this in my views.py: my front end makes a call to my back end which uses the params received from front end to make an API call to an external API. I map the response from the external API to my serializer and check if the serializer is valid before saving the response to database. What I need help with is how to properly check for the responses from the external API and catch any errors getting from there? Can I just use try/except? At the moment I don't know about their exact responses but that is something I can clarify later. This is my class from views.py: class Example(generics.ListCreateAPIView): permission_classes = (AllowAny,) serializer_class = ExampleSerializer def post(self, request, format=None): pin = request.data['pin'] id = str(uuid.uuid4()) post_obj = {'pin': pin, 'id': id} data = requests.post(url, data=json.dumps(post_obj)) json_result = data.json() serializer = ExampleSerializer(data=json_result['data']) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django file_resubmit doesn't work in a templates view
So I have the problem where for a form that has an ImageField, (rendered using forms.py in Django) whenever the validation error comes up, maybe due to miss matching passwords etc. the ImageField get cleared. After some googling, I found a module called file_resubmit . This seems to have worked well for many people however for some reason it doesn't work for me... Docs of file_resubmit I did as their docs said but doesn't seem to work for me. I'm my settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', . . 'file_resubmit', ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, "file_resubmit": { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', "LOCATION": '/tmp/file_resubmit' } } In my forms.py... from file_resubmit.admin import AdminResubmitImageWidget class DriverRegisterForm(forms.ModelForm): mobile = forms.CharField(min_length=10) date_of_birth = forms.DateField(widget=forms.TextInput(attrs={'autocomplete': 'off'}), help_text="You need to be a minimum age of 18 to register with us") gender = forms.ChoiceField(choices=[("M","Male"), ("F", "Female")]) district = forms.ChoiceField(choices=CITY) nic_number = forms.CharField(label="NIC number", min_length=10) license = forms.ImageField(label="License picture") your_picture = forms.ImageField(help_text="A picture of yourself so that we know who you are") class Meta: model = ProfileDriver fields = ('mobile', 'gender', 'district', 'nic_number', 'license', 'date_of_birth', 'your_picture') widgets = { "license":AdminResubmitImageWidget, "your_picture":AdminResubmitImageWidget, } And just in case my models.py.. class ProfileDriver (models.Model): … -
How to filter by a list in Django REST Framework?
Suppose I have a model called X, X contains a field called Ys, a many-to-many field for a class Y. If I have a list of multiple instances of the model Y, how to filter for Xs that have the field Ys that is a superset of my list? Example: I have 3 X objects here: x1.Ys = [y1, y3, y4] x2.Ys = [y1, y2, y3] x3.Ys = [y1, y2] items_list: [y1, y2] I want to write X.objects.filter(xxx=items_list) and get x2, and x3 but not x1. What should I write in place of xxx? -
How to make foreingkey object in django forms (like "+" in django admin)
im using django forms and i want to add like in django admin "+" for adding in form filed a foreign key object. I want the same as in django admin, you pushing +, then opens foreign key object form, filling foreign object fields, saving it, and object appears in main form field. How can i do this? (using django crispy forms) -
How to implement a Central Authentication Server in Django?
I am trying to implement a Authentication Server using Django which will be used only for user authentication. We have multiple services hosted on different subdomains like one.service.com, two.service.com, three.service.com etc. And we don't want our users to memorize/use different login credentials for each service. We want a system where user can authenticate themselves through the auth server and can access all the services of the subdomains. Just think about Google or Microsoft, we just need one login credential and then we can access all of their services. How can I implement this type of system for our services using Django ?? Note: We are primarily using JWTAuthentication for our servers. -
Django application deployed on AWS is quite slow
I have used AWS Elastic Beanstalk to deploy a Django project and I’m using a RDS PostgreSQL (size db.t2.micro) database from AWS. What I have noticed is that while testing the app locally (localhost) with the default sqlite3 the app is much faster than the deployed version that uses the PostgreSQL database from AWS/RDS. This may be something normal but I’m quite new working with AWS and RDS and I would like to know why this is happening and what can I do to make the application work as fast as it works locally. Thanks, -
How to query for an object that has specific number of foreignKey relations and has specific values in those foreinKey values in Django?
I am building a Django GraphQL API to use for a chat app. I have the following 2 models, one for Chat and one for chat members, which is tied in as a foreingKey:- class Chat(models.Model): name = models.CharField(max_length=100, blank=True, null=True) members = models.ManyToManyField(User, related_name="privateChats", through="ChatMember", through_fields=('chat', 'member'), blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class ChatMember(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.chat I have a certain method that is supposed to take in 2 user Ids and first it looks to check if an existing chat exists between these 2 members. If it exists, it returns that chat. If not then it creates a new chat for these 2 members and returns the newly created chat. The tricky part is where it tries to search if an existing chat exists. Because I'm using this same chat model for group chats, it is possible that it could return a group that also has these 2 members. So the condition to check if there is a one on one chat between these 2 members, it is to first check if the chat has only 2 members in it … -
nginx how can properly setting public domain names for Django apps with gunicorn
I have set up nginx for Djnago apps with gunicorn on ubuntu 20.04 by following this tutorial, and as result of this, the site works locally with local domain name. But after buying public domain name, I can not manage how to set up this public domain name with my nginx server. And I take this error on browsers: -
How to search in Django [closed]
I have a table in db which look like this I need to search by Rule No and store the search string which is Epic="DevOps" AND Desc = "desc1" variable in a variable. note: i gave example for Rule no 1. for all the rule i have to search and store that in a variable Anyone guide me how to do that in django? Here's my model for Rule table: class assignmentRule(models.Model): Developer = models.ForeignKey(developer, on_delete=models.CASCADE) Jira_Column = models.CharField(max_length=100, blank=True) RelationalOperators= models.CharField(max_length=100) Jira_Value = models.CharField(max_length=500) LogicalOperator = models.CharField(max_length=30) Rule_No = models.CharField(max_length=30) here my developer table: class developer(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) def __str__(self): return self.Developer_Name -
ImageField default upload_to directory changes
when I upload an image, it doesn't get saved to default upload_to directory (get_news_image). Instead it created a new directory (new) that has the name of the Model (News) and each image I add uploads there. I'm using class based views, are they automatically making an upload folder for my images?? On the left side in the bottom you can see my media folder: -
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.