Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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() -
Make Icon Clickable in HTML
I am essentially trying to replace the following EDIT and DELETE buttons with icons, but am running into issues trying to do this within HTML. The OnClick function doesn't seem to do anytihng when I click the buttons. Any ideas on how to adjust this code? html <div style="height:400px; overflow:auto; margin:0px 20px 20px 20px"> <table id="userTable" class="table table-striped" style="font-family: graphik"> <tr> <th>Employee</th> <th>Description</th> <th colspan="3">Stakeholder Group</th> </tr> {% for user in users %} <tr id="user-{{user.id}}"> <td class="useremployee userData" name="employee">{{user.employee}}</td> <td class="userdescription userData" name="description">{{user.description}}</td> <td class="userstakeholder_group userData" name="stakeholder_group">{{user.stakeholder_group}}</td> <td align="center"> <button class="btn btn-success form-control" onClick="editUser({{user.id}})" data-toggle="modal" data-target="#myModal" )">EDIT</button> </td> <td align="center"> <img class="d-block w-100" src="{% static 'polls/images/edit.png' %}" style="cursor:pointer; width: 30px; height: 30px" alt="opmodel"> </td> <td align="center"> <img class="d-block w-100" onClick="editUser({{user.id}})" src="{% static 'polls/images/delete.png' %}" style="cursor: pointer; width: 30px; height: 30px" alt="opmodel"> </td> <td align="center"> <button class="btn btn-danger form-control" onClick="deleteUser({{user.id}})">DELETE</button> </td> </tr> {% endfor %} </table> </div> -
Which is the best way to bulid chat application in django with mongodb
Can any one pls suggest how to implement the chat application using django with mongodb -
How do you delete a Django Object after a given amount of time?
I'm a new Django developer, and working on a website where users can store csv files outputted by the website to a field of a model along with a randomly generated key. I referred to this link: Delete an object automatically after 5 minutes for more information, but when I implemented it onto my own project, it did not work. from django.db import models from django.utils import timezone from django.conf import settings import datetime import os # Create your models here. class TemporaryFile(models.Model): key = models.CharField(max_length = 64) data = models.FileField() time_created = models.DateTimeField(default = timezone.now) @property def delete_after_time(self): if self.time_created < datetime.datetime.now()-datetime.timedelta(minutes=1): self_file = TemporaryFile.objects.get(pk = self.pk) data = self.data os.remove(os.path.join(MEDIA_ROOT, data)) os.remove(os.path.join(BASE_DIR, data)) self_file.delete() return True else: return False Because it is difficult to store a csv file to a model field, I instead saved it to the default storage that Django has, which for some reason made two copies of the csv file and stored one in the media root and another one in the base directory. That is why I have the os.remove functions. Can somebody please tell me why the object and files are not being deleted? -
Django URL not loading response in browser, when opened from HTML file using href attribute
I am comparatively new to web development , trying to open Django URL by "href" link in HTML file. But URL response not loading fully in browser. While same link(URL), when opened directly in browser, url response loads fully. Below is the sample Django view def sampleview(request): return HttpResponse("URL response loaded fully") Sample URL for view url(r'^sampleurl/$', views.sampleview, name='sampleurl') When opening URL link directly in browser Browser shows the response as "URL response loaded fully" While when opening the link through href attributes of html view, like <a href="/sampleurl">Sample link</a></li> browser do not loads the response Have tried following: i) Making the link as `href="/sampleurl/" instead of href="/sampleurl"` ii)Using url name in the `{% url 'sampleurl' %} instead of href="/sampleurl"` but failed to resolve the issue -
(Django Migration Bug with PostgreSQL) django.db.utils.ProgrammingError: relation "subjects_subject" does not exist
**Link github to this repo : **https://github.com/thetruefuss/elmer When i start this project using sqlite for database, it migrate with database perfectly, but when i switch it to POSTGRESQL, it got this error: django.db.utils.ProgrammingError: relation "subjects_subject" does not exist LINE 1: ...ect"."created", "subjects_subject"."updated" FROM "subjects_... THE POINT IS: in this repo it already had all the migrations file for all model, u can check in this repo, and i cannot migrate this with database in pgadmin 4 db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'demo_postgres', 'USER':'postgres', 'PASSWORD':'18092000', 'PORT':'5432', 'HOST':'127.0.0.1', } } ** my command ** python manage.py migrate subjects_subject ( migration_file) class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0001_initial'), ] operations = [ migrations.CreateModel( name='Subject', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(db_index=True, max_length=150)), ('slug', models.SlugField(blank=True, max_length=150, null=True)), ('body', models.TextField(blank=True, max_length=5000, null=True)), ('photo', models.ImageField(blank=True, null=True, upload_to='subject_photos/', verbose_name='Add image (optional)')), ('rank_score', models.FloatField(default=0.0)), ('active', models.BooleanField(default=True)), ('created', models.DateTimeField(default=django.utils.timezone.now)), ('updated', models.DateTimeField(auto_now=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posted_subjects', to=settings.AUTH_USER_MODEL)), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='submitted_subjects', to='boards.Board')), ('mentioned', models.ManyToManyField(blank=True, related_name='m_in_subjects', to=settings.AUTH_USER_MODEL)), ('points', models.ManyToManyField(blank=True, related_name='liked_subjects', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('-created',), }, ), ] subjects_subject(model_file) class Subject(models.Model): """ Model that represents a subject. """ title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, null=True, blank=True) body = models.TextField(max_length=5000, blank=True, null=True) photo … -
Django IntegrityError at /doctor-add-notes NOT NULL constraint failed:
I am a newbie. Enhancing a project For the current user, there are different members, for each member I want to add Notes with the current time & date. so I am using Django in-built user model. for example User1 Member1 Notes Date & Time Member2 Notes Date & Time Member3 Notes Date & Time **User2** Member1 Notes Date & Time Member2 Notes Date & Time Member3 Notes Date & Time for now just trying to add user1, member1 Notes & Date but after submitting the form getting an error. how to correct that, IntegrityError at /doctor-add-notes NOT NULL constraint failed: hospital_notes.user_id Request Method: POST Request URL: http://127.0.0.1:8000/doctor-add-notes Django Version: 3.0.7 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: hospital_notes.user_id Exception Location: C:\Users\user1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Users\user1\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\user1\\PycharmProjects\\Project\\hospitalmanagement', 'C:\\Users\\user1\\PycharmProjects\\Project\\hospitalmanagement', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\Users\\user1\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages'] Server time: Thu, 31 Dec 2020 03:37:51 +0000 Here is part of relevant code **Models** class Notes(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) report = models.TextField(max_length=500) NoteDate = models.DateField(auto_now=True) **View:** def doctor_add_notes_view(request): appointmentForm=forms.PatientNotesForm() mydict={'appointmentForm':appointmentForm,} print(mydict) if request.method=='POST': appointmentForm=forms.PatientNotesForm(request.POST) if appointmentForm.is_valid(): appointment=appointmentForm.save(commit=False) appointment.save() return HttpResponseRedirect('doctor_add_notes') else: return render(request, 'hospital/doctor_view_patient.html',{'alert_flag': True}) return render(request,'hospital/doctor_add_notes.html',context=mydict) **Forms:** class PatientNotesForm(forms.ModelForm): class Meta: model=models.Notes fields=['report'] **doctor_add_notes.html** {% extends … -
How to build a exchange software (like the Stock Market) in Django?
I am trying to build an exchange software that would handle buy and sell orders and execute transactions within Django. To be clear, this is not a software that would buy and sell existing stocks like from the US Stock Exchange and try to make a profit. Think of it as trying to create a site just like Fidelity or Robinhood where the software connects buyers to sellers and fulfills millions of transactions a day. I am trying to create the Fidelity or Robinhood, not a bot that would try to trade on Fidelity or Robinhood. Are there any packages or resources anyone is familiar with that would be helpful for this? I haven't been able to find any on my own but am sure someone has tried to do this in the past. -
Postgresql GIN index not used when query is performed with icontains
When I query the table using icontains, Django performs an SQL query using UPPER and the index seems to be useless. When I query the same table using contains the index is used. The difference is 3ms vs 240ms. Should I create a lowercase index and match with contains? (How could this be done?) Should I create a field where all the contents will be lower cased and index that field? Something else? The model: class Name(models.Model): name_en = models.CharField(max_length=127) ... class Meta: indexes = [ GinIndex( name="name_en_gin_trigram", fields=["name_en"], opclasses=["gin_trgm_ops"], ) ] The query that uses the index: >>> Name.objects.filter( Q(name_en__contains='eeth') | Q(name_en__trigram_similar='eeth') ) SELECT * FROM "shop_name" WHERE ("shop_name"."name_en"::text LIKE '%eeth%' OR "shop_name"."name_en" % 'eeth') LIMIT 21; The resulting query plan: Limit (cost=64.06..90.08 rows=7 width=121) (actual time=0.447..2.456 rows=14 loops=1) -> Bitmap Heap Scan on shop_name (cost=64.06..90.08 rows=7 width=121) (actual time=0.443..2.411 rows=14 loops=1) Recheck Cond: (((name_en)::text ~~ '%eeth%'::text) OR ((name_en)::text % 'eeth'::text)) Rows Removed by Index Recheck: 236 Heap Blocks: exact=206 -> BitmapOr (cost=64.06..64.06 rows=7 width=0) (actual time=0.371..0.378 rows=0 loops=1) -> Bitmap Index Scan on name_en_gin_trigram (cost=0.00..20.03 rows=4 width=0) (actual time=0.048..0.049 rows=15 loops=1) Index Cond: ((name_en)::text ~~ '%eeth%'::text) -> Bitmap Index Scan on name_en_gin_trigram (cost=0.00..44.03 rows=4 width=0) (actual time=0.318..0.320 rows=250 …