Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
relationship choices¶widget showing text
I would like to display choices of Test_Baustoff->art Model in my Test_Objekt Model Form. Right now i am trying to solve it with a Widget... Models: class Test_Objekt(models.Model): baustoffid = models.ForeignKey(Test_Baustoff, on_delete=models.CASCADE) bezeichnung = models.CharField(max_length=100, default='', blank=True) class Test_Baustoff(models.Model): art = models.CharField(max_length=100) wert = models.IntegerField(default='0') Forms: (found this code in the django docs... don't know if i am using it in the right way??) class BaustoffidSelect(forms.Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option = super().create_option(name, value, label, selected, index, subindex, attrs) if value: option['attrs']['data-wert'] = value.instance.wert return option class ObjektForm(forms.ModelForm): class Meta: model = Test_Objekt fields = ['bezeichnung', 'baustoffid', 'bauweiseid', 'dickeaussenwand', 'dickedaemmung', 'fensterqualitaet'] labels = {'bezeichnung': 'Objekt-Bez'} widgets = {'baustoffid': BaustoffidSelect} html template: <table class="table table-bordered table-light"> {{objekt_form.as_table}} </table> For the moment, I don't find a way to solve my problem. I looked some tutorials or StackOverflow questions but nothing up to now. Do you have any idea about this handling? -
How to filter DB query with OR in Django
I am trying to structure a WHERE question LIKE 'Who%' OR question LIKE 'What%' SQL query from inputs of a POST request. What is the correct way to do this? https://docs.djangoproject.com/en/3.1/topics/db/queries/#complex-lookups-with-q-objects from django.db.models import Q def getuserlist(request): if request.method == "POST": showall = request.POST['showall'] showfl_1 = request.POST['showfl_1'] showfl_2 = request.POST['showfl_2'] if showall: filt = Q(listing=any) elif showfl_1: filt = Q(listing="Filtered1") elif showfl_2: filt = filt | Q(listing="Filtered2") searchresult = list(User_data.objects.filter(listing=filt).values_list("Country","gender","listing").order_by('-added_date')) return searchresult -
LimitOffsetPagination with viewsets.ViewSet in Django Rest Framework
Can we use LimitOffsetPagination with viewsets.ViewSet in Django Rest Framework. Below is how my list view looks: def list(self, request): # serializer for validating list request serializer = UserIndexSerializer(data=request.query_params) if serializer.is_valid(): users = User.objects.all() serializer = UserGetSerializer(users, many=True) response = {"users": serializer.data, "total": len(serializer.data)} return AppResponse.success("User list found.", response) return AppResponse.error(serializer.errors, None, http_error_code=400) -
Django: no such table: create_genres
I have run makemigrations and migrate but both give the same error. I found that the code below is what causes the error. I have also deleted migrations folder and remade it with init file and deleted the database but doesn't seem to help. This code was working fine for a while but now it keeps giving the same error. models.py class Genres(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Genres" class Post(models.Model): genres = models.ManyToManyField(Genres) -
Why are models having there parent class names in admin Django
I have created models like this class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) and in the users.admin.py, I have admin.site.register(Supplier) admin.site.register(Worker) Why is it that I have all models names as Users in the Django Admin? instead of Workers and Suppliers? -
ASIC BRS SOAP API service Binding Bug
I was pulling my hair building ASIC(Australia) Business Registration (BRS) App for a client. ASIC SOAP API in UAT has an a bug in a service binding within a soap response. It returns an incorrect URL. -
'loginForm object has no attribute 'is_valid' in django why i'm getting this
'loginForm' object has no attribute 'is_valid' can anyone have solution why i'm getting this i just trey to get data and the form it shows error on this line is_valid() in django >login.py <form action ='' method ='POST' > {% csrf_token %} <div class="form-group"> <label for="formGroupExampleInput">User Name</label> <input type="text" id='username' name = 'username' class="form-control" id="formGroupExampleInput" placeholder=""> </div> <label for="inputPassword5">Password</label> <input type="password" name ='password' id="password" class="form-control" aria-describedby="passwordHelpBlock"> <input class="btn btn-primary my-3" type="submit" value="Submit"> </form> </div> > views.py def login(request): if not request.user.is_authenticated: if request.method == 'POST': form = loginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username , password=password) if user is not None: login(request , user) messages.success(request,'logged in Successfully !!') return HttpResponseRedirect('dashbord') else: form = loginForm() else: return HttpResponseRedirect('dashbord') return render(request,'login.html',{'form':form}) def logout(request): return HttpResponseRedirect('/') > models.py class loginForm(models.Model): username = models.CharField(max_length=50) password = models.EmailField(max_length=200 ) -
manyToMany django form
i have a class PhoneBook and a class Campaign and these tow have ManyToMany relation.... when i use Modelform for create Campaign it shows me all the Phonebooks in checkbox...but i want just show current user's PhoneBooks ..not all the PhoneBooks!!!! what can i do? class Campaign(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="کاربر") title = models.CharField(max_length=200, verbose_name="عنوان کمپین") phone_book = models.ManyToManyField(PhoneBook, verbose_name='دفترچه تلفن') message_price = models.PositiveBigIntegerField(verbose_name="نرخ هر پیام") daily_budget = models.PositiveBigIntegerField(verbose_name="سقف بودجه ی روزانه") class CreateCampaignForm(forms.ModelForm): class Meta: model = Campaign fields = ("title", "phone_book", "message_price", "daily_budget") -
Serialize the specific form in Ajax request POST
I have Table of Books, for each row there's book no, and book name and delete button which will delete the book and i am using ajax for deleting, the problem i have when i click the delete button it always delete the first book in the table , any help thanks. <table> <thead> <tr> <th>Book NO</th> <th>Book Name</th> <th>Remove</th> </tr> </thead> <tbody> {% for book in book_List %} <tr> <td>{{book.no}}</td> <td>{{book.name}}</td> <td> <form method="POST"> <input type="hidden" name="remove_uuid" value="{{ book.uuid}}"> <button onclick="delete()">Delete</button> </form> </td> </tr> {%endfor%} </tbody> </table> script function delet(){ $.ajax({ type:'POST', data: $('form').serialize(), success: function (data) { alert("the book has been delete it") } } -
Create DRF serializers class dynamically
I have a few DRF serializer classes of the same model. I want to move the class creation code to a function to avoid code repetition. So basically I have to return a class from a function, but I am unable to access the function parameters inside the class. def get_course_serializer(fields, read_only_fields=None): class CourseSerializer(serializers.ModelSerializer): if "id" in fields: id = serializers.CharField(default="", read_only=True) class Meta: model = Course fields = fields if read_only_fields: read_only_fields = read_only_fields return CourseSerializer Here the fields aren't accessible inside the CourseSerializer class definition. I tried using global keyword, but it didn't work. I am planning on using this function as below CourseListSerializer = get_course_serializer( ["id", "title", "slug", "description"]) -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. in Django 3.1
I have used Django Multitenant. I need to create a tenant creation flow in the background. so I have used multiprocessing Django. Here my code is p1 = multiprocessing.Process(target=create_tenant_background, args=[username,email,password,tenant_name,user.id]) p1.start() and my background function is def create_tenant_background(username,email,password,tenant_name,user_id): # my code After I run the code below error in the terminal pls help me to solve the issue. -
Django Channels - Not Able to Send Messages on Disconnect
I would like to be able to send a message to the room group on disconnect of the user so that it updates the player list. It seems that it is not possible once disconnected, which would make sense in a way, but how would I be able to send a message to the channel before it disconnects the user. I have the following code: async def disconnect(self, close_code): #Remove the disconnected player player = players.get_player(self.scope['session']['id']) players.remove_player(player.id) room = rooms.get_room(player.room) if room: #Sending messages on disconnect doesn't seem to work players_left = room.leave_room(player) if players_left < 1: rooms.remove_room(room.name) await self.channel_layer.group_send( 'all_users', { 'type': 'room_list', } ) await self.channel_layer.group_discard( room.name, self.channel_name ) else: await self.send_room(room,'list_players') async def send_room(self,room,type): await self.channel_layer.group_send( room.name, { 'type': type, 'data': room.name } ) async def list_players(self,event): # Send message to WebSocket room = rooms.get_room(event['data']) players = room.get_players() await self.send(text_data=json.dumps({ 'action': 'room_list_players', 'payload' : { 'players' : players, 'owner' : room.owner.id } })) -
Django CSS/JS MIME type (“text/html”) mismatch Error
I am developing a a web application which runs on a local server provided by django.The first page index.html has many css and javascript files. But none of them is properly rendered on browser. All the css/js files show same MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff) error. The firefox console shows the error briefly - The resource from “http://localhost:8000/C:/Users/PYTHON/foodie/static/plugins/scrollTo/jquery.scrollTo.min.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). -
Import with __init__.py on windows
Currently I have a directory that looks like this: -test -functions -sub_func -add.py -__init__.py -__init__.py -main.py I want to import add.py into main.py, and it works if I do from sub_func import add , but it comes with pylint(import_error) saying unable to import 'sub_func'. So I tried from functions.sub_func import add the pylint error is resolved, but when I run it, an error appears saying ModuleNotFoundError: No module named 'functions' Is there a way I can import add.py while keeping the __init__.py files? edit: I am using python3.9 edit2: So I didn't resolve the problem, but for some reasons, if I had from sub_funct import add in the provided views.py from django, it causes an error, calling that Module not found, but it works when I just python run it in the terminal. Opposite happened when I used from functions.sub_func import add, running python in server didn't work, with the error message saying no module named 'functions', but by running the server, the import seems to be working. I am happy it's working, but I am very confused on why it works when I run the django server, but it doesn't work when I run it using python straight away, … -
'loginForm' object has no attribute 'is_valid' in django
` def login(request): if not request.user.is_authenticated: if request.method == 'POST': form = loginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username , password=password) if user is not None: login(request , user) messages.success(request,'logged in Successfully !!') return HttpResponseRedirect('dashbord') else: form = loginForm() else: return HttpResponseRedirect('dashbord') return render(request,'login.html',{'form':form}) def logout(request): return HttpResponseRedirect('/') ` -
"has_add_permission" is called on every admin page irrespective of explicitly invoked in Django Admin
I have override "has_add_permission" in one of my ModelAdmin and it has been called automatically in my other modelAdmin classes too. I found that it is happening due to "each_context" method called every time. Is there any way we can stop that thing calling on each model admin. -
Collect ids as list during annotate grouping by different parameters in Django
I have to collect distinct vehicle_type_ids while annotating in django . This is what I have right now along with grouping by city_code and final_driver_owner_contact. I wish to collect all corresponding vehicle_types grouped by them (city_code, final_driver_owner_contact) and month. od_engagement = list(FieldOpsBooking.objects.using( 'analytics').exclude(**exclude_query).filter(**filter_query).values( 'city_code', 'final_driver_owner_contact').annotate( booking_count=Count('final_driver_owner_contact'), vehicle_count=Count('final_driver_vehicle_no', distinct=True), total_cost=Sum('final_driver_rate'), month=TruncMonth('pick_up_at'))) Is it possible to add it to this query (similar to mongodb which lets you push ids while grouping in aggregate. Or is there another way to get the same using a separate query. Any help is appreciated. -
How to reduce memory consumption (RAM) on Python/Django project?
My memory usage on a Django DRF API project increases over time and RAM is getting filled once I reach 50+ API calls. So far I tried loaded all models, class variable upfront used memory profiler, cleaned code as possible to reduce variable usage added garbage collection : gc.disable() at beginning and gc.enable() at end of code added ctypes mallot.trim() at end of code etc Any suggestions on how to free up memory at the end of each request ? -
How to check requirements. txt file package are not used in Django
I have a number of packages in the requirements.txt file. I need to list which packages are used in the Django project and Which packages are not used in the Django project using the command prompt. Is it possible? -
django re_path seeing correct path but it didnt match
here is my path re_path(r'^creator-by-slug/(?P<creatorslug>[^A-Za-z0-9]+)$', GetContentCreatorByCreatorUrlSlug.as_view()) and here is my error output Not Found: /creator-by-slug/test1 [31/Dec/2020 06:14:03] "GET /creator-by-slug/test1 HTTP/1.1" 404 2374 its going to the path but the test1 which is my current creatorslug is not being recognised as a query param I think note the creatorslug can be any string of letters and numbers together Cat cat catepiller caTe3piller would all be valid -
Django Channels group_send not sending across the opponent_offline in some cases when one user disconnects
I'm developing a chess game on Django using Django Channels. Here are the relevant portions of the GameConsumer class GameConsumer(AsyncJsonWebsocketConsumer): async def disconnect(self, code): await self.disconn() await self.opp_offline() async def opp_offline(self): await self.channel_layer.group_send( str(self.game_id), { "type": "offline.opp", 'sender_channel_name': self.channel_name } ) async def offline_opp(self,event): if self.channel_name != event['sender_channel_name']: await self.send_json({ "command":"opponent-offline", }) print("sending offline") @database_sync_to_async def disconn(self): user = self.scope["user"] game = Game.objects.all().filter(id=self.game_id)[0] if game.opponent == user: game.opponent_online = False print("Setting opponent offline") elif game.owner == user: game.owner_online = False print("Setting owner offline") game.save() So what happens is that I want to notify the other online user (if any) that their opponent has disconnected. So here's the case in which there's a problem: The first user connects. It shows that his opponent has not connected yet and tells him to wait. The second user connects. The game starts for both of them. Now the first user disconnects before any moves have been made. The second user does not get the user offline notification. But if it was the other way round ie the second user is the one disconnecting, then the first user gets the notification. But if a move has been made then everything works normally. Trying to find … -
Add a comment section in django
So i have a problem which is i don't know how can i add the comment on my project. My project is a star social this project you can only post if you are in a group. I want to add a comment section on my project but i don't know how i tried to search on google and i see some of solution and i tried to add it to my project but it is not working and now i am very frustrate and i don't know what to do and i hope someone will help me to add a comment section on my project and btw i'm a beginner and i'm currently learning django. This is the project code https://github.com/K3v1n0153/Star-Social.git -
Using Django smart_select with settings.Auth_user_model
I am trying to do a dynamic selection on the admin page using smart_select package. It works well with my defined model - Attendee. But I am not able to get it to work with my AUTH_USER_MODEL. Can anyone assist to help me with this? I have tried to use both code below, but my leader in my listing should showing blank. ChainedForeignKey(Group, chained_field='syndicate', chained_model_field='creator', show_all=False, auto_choose=True, sort=True) ChainedForeignKey(settings.AUTH_USER_MODEL, chained_field='syndicate', chained_model_field='username', show_all=False, auto_choose=True, sort=True) My model.py file is per below: from django.db import models from django.conf import settings from django.db.models import fields from smart_selects.db_fields import ChainedForeignKey from django.db.models.fields import CharField, SlugField from django.urls import reverse # Create your models here. class Group(models.Model): """ Create a model/table for group going to church eg. Alpha Group; Christmas Casts/Crews """ name = models.CharField(max_length=200, db_index=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True,) slug = models.SlugField(max_length=200, unique=True, db_index=True) class Meta: ordering = ('name', ) verbose_name = 'group' verbose_name_plural = 'groups' def __str__(self): return self.name # def get_absolute_url(self): # return reverse() class Attendee(models.Model): """ Create attendee """ group = models.ForeignKey(Group, related_name='attendees', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name', ) index_together = (('id', 'slug'), ) # Specify an index for the … -
how i will handle 500 error in python Django api
When I will use Django api then how I will handle internal server error error handling python Django when internal server error 500 -
Django Query Error: How do i properly query my total likes to show in the Home Screen?
can anyone advice on how to query the total_likes of a post to be shown in my html, i tried but was given this error: Page not found (404) No BlogPost matches the given query. THANK YOU! views.py def home_feed_view(request, **kwargs): context = {} blog_posts = sorted(BlogPost.objects.all(), key= attrgetter('date_updated'), reverse = True) blog_post = get_object_or_404(BlogPost, slug=request.POST.get('blog_post_slug')) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exists(): liked = True context['blog_posts'] = blog_posts context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, "HomeFeed/snippets/home.html", context) def LikeView(request, slug): context = {} post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return redirect('HomeFeed:detail', slug=slug) .html {% for post in blog_posts %} <td class="table-primary"><form action="{% url 'HomeFeed:like_post' post.slug %}" method="POST">{% csrf_token %} <button type="submit" name="blog_post_slug" value="{{post.slug}}" class='btn btn-primary btn-sm'>Like</button> {{ total_likes }} Likes</form></td> {% endfor %} models.py class BlogPost(models.Model): body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) slug = models.SlugField(blank=True, unique=True) def total_likes(self): return self.likes.count()