Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to automate the process of django templates translation?
I would like to translate all my Django templates, Which means I need to go through every word or sentence in my templates and add the code _() to it. For ex This: <h1>hello</h1> Will be this: <h1>_("hello")</h1> But I would like to do it automatically since I have many many sentences, It doesn't matter if it's software or an online tool or a text editor that can automate the process. -
Error 404 NOT FOUND occurs when trying to GET from django
I am getting the 404 error Failed to load resource: the server responded with a status of 404 (Not Found) 127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D:1 my code for product/models.py: from io import BytesIO from PIL import Image from django.core.files import File from django.db import models class Category (models.Model): name = models.CharField(max_length=255) slug = models.SlugField(null=True) class Meta: ordering = ('name',) def __str__(self) : return self.name def get_absolute_url(self): return f'/{self.slug}/' class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField(null=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self) : return self.name def get_absolute_url(self): return f'/{self.category.slug}/{self.slug}/' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def get_thumbnail(self): if self.thumbnail: return 'http://127.0.0.1:8000' + self.thumbnail.url else: if self.image: self.thumbnail = self.make_thumbnail(self.image) self.save() return 'http://127.0.0.1:8000' + self.thumbnail.url else: return '' def make_thumbnail(self, image, size=(300, 200)): img = Image.open(image) img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail the product page,product.vue code: <template> <div class="page-product"> <div class="column is-multiline"> <div class="column is-9"> <figure class="image mb-6"> <img v-bind:src="product.get_image"> </figure> <h1 class="title">{{ product.name }}</h1> <p>{{ product.description }}</p> </div> <div class="column is-3"> <h2 class="subtitle">Information</h2> <p><strong>Price: </strong>Ksh{{ … -
How to Populate ImageFIeld Value when Adding Model Instance in Django Admin with Query Param?
I have a model like this: class MyModel(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='images') When going to http://127.0.0.1:8000/admin/myapp/mymodel/add, I can add a new instance of MyModel. I know that there is a way to populate the name field by adding the following query param: ?name=myname, but when I try to do ?image=images%2Fmyimage.jpg, it doesn't work. I also tried ?image__url=images%2Fmyimage.jpg but it didn't work either. Does anyone know how to populate an ImageField value with a query paramater when adding a new model instance in Django admin? -
Python Package gets removed when azure app restarts
I have uploaded Django app on azure server web app using Zip Deploy. After deploying it gives error that "sndlibrary not found" so i need to go to ssh and install it manually by using command "apt update && apt-get -y install libsndfile1-dev".So The problem is that whenever the app gets restarted it again shows the same error and i again need to install the package from ssh.The package does not persist on restart.So is there any way to persist the package on app restart? I have also tried using startup.sh script on the wwwroot path but when run it shows error that "could not locate the package". -
Djnago send mail not working, also not showing any error
Settings.py DEFAULT_FROM_EMAIL = 'testing.email2908@gmail.com' SERVER_EMAIL = 'testing.email2908@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'testing.email2908@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAILL_USE_TLS = True views.py print('Helloo') send_mail( 'Testing', 'Hi', 'testing.email2908@gmail.com', ['xyz@gmail.com'], #my personal gmail id fail_silently=False, ) print('Hiiii') When i run this code, only Helloo is getting printed, I've imported send_mail as well,tried using smtplib as well but that was giving smpt auth extension error so i'm trying send_mail method but it also doesn't seem to work, don't know what is the exact issue. -
Return decimal fields from list
I have a generator which yields to datatype on is decimal and other is string i need the method to just return the decimal def my_generator(): yield amount, name def get_amount(obj): p = list() gen = obj.my_generator() for i in gen: p.append(i) return p get_amount() now it is returning [(Decimal('1950.00'), '06/16/2020'), (Decimal('4500.00'), '06/16/2020')] I want the list to be returned as formatted how can i do that '${:0,.2f}'.format(Decimal('1950.00') which is in my list) so the end result would be like $1,950.00 if the the return has two yields it should return like. $1,950.00, $4,500.00 -
Remove '*' from required fields
I have a form in django in which there are some demographics. I want those fields to be required but if I set them as such from the model I get the * special character after every field label in the form. How do i remove that character but still have those fields as required? My model fields: location = models.CharField(max_length=254, choices=COUNTRIES, null=True) homeowner = models.CharField(max_length=254, choices=HOME_STATUS, null=True, blank=True) form: class UserDemographicsForm(forms.ModelForm): class Meta: model = Demographics fields = ['age', 'sex', 'yearly_income', 'employment', 'location', 'homeowner', 'education', 'home_adults', 'home_children'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_tag = False and the result i try to omit : -
How to restrict users to only type English in Django forms?
i have a model form with field (forms.textinput) and i want users just can type english in this field and if they want type with another language get a error thank you -
Why is my linode domain not working in my browser?
I just bought a domain to fit with my new web application which is hosted on a linode. I proceeded to the configuration on the domain manage panel by setting the server adresses to "ns1.linode.com", "ns2.linode.com",.... and i correctly added the domain on linode with new AAAA/A. I know that this changes can take several hours to be applied, but now, when I enter the domain in my browser, it displays the message " does not allow connection". I wanted to know if this result was a normal part of the step that should happen during the configuration and i just have to wait a few more hours, or if i did something wrong somewhere. (i precise that the linode is running correctly, when i enter the IP adress on the 8000 port it works, the problem is just with the domain). Could the problem happen because on my domain setting pannel, i only have 4 fields for the adresses so i can not enter de fivth "ns5.linode.com" ? Thanks a lot for your answer. -
How to make a (Dapp) with Django?
How to integrate Django with blockchain and build a decentralized application? Are there any packages for this? Is there a tutorial about this? -
How to use exclude filter in django classic view for blog post page?
I'm writing a code for django to list posts in a ListView and DetailView: converting from functional to class view. I can get all the posts to show up, but I want only published posts to show on the list. I know I can use published = Post.objects.exclude(published_date__exact=None) posts = published.order_by('-published_date') but how do I get only the posts variable to render in the template, instead of all Post objects in post_list (in list.html template)? views.py: from blogging.models import Post from django.views.generic.list import ListView from django.views.generic.detail import DetailView class PostListView(ListView): model = Post template_name = 'blogging/list.html' published = Post.objects.exclude(published_date__exact=None) posts = published.order_by('-published_date') class PostDetailView(DetailView): model = Post template_name = 'blogging/detail.html' urls.py from django.urls import path from blogging.views import PostListView, PostDetailView urlpatterns = [ path('', PostListView.as_view(), name="blog_index"), path('posts/<int:pk>/', PostDetailView.as_view(), name="blog_detail"), ] list.html: {% extends "base.html" %}{% block content %} <h1>Recent Posts</h1> {% comment %} here is where the query happens {% endcomment %} {% for post in post_list %} <div class="post"> <h2><a href="{% url 'blog_detail' post.pk %}">{{ post }}</a></h2> <p class="byline"> Posted by {{ post.author.username }} &mdash; {{ post.published_date }} </p> <div class="post-body"> {{ post.text }} </div> <ul class="categories"> {% for category in post.categories.all %} <li>{{ category }}</li> {% endfor %} … -
How to communicate between the virtual box and the system?
I installed Docker on Virtual Box because my computer is 32-bit and Docker only ran on 64-bit systems. Now, Docker runs in a virtual box and my Django project is on system. In VScode, when I enter commands related to Docker, it naturally does not recognize it and gives an error. Specifically, how can I use Docker on my editor and windows terminal? -
Update operation in a model removes all the users stored in a many to many field in that model - Django
In my app a student can send a teacher a follow request that gets accepted by the teacher and the student gets added to the teacher's follower list. The way I am storing the students as a follower for the teacher is by a many to many relationship model. Below is the code: home_tuition_students = models.ManyToManyField(CustomUser, blank=True, related_name='home_tuition_students') general_tuition_students = models.ManyToManyField(CustomUser, blank=True, related_name='general_tuition_students') The above fields are inside a model that is actually the teacher's profile model where other information about the teachers are stored such as name, phone number, etc. Now I am facing a weird problem, whenever a teacher makes an update operation, e.g. change his phone no or any other detail, all the students stored in the many to many field get removed after updation. The update api looks like below: api_view(['PUT']) @permission_classes([IsAuthenticated]) @parser_classes([MultiPartParser, FormParser]) def edit_teacher_detail(request): data = request.data if data is not None: queryset = TeacherDetail.objects.get(user = request.user) serializer = TeacherDetailSerializer(instance=queryset, data = data) try: if serializer.is_valid(): serializer.save() return Response({'message':"details edited"} ,status=status.HTTP_200_OK) else: print(serializer._errors) return Response({'message': serializer._errors}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: print(e) return Response({"message": str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response({'message':'no query recieved'}, status=status.HTTP_400_BAD_REQUEST) I do not know how and why is it happening. Please suggest me … -
FCM: Django firebase-admin-python/fcm-django showing API connection timeout after around 5 minutes without throwing any other error
Hey guys I am having an issue with FCM and django + celery. I have my application running on AWS. Everything was working fine until last week, but suddenly I am getting a API timeout error after around 5 minutes of waiting for each api call and no notifications are being pushed by fcm-django or firebase-admin-python. (I tried with both packages). I tried changing the serviceAccountKey.json credentials, and still it's not working. This is the traceback I get, if I interrupt the function after a minute or so. ^CTraceback (most recent call last): File "<console>", line 1, in <module> File "/home/ubuntu/env/lib/python3.8/site-packages/celery/local.py", line 188, in __call__ return self._get_current_object()(*a, **kw) File "/home/ubuntu/env/lib/python3.8/site-packages/celery/app/task.py", line 392, in __call__ return self.run(*args, **kwargs) File "/home/ubuntu/notifications/tasks.py", line 100, in send_notifications FCMDevice.objects.send_message(Message(notification= File "/home/ubuntu/env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/env/lib/python3.8/site-packages/fcm_django/models.py", line 170, in send_message messaging.send_all( File "/home/ubuntu/env/lib/python3.8/site-packages/firebase_admin/messaging.py", line 136, in send_all return _get_messaging_service(app).send_all(messages, dry_run) File "/home/ubuntu/env/lib/python3.8/site-packages/firebase_admin/messaging.py", line 391, in send_all batch.execute() File "/home/ubuntu/env/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 131, in positional_wrapper return wrapped(*args, **kwargs) File "/home/ubuntu/env/lib/python3.8/site-packages/googleapiclient/http.py", line 1563, in execute _auth.refresh_credentials(creds) File "/home/ubuntu/env/lib/python3.8/site-packages/googleapiclient/_auth.py", line 130, in refresh_credentials return credentials.refresh(request) File "/home/ubuntu/env/lib/python3.8/site-packages/google/oauth2/service_account.py", line 410, in refresh access_token, expiry, _ = _client.jwt_grant( File "/home/ubuntu/env/lib/python3.8/site-packages/google/oauth2/_client.py", line 193, in jwt_grant response_data = … -
How to sanitize Django Rest Framework inputs
How to sanitize the charfield in Django Rest Framework Using Serializer Or Django models itself. No idea how to secure This value can be makes my app vulnerable.... Like XSS <script>alert('Hacked')</script> Check the serializer code class Meta: model = MyDB fields = ['id','name','price','isAvailable','isVeg','hotelID'] read_only_fields = ['id'] I Have seen Bleach. But it feels like not dynamic, i.e cant be applied to all input field at same time. Is any option that can be used dynamic. I'm not pro in Django so please suggest me -
manage. django.db.utils.Operational Error connection to server on socket "/cloudsql/.s.PGSQL.5432" failed: Invalid argument (0x00002726/10022)
.\cloud_sql_proxy.exe -instances="ajrsd2:us-central1:ajrsd2"=tcp:5432 is working fine. https://prnt.sc/WpLWyy_e4ZAy python manage.py runserver is getting the error django.db.utils.OperationalError: connection to server on socket "/cloudsql/ajrsd2:us-central1:ajrsd2/.s.PGSQL.5432" failed: Invalid argument (0x00002726/10022) https://prnt.sc/rJpfVfjUgAX1 We are executing these commands in Visual studio app in Windows 10. I have checked secrets details in https://console.cloud.google.com/security/secret-manage There are no restrictions in the access permission. Also I have verified steps as per the below reference link. https://cloud.google.com/python/django/appengine#console_3 Please let me know the troubleshooting steps on this. Thanks. -
Django and React: connection between login page of django with react home page
I need help in resolving the following issue. I created login page using django+html templates. I have my frontend running in react. When I login I need to render my home page in react. How can I connect my frontend from the login page written in html template in django? -
How to send javascript object with images to django api?
I have the following object: { name:"" colors: { red: { images: [img1, img2] variants: [ { size: "23" stock: 23, barcode: "" price: 200 }, ] }, } } Should I be using Form Data? But I am not really sure how I can do that? -
Django: set default value for new model field which has unique=True
There is a custom user model which inherits AbstractUser in Django. The model has username = None, below is the model: class User(AbstractUser): username = None email = models.EmailField(_("Email address"), unique=True) I want to remove username = None so that we can save usernames as well. But the issues is we have various users in the database. and when I remove the username = None and try to migrate, I get the prompt: It is impossible to add a non-nullable field 'username' to user without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. I don't want to override the username field of AbstractUser class. AbstractUser > username: username_validator = UnicodeUsernameValidator() username = models.CharField( _("username"), max_length=150, unique=True, help_text=_( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[username_validator], error_messages={ "unique": _("A user with that username already exists."), }, ) How can I provide the default value? -
how to create an app with in app inside a Django project? How that app can be registered to setting py file?
*project- New.app-app want to add an app inside app 1.how to register this to the setting.py file? what are the things I should be worried once I have an app with in an app? -
How can I create an HTML page using python? (Not pyscript) [closed]
I want to create some web apps that use python libraries like opencv or yt-dlp, is it possible with Django or it is only on JavaScript? If it is not possible, what Django do on python? -
How to insert a value when post request done in postman using django
Views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. from rest_framework import viewsets import requests import gdown from pydub import AudioSegment import speech_recognition as sr from .serializers import * from .models import * import time from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from urllib.request import urlopen class VoiceViewSet(viewsets.ModelViewSet): queryset = Voiceapi.objects.all() serializer_class = VoiceSerializer datas = Voiceapi.objects.values() print(datas) def post(self,request): vc_api = Voiceapi.objects.all() serializer = VoiceSerializer(vc_api,many=True) for i in datas: try: print("Audio File-->",i['name']) audio_url = i['name'] audio_id = i['id'] output = '/home/venpep/voicetotext/messages/media/sample2.ogg' gdown.download(audio_url, output, quiet=False) src = "/home/venpep/voicetotext/messages/media/sample2.ogg" # time.sleep(15) dst = "/home/venpep/voicetotext/messages/media/test.wav" sound = AudioSegment.from_ogg(src) sound.export(dst, format="wav") # time.sleep(15) def VoiceRecognizer(audio,audio_id): r = sr.Recognizer() with sr.AudioFile(audio) as source: audio_text = r.listen(source) try: text = r.recognize_google(audio_text) print(text) except: print('Audio Not Clear') audio = "/home/venpep/voicetotext/messages/media/test.wav" VoiceRecognizer(audio,audio_id) except: print("Not audio file") Models.py from django.db import models class Voiceapi(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=200) voice_text = models.CharField(max_length=200,default="voice_data") Serializer.py from .models import * class VoiceSerializer(serializers.HyperlinkedModelSerializer): # specify model and fields class Meta: model = Voiceapi fields = ('id', 'name', 'voice_text') When I post my data the "text" from views.py should insert into voice_text field in models.py database where I have given a default value. Is there any … -
React: Each color of a product has different images. What is the right way to post this type of data to Django api?
I have some basic product information like name, description and I also have colors that the product is in and each color has different sets of images like for eg: amazon. Now I am not sure how I can send all product info to my api? I can't just send it as JSON because of the images. Can anyone suggest something? Please ask if you don't understand my question! I already have my image model that will store these images. -
How to set a common dynamic value for all Django models in Django admin page?
I have an application, where i have created a next button to redirect to the next model. What i want is that, when i am in the first admin page, eg. Master is the model, and it is connected with other models based foreign key relationship. I want this Master ID, to get automatically populate when the next button is click. I thought of using cookies but i am not able to understand how to make change in the forms.py. I have created an API for setting and getting the API. views.py def setcookie(request): response = HttpResponseRedirect('/admin/core/masterfertilizer/add/') response.set_cookie('crop', request.GET.get("crop_id")) return response def getcookie(request): crop_id = request.COOKIES['crop'] return JsonResponse({'data': [crop_id]}) admin.py def response_change(self, request, obj): if "_next" in request.POST: return redirect(f'/core/setcookie/crop_id?crop_id={obj}') return super().response_change(request, obj) crop.js function getCropID(){ let $ = django.jQuery; $.get('/core/getcookie/', function(resp){ console.log(resp); document.querySelector('#id_master_crop_id').value=parseInt(x.split(';')[1].split('=')[1]); }); } forms.py self.fields['master_crop_id'].widget = forms.Select( attrs={ 'id': 'id_master_crop_id', 'onchange': 'getCropID()', 'style': 'width:200px' }, ) -
How to get value of ManyToMany Model rather than their ids?
I have three models, as shown below: class ImagesModel(models.Model): title = models.CharField(max_length=500, default='image') cdn = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='articles/images/', null=True, blank=True) timestamp = models.DateTimeField(auto_now=True) update = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class ArticlesModel(models.Model): title = models.CharField(max_length=1000) category = models.CharField(max_length=40, choices=category_choices, default=('General', 'General')) summary = models.TextField(blank=False, null=True, max_length=5000) tags = models.ManyToManyField(TagsModel, blank=True) publish_date = models.DateTimeField(auto_now=True) update_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(blank=True, null=True, upload_to='articles/article-image/') images = models.ManyToManyField(ImagesModel, blank=True) json = models.JSONField(null=True, blank=True) html = models.TextField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('articles:article_detail', kwargs={'article_id': self.id}) And in the view.py class ArticlesView(APIView): def get(self, request): articles_list = ArticlesModel.objects.all() images_list = ImagesModel.objects.all() images_serializer = ImagesSerializer(images_list, many=True) articles_serializer = ArticlesListSerializer(articles_list, many=True) return Response({ 'images':images_serializer.data, 'articles':articles_serializer.data }) So when I send request I get results like this: The problem here is that I get the ids of Images and tags and not the objects themselves! I am asking if there's a way in django/DRF to get the objects (images, tags) included with the queries of Articles and not only their ids?