Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
UserWarning on Kubernetes Django app in DigitalOcean
Deployed a Django app on a K8s cluster in Digital Ocean using a GitHub Actions Workflow, and this part run: | export SINGLE_POD_NAME=$(kubectl get pod -l app=django-doapp-web-deployment -o jsonpath="{.items[0].metadata.name}" | tr -d '\r') kubectl exec -it $SINGLE_POD_NAME -- bash /app/migrate.sh kubectl exec -it $SINGLE_POD_NAME -- bash /app/collectstatic.sh Even though it builds most of the time, it gives always the following Unable to use a TTY - input is not a terminal or the right kind of file /app/manage.py:21: UserWarning: Not reading /app/.env - it doesn't exist. dotenv.read_dotenv() As it is still not clear, decided to check the pod logs with kubectl logs -f [POD_NAME] There I can see this error [2022-10-20 04:49:36 +0000] [8] [INFO] Booting worker with pid: 8 /app/django_doapp/wsgi.py:19: UserWarning: Not reading .env - it doesn't exist. dotenv.read_dotenv(str(ENV_FILE_PATH)) This seems to be pointing to a problem in the wsgi.py file. Mine looks like this import os import pathlib import dotenv from django.core.wsgi import get_wsgi_application CURRENT_DIR = pathlib.Path(__file__).resolve().parent BASE_DIR = CURRENT_DIR.parent ENV_FILE_PATH = BASE_DIR / ".env" dotenv.read_dotenv(str(ENV_FILE_PATH)) # This is line 19 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_rentals.settings') application = get_wsgi_application() What is the impact of this and how to solve it? As it may be relevant the project structure is similar to … -
I want to make this website in a tabular format but it only comes in a vertical line
This is the output I am getting https://i.stack.imgur.com/Tqekd.jpg I have copies the bootstrap card code from the offical site and tried many changes to my code but the output always comes in a vertical line. *Please suggest a way to make it in a tabular format(likely 3 columns in a full window) it would be really helpful. * {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col-sm-4"> <div class="card" style="width: 18rem;"> <img src="{{ product.image_url }}" class="card-img-top" alt="..." width="300" height="300"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">${{ product.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> </div> </div>[enter image description here][1] </div> {% endfor %} </div> {% endblock %} -
Foriegn_key overwrite and show some field problem. I want to restock my inventory product
Foriegn_key overwrite and show some field problem. I want to restock my inventory product. enter image description here -
Django Filter by ForeignKey value
Suppose I have two models class DocumentType(BaseModel): name = models.CharField(max_length=128) code = models.CharField(max_length=128) exp_days = models.PositiveIntegerField("Remind me before (Days)", blank=True, null=True) def __str__(self): return str(self.name) class EmployeeDocument(BaseModel): type = models.ForeignKey("masters.DocumentType", on_delete=models.PROTECT) date_of_expiry = models.DateField(blank=True, null=True) attachment = models.FileField(blank=True, null=True) def __str__(self): return str(self.employee) I need to get the documents that will expire in the next {exp_days} mentioned in the type. documents = Document.objects.filter(date_of_expiry__lte=today+timedelta(days=30)) The above filter will return the documents expiring in the next 30 days. But how to apply the exact same condition -
Rotating User inside model in Django
Hi I have two models like below: class ShiftModel(BaseModel): name = models.CharField(max_length=256) class UserShiftModel(BaseModel): user = models.OneToOneField( "user.User", on_delete=models.CASCADE, related_name="user_shift" ) shift = models.ForeignKey( ShiftModel, on_delete=models.CASCADE, related_name="shift_user" ) Now, suppose I have four shifts in my ShiftModel: s1, s2, s3, s4 And in each shift I have unique users stored in UserShiftModel. For example: s1 = [u1, u2] s2 = [u3, u4] s3 = [u5, u6] s4 = [u7, u8] Now what I want is to rotate the shifts backwords that is [u1, u2] will be move from s1 to s4, [u7, u8] will be move from s4 to s3 and so on. How can I achive this? Things I have done so far: current_branch = organization_models.BranchModel.objects.get( id=kwargs.get("branch_id") ) rotating_shifts = current_branch.branch_shift.filter( shift_type="rotating" ).prefetch_related( Prefetch( "shift_user", queryset=models.UserShiftModel.objects.filter(user__is_active=True), ) ) for i in range(len(rotating_shifts)): shift = list(rotating_shifts)[i] previous_shift = list(rotating_shifts)[i - 1] for user in shift.shift_user.all(): user.shift = previous_shift user.save() But the output of the above code is like this: s1 = [u3, u4] s2 = [u5, u6] s3 = [u7, u8, u1, u2] s4 = [] What I want is this: s1 = [u3, u4] s2 = [u5, u6] s3 = [u7, u8] s4 = [u1, u2] Hope I am … -
How to stop Django from rendering result in new tab
I have following views and each time form is submitted, result is rendered in new tab which has empty form. How to render result in same form (with data submitted) without opening new tab? views.py class contact(View): def __init__(self, logger=None, **kwargs): self.logger = logging.getLogger(__name__) def get(self, request): return render(request, 'test.html') def post(self, request): if request.method == 'POST': form = ContactForm(request.POST, request.FILES) if form.is_valid(): self.host = form.data['ip'] messages.success(request, "Successful") else: form = ContactForm() else: form = ContactForm() return render(request, 'test.html', {'form':form}) forms.py class ContactForm(forms.Form): ip = forms.CharField() urls.py urlpatterns = [ path('', contact.as_view()), ] html <body> <form action="/" method= "post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> </body> -
Upgrading up from Heroku-18 for a Django app. Any watchouts?
Title pretty much says it - I have a simple Django app that's been running on Heroku-18 for several years. With the upgrade requirement deadline approaching in spring 2023 I'm concerned with how the upgrade may affect my site. My biggest concern is the the database. The app is configured with just the default SQLite db. Once I deploy it looks like Heroku uses Postgres for the database stored on their side. Basically it just works once I deploy so I don't really care. For some recent sites I've been working on though, when I deploy those on Heroku-22 also with the same db setup it is just continuing to use the SQLite file and the data I've been messing around with locally is now part of the database once in the live app! So I am concerned once I upgrade to Heroku 22 stack my app will disconnect with the Postgres data stored on Heroku and will point to my local SQLite file. Hopefully I'm worried over nothing, but if anyone in similar situation has already worked through the upgrade and can provide some information on my particular concern and/or anything else to watch out for that would be …