Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: share local server with multiple laptops
is there a way to share my Django local server with multiple laptops. I wanted to build an exam web app to be done offline and to be later upload to online server. -
Django google kubernetes client not running exe inside the job
I have a docker image that I want to run inside my django code. Inside that image there is an executable that I have written using c++ that writes it's output to google cloud storage. Normally when I run the django code like this: container = client.V1Container(name=container_name, command=["//usr//bin//sleep"], args=["3600"], image=container_image, env=env_list, security_context=security) And manually go inside the container to run this: gcloud container clusters get-credentials my-cluster --region us-central1 --project proj_name && kubectl exec pod-id -c jobcontainer -- xvfb-run -a "path/to/exe" It works as intended and gives off the output to cloud storage. (I need to use a virtual monitor so I'm using xvfb first). However I must call this through django like this: container = client.V1Container(name=container_name, command=["xvfb-run"], args=["-a","\"path/to/exe\""], image=container_image, env=env_list, security_context=security) But when I do this, the job gets created but never finishes and does not give off an output to the storage. When I go inside my container to run ps aux I get this output: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 2888 1836 ? Ss 07:34 0:00 /bin/sh /usr/bin/xvfb-run -a "path/to/exe" root 16 0.0 1.6 196196 66256 ? S 07:34 0:00 Xvfb :99 -screen 0 1280x1024x24 -nolisten tcp -auth … -
Why is my django project not working after I have shut down my pc
when I start a new django Project it works perfectly well but after I shutdown or restart my pc it does not work again. even though I have activated my virtual environment it keeps giving me errors. -
Django: Errors when switching DateTimeField into DateField
I'm working on a project with Django. I used DateTimeField() when I first created some Model. I also created hundreds of instances. Then I decided that DateField was more appropriate and changed it. when I migrate, It was migrated well without any warning messages. But when I try to access original instances made with DateTimeField, I received the following error. invalid literal for int() with base 10: b'13 00:00:00' The Error seems to have occured because datetimefield data remains even though format has changed. But I don't know how to resolve it since I get this errors even when I try to delete existing instances. I also wonder why this error appears. -
In django rest; i'm tying to POST an artiste with a ForeignKey relation
I would like to add data to table which having a foreignkey relatonship with user model through django rest api. models.py class Artiste(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=200) name_vo = models.CharField(max_length=200, blank=True, null=True) name_vo_romanji = models.CharField(max_length=200, blank=True, null=True) biographie = models.TextField(blank=True, null=True) image = models.ImageField(upload_to=artiste_get_upload_to, blank=True, null=True) date_birth = models.DateTimeField(blank=True, null=True) date_death = models.DateTimeField(blank=True, null=True) nationnality = models.ForeignKey(Countrie, related_name='Artiste_countrie', on_delete=models.CASCADE, null=True) profession = models.ManyToManyField(Profession, related_name='Artiste_profession', blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Countrie(models.Model): slug = models.SlugField(unique=True) code = models.CharField(unique=True, max_length=2) name = models.CharField(unique=True, max_length=200) nationnality = models.CharField(unique=True, max_length=200) image = models.ImageField(upload_to=countrie_get_upload_to, null=True) serialiser class ArtisteSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) slug = serializers.SlugField(required=False) name = serializers.CharField() name_vo = serializers.CharField(required=False) name_vo_romanji = serializers.CharField(required=False) biographie = serializers.CharField(style={'base_template': 'textarea.html'}, required=False) image = serializers.ImageField(required=False) date_birth = serializers.DateTimeField(required=False) date_death = serializers.DateTimeField(required=False) nationnality = CountrieSerializer(required=False) profession = ProfessionSerializer(many=True, required=False) created_at = serializers.DateTimeField(read_only=True) updated_at = serializers.DateTimeField(read_only=True) def create(self, validated_data): print(validated_data) return Artiste.objects.create(**validated_data) def update(self, instance, validated_data): instance.slug = validated_data.get('slug', instance.code) instance.name = validated_data.get('name', instance.name) instance.name_vo = validated_data.get('name_vo', instance.name_vo) instance.name_vo_romanji = validated_data.get('name_vo_romanji', instance.name_vo_romanji) instance.biographie = validated_data.get('biographie', instance.biographie) instance.image = validated_data.get('image', instance.image) instance.date_birth = validated_data.get('date_birth', instance.date_birth) instance.date_death = validated_data.get('date_death', instance.date_death) instance.nationnality = validated_data.get('nationnality', instance.nationnality) instance.save() return instance class CountrieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) slug = serializers.SlugField(required=False) code = serializers.CharField() name … -
I got an error while trying to install psycopg2-binary
Error I want to learn to develop websites with python and Django. I bought a tutorial and made everything like the teacher. But while trying to install psycopg2-binary on my Mac to work with PostgreSQL 14, I got this error. Can anyone help me please. -
Custom actions in nested Django model
I currently have a model Thing that has User model as foreign key: class Thing(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) If I use Thing as standalone in admin, I can override deletion as follows: class ThingAdmin(admin.ModelAdmin): actions = ['delete_model'] def delete_model(self, request, obj): for o in obj.all(): # Do stuff o.delete() This works: if I go into admin, I click on 'Things', select which ones I wish to delete and the custom part runs (I wish there was a way to create a button instead of using a dropdown, but this is good enough). I do not, however, wish to have things as standalone in admin. I want them in a nested view from User model so that I could delete them directly from user view. For that reason, I use django-nested-admin: class ThingInline(nested_admin.NestedStackedInline): actions = ['delete_model'] def delete_model(self, request, obj): for o in obj.all(): # Do stuff o.delete() The things are displayed fine, but I am not getting a 'delete model' button anywhere. Question: how do i created custom actions for nested models? -
django-storages (azure) - accessing data without defining my azure container as the default file storage
So I have my azure storage which looks like this: class PublicAzureStorage(AzureStorage): account_name = 'myaccount' account_key = 'mykey' azure_container = 'mypublic_container' expiration_secs = None I want to get all the files that this container has and display them in my app - but my default file storage & static file storage are still local. From Azure I only want to get some .CSVs. How can I access this container as I said? In the docs it seems that I need to set Azure as the DEFAULT_FILE_STORAGE/STATICFILES_STORAGE in order to work. -
You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs
Getting the error: You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs. meetups/urls.py from django.urls import path from . import views urlpatterns = [ path('meetups/', views.index) #domain_name.com/meetups/ ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('meetups.urls')) ] views.py from django.shortcuts import render # Create your views here. def index(request): return render(request,'templates/meetups/index.html') -
How to upgrade my AWS ebs Platform from running Python 3.8 to python 3.10?
More specifically I am currently running Python 3.8 running on 64bit Amazon Linux 2/3.3.16. I was hoping to make it python 3.10. I have seen instructions online but I do not know where to run those commands and where to start. Thanks in advance for any help. -
Withdrawal in Django Rest API
I am getting an error "UserRoom object has no attribute 'images'" models.py class UserRoom(models.Model): objects = None categoty = [ ('President Lux', 'President Lux'), ('Lux', 'Lux'), ('Double', 'Double'), ('Standard', 'Standard'), ] name = models.CharField(max_length=150, choices=categoty, verbose_name='Категория') room_num = models.CharField(max_length=150,verbose_name='Доступные номера для категории') about = models.TextField(verbose_name='Подробности') price = models.IntegerField(verbose_name='Цена') img360 = models.FileField(verbose_name='Фотография в 360') class Meta: verbose_name = 'Номер (About)' verbose_name_plural = 'Номера (About)' class UserImg(models.Model): objects = None name = models.ForeignKey(UserRoom, on_delete=models.CASCADE, verbose_name='img2') img = models.FileField(upload_to='User img', verbose_name='Фотография') class Meta: verbose_name = 'Фотографию' verbose_name_plural = 'Фотографии' views.py class UserRoomViewSet(ModelViewSet): permission_classes = [AllowAny] queryset = UserRoom.objects.all() serializer_class = UserRoomSer serializers.py class UserImgSer(ModelSerializer): class Meta: model = UserImg fields = '__all__' class UserRoomSer(ModelSerializer): images = RelatedField( many=True, queryset=UserImg.objects.all()) class Meta: model = UserRoom fields = [ 'name', 'room_num', 'about', 'price', 'img360', 'images', ] urls.py from rest_framework import routers router = routers.DefaultRouter() router.register(r'room', UserRoomViewSet) urlpatterns = router.urls please help me with this problem i can't get json IN THE IDEA I SHOULD LOOK LIKE THIS { "images": [ { "name": "", "img": "" }, { "name": "", "img": "" } ], "name": "", "room_num": "", "about": "", "price": "", "img360": "" } ANOTHER PROGRAMMER HELPED ME AND EVERYTHING WORKS FOR HIM BUT WHY … -
Reverse for 'AddCart' not found. 'AddCart' is not a valid view function or pattern name
I am Working on my project and I don't know how this error I got Can anybody see what I'm missing? Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/onlinePizza/menu/ Django Version: 4.0.5 Python Version: 3.10.4 Installed Applications: ['onlinePizza.apps.OnlinepizzaConfig', 'cart', 'accounts', 'blog', 'django_user_agents', 'import_export', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_user_agents.middleware.UserAgentMiddleware'] Template error: In template C:\Django venv\Project\DjPizza\templates\onlinePizza\pc_menu.html, error at line 72 Reverse for 'AddCart' not found. 'AddCart' is not a valid view function or pattern name. 62 : {{i|cart_quantity:request.session.cart}} 63 : </div> 64 : <div class="col-auto"> 65 : <form action="{% url 'cart:AddCart' %}" method="POST">{% csrf_token %} 66 : <input hidden type="text" name="product" value="{{i.id}}"> 67 : <button class="main-btn cart cart-btn" style="padding: 3px 17px;"><i class="fa-solid fa-plus"></i></button> 68 : </form> 69 : </div> 70 : </span> 71 : {% else %} 72 : <form action=" {% url 'cart:AddCart' %} " method="POST">{% csrf_token %} 73 : <input hidden type="text" name="product" value="{{i.id}}"> 74 : <button class="main-btn cart cart-btn" style="padding: 5px 32px">Add <i class="fa-solid fa-cart-shopping"></i></button> 75 : </form> 76 : {% endif %} 77 : </div><!-- /Cart Button --> 78 : </div> 79 : </div> 80 : </div> 81 : </div> 82 : {% endfor %} Traceback (most … -
In admin I see "Topic_object(1)" but not actual object name
from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text # return f"{self.text[:50]}..." but I see this: Topic object(1), however I want to see Chess! enter image description here -
Slack Bot replies to every channel
I am using a slack bot to send messages from my app to slack. My use cases: ---> user types IN command to a specific bot and then the bot returns with system generated message within a channel Now everything is going well ..i want bot replies only if user's send direct messages to that bot. but in my case that is not happening.no matter which channel user;s type in command the bot replies but that is what i do not want. i want the system to reply only if user sends in command to my bot channel class SlackEvents(APIView): def post(self, request, *args, **kwargs): slack_message = request.data # denied if request is sent from some other url if slack_message.get('token') != SLACK_VERIFICATION_TOKEN: return Response(status=FORBIDDEN) # verification challenge if slack_message.get('type') == 'url_verification': return Response(data=slack_message,status=OK) # greet bot if 'event' in slack_message: event = slack_message.get('event') # ignore bot's own message if event.get('subtype') == 'bot_message': return Response(status=OK) # process user's message if event['type'] == 'message': # a = Client.conversations_open() user = event['user'] channel = event['channel'] other_channel = 'C03SKDLHUPP' msg = event['text'] if msg == 'in': in_command(channel,other_channel,user) if msg == 'out': out_command(channel,other_channel,user) if msg == 'brb': brb_command(channel,other_channel,user) if msg == 'lunch': lunch_command(channel,other_channel,user) if msg … -
drf viewset : multiple choices
I tried to make method(location_item) that shows item by region. And I want to implement the 'gu, dong' field(in location model) with multiple choices. so, wrote this method code. but filtering doesn't work.. This shows all item objects, not just the objects I want. TypeError: Field 'id' expected a number but got <Item: 애니원모어 원피스입니다!>. [13/Aug/2022 15:01:07] "GET /item_post/location/location_item/ HTTP/1.1" 500 152955 I don't know what sholud i do. please help me... models.py class Item(models.Model): user_id = models.ForeignKey(User, related_name='item_sets', on_delete=models.CASCADE) category_id = models.ForeignKey(Category, related_name='item_sets', on_delete=models.DO_NOTHING) description = models.TextField() feature = models.TextField() product_defect = models.TextField() size = models.CharField(max_length=6) wear_count = models.IntegerField() price = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.description class Location(models.Model): city = models.CharField(max_length=10) gu = models.CharField(max_length=10) dong = models.CharField(max_length=10) def __str__(self): return self.city+" "+self.gu+" "+self.dong class LocationSet(models.Model): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='location_sets') location_id = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='location_sets') serializers.py class ItemSerializer(serializers.ModelSerializer): photos = PhotoSerializer(source='photo_sets', many=True, read_only=True) style_photos = StylePhotoSerializer(source='style_photo_sets', many=True, read_only=True) class Meta: model = Item fields = '__all__' class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = '__all__' class LocationSetSerializer(serializers.ModelSerializer): class Meta: model = LocationSet fields = '__all__' views.py class ItemViewSet(ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer filter_backends = [SearchFilter, OrderingFilter] search_fields = ['description'] # … -
Django Error (unsupported operand type(s) for +: 'float' and 'NoneType')
I'm facing an issue of unsupported operand type(s) for +: 'float' and 'NoneType' actually I want to sum two different database column value in specific date range and one column has no value in this specific date range and that's why I'm facing that issue can anyone one help me One more thing help me to solve this in simple ways because I have many more arguments like that and if I use condition to make that value to zero that will be difficult for me the date range(modified6, modified5) is correct, if it contain a value, it display the number cell = Celldetail.objects.filter(DatePur__range=[modified6, modified5]).aggregate(Sum('Cell_price'))['Cell_price__sum'] bms = BMSdetail.objects.filter(DatePur__range=[modified6, modified5]).aggregate(Sum('BMS_price'))['BMS_price__sum'] -
Encrypt message field in django & render it on React after decrypting
i'm cloning a Whatsapp app as my personal project. i'm using React as my Frontend & Django as my backend. i'm using MongoDB to store my data & using django Rest framework to fetch it on frontend(i don't know how to retrieve it from MongoDB directly so if let me know if you can. it'll help me a lot). since it's personal messages, even logged in users shouldn't access to others messages but i can't hide them from others so i wan't to encrypt the data while storing it on backend & want to retrieve it by decrypting on frontend using React. i know a few libraries that Django has to encrypt a field but how can i decrypt it on the frontend??? #model.py from email import message from tkinter import Image from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver # Create your models here. class Room(models.Model): name = models.CharField(max_length=100,blank=True,null=True) def __str__(self): return self.name class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,blank=False,null=True) message = models.TextField(max_length=500,blank=False,null=True) name = models.CharField(max_length=100,blank=True,null=True) room = models.ForeignKey(Room,on_delete=models.CASCADE,null=True) time = models.DateTimeField(auto_now_add=True) received = models.BooleanField(default=False,null=True) views.py from rest_framework.response import Response from django.http import HttpResponse from rest_framework.decorators import api_view from App.models import * from .serializers import messageSerializer, roomSerializer … -
django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)")
the ERROR above I became in the tutorial lesson 'The Ultimate Django 3' of Mosh Hamedani. Lesson part: Running Background Tasks, 5-Celery and Windows. If you followed the pdf instruction and got no error, and lastly you had to run 'python manage.py migrate', maybe you got ERROR above. I wanna share the solution here and it`s so simple ). I am grateful to nicholas.allarick, it was his solution in codewithmosh forum. -
drf viewset method error : TypeError: Field 'id' expected a number but got <Item: ```>
I tried to make method that shows item by region. so, wrote this method code. but arise error like this. TypeError: Field 'id' expected a number but got <Item: 애니원모어 원피스입니다!>. [13/Aug/2022 15:01:07] "GET /item_post/location/location_item/ HTTP/1.1" 500 152955 I think filtering is works. but to fix error, I don't know what sholud i do. please help me... models.py class Item(models.Model): user_id = models.ForeignKey(User, related_name='item_sets', on_delete=models.CASCADE) category_id = models.ForeignKey(Category, related_name='item_sets', on_delete=models.DO_NOTHING) description = models.TextField() feature = models.TextField() product_defect = models.TextField() size = models.CharField(max_length=6) wear_count = models.IntegerField() price = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.description class Location(models.Model): city = models.CharField(max_length=10) gu = models.CharField(max_length=10) dong = models.CharField(max_length=10) def __str__(self): return self.city+" "+self.gu+" "+self.dong class LocationSet(models.Model): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='location_sets') location_id = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='location_sets') serializers.py class ItemSerializer(serializers.ModelSerializer): photos = PhotoSerializer(source='photo_sets', many=True, read_only=True) style_photos = StylePhotoSerializer(source='style_photo_sets', many=True, read_only=True) class Meta: model = Item fields = '__all__' class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = '__all__' class LocationSetSerializer(serializers.ModelSerializer): class Meta: model = LocationSet fields = '__all__' views.py class LocationViewSet(ModelViewSet): queryset = Location.objects.all() serializer_class = LocationSerializer # 지역별 아이템 조회 @action(detail=False, methods=['GET']) def location_item(self, request): locations = Location.objects.all() city = request.GET.get('city', None) # 시는 한개 gu = request.GET.getlist('gu', None) … -
AttributeError: 'Manager' object has no attribute 'Raw' , raw queryset(RawQuerySet) - Python, Django
Hey guys i was getting AttributeError: 'Manager' object has no attribute 'Raw' -
Login/Register feature not working on Deployed website
I have deployed the website by following all the steps in the video. But in the deployed site, I'm not able to register or login. Getting this error in the console. enter image description here I have used Next.js for the frontend and Django for the backend. Backend is deployed using Heroku CLI. And I've used Postgres for the database. -
Will google translate free api work when working on production website?
Will Google translator function work when hosting it in a live website, or there are any chances it will stop it services if google detects traffic. I am talking about the free translator function that we use in python. What are the chances? -
Adding a tag to a pagination element django
When creating a pagination, everything works as it should. Added (?page= page number selection) pagination. How can I add the pagination page number to its object? When selecting an object and reloading the page, I need it to be spelled out in the URL (/?page=pagination number). And the pagination remained on the selected page. class MovieShow(DetailView): model = Movie template_name = 'movies/movie_play.html' context_object_name = 'movie' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_list'] = Movie.objects.filter(course__slug=self.kwargs['course_slug']) context['title'] = context['movie'] paginator = Paginator(context['object_list'], 1) page = self.request.GET.get('page') try: context['object_list'] = paginator.page(page) except PageNotAnInteger: context['object_list'] = paginator.page(1) except EmptyPage: context['object_list'] = paginator.page(paginator.num_pages) return context This is how I present pagination in the template <div class="pagination" id="pagination"> <span class="step-links" > {% if object_list.has_previous %} <a class="page-link" href="?page=1"> << </a> <a class="page-link" href="?page={{ object_list.previous_page_number }}"> < </a> {% endif %} <span class="current"> {{ object_list.number }} из {{ object_list.paginator.num_pages }} </span> {% if object_list.has_next %} <a class="page-link" href="?page={{ object_list.next_page_number }}"> > </a> <a class="page-link" href="?page={{ object_list.paginator.num_pages }}"> >> </a> {% endif %} </span> And so I have a search of the elements inside the pagination, on which I want to hang the pagination page number. I really hope I asked the question correctly. I will be glad … -
I am not sure why I am getting an attributeError
So I have been using locust for stress testing my python programs. I attempted to do a post request using the client class, but for some reason I keep getting this error. this error occurs every time I try to make a most request by calling the register link -
Fetch files from outside of SvelteKit project directory
I'm fetching data, including media file links, from a Django API. Project structure as follows: -backend (Django) -core -media -frontend (SvelteKit) -src -lib -node_modules Both apps are running on different ports and I can't figure out how to access the files inside of backend/core/media from SvelteKit after fetching the link. The media link I'm receiving by my API would be something like this: /media/images/user1/image.jpg Thanks in advance!