Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I use 2 database models in Django programming?
in my models.py , I have 2 database named 'DB' and 'Rent'. what I want to do in my html page is to subtract rented number ( which is in Rent database ) from total number ( which is in DB databases ). I wonder if there is possible way to use for loop which first loop uses DB databases and second loop uses Rent databases. point is that I have to lookup both databases every loop. {% for p in DB %} <tr> <td>{{ p.product_name }}</td> <td>{{ r.rented_num }}</td> <!-- how can I do this??? --> <td>{{ p.total_num }}</td> </tr> {% endfor %} -
How to add object to ManyToMany field in django?
I have several models/table classes: class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=65, null=False) description = models.TextField() starting_bid = models.PositiveIntegerField(null=False) image = models.URLField(null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) def __str__(self): return self.title class Watchlist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) listing = models.ManyToManyField(Listing) def __str__(self): return f"Watchlist item of {self.user} user. Product: {self.listing}" I've registered these models in admin.py file: from django.contrib import admin from .models import Category, Listing, Bid, Comment, Watchlist, User # Register your models here. admin.site.register(Category) admin.site.register(Listing) admin.site.register(Bid) admin.site.register(Comment) admin.site.register(Watchlist) admin.site.register(User) When I go to the admin interface and trying to add item to the watchlist table I see the next form where I cat pick User to which will be belong that new watchlist object and also I can pick one or more Listing items: But when I hit save it saves Watchlist object with filled User field, and listing field stays empty. My question is how to add record to ManyToMany field in general and how could be added more than one item to the row with only two columns (admin and listing). Django Admin specifies literally that: "Hold down “Control”, or “Command” on a Mac, to select more … -
correct use of class method in django
I had studied class methods in python but never really understood its application in Djnago. My coding life was going well without the use of it. But I came across a situation where class method will be useful. My model: class Example(models.Model): post_count = models.IntegerField(default=0) @classmethod def total_counts(cls): return cls.objects.values('post_views').annotate(sum logic) In the above function, if I had used property decorator, i can only get a single object post_count because the object self is used. But if I use classmethod then I can count the post views of all the objects. So my thought is that whenever we have to deal with all the objects instead of a self object we need class method. Is this correct? Also, can we use this class method directly into our model serializer field just like we use property to serializer?? -
Django - Changed url to re_path, now getting 404 error
I've changed my url to re_path and am now getting 404, not found error. Any ideas? Here is my code for the urls.py and html which includes the ajax script: re_path(r'^get_mmm_ingredients/(?P<ingredient_type>\w+)/$', get_mmm_ingredients), <script> // populate ingredients let ingredient; $("select[name='ingredient_type']").change(function() { const ingredient_type = $(this).val(); const data = {"item": ingredient_type}; ingredient = $("select[name='ingredient']"); $.ajax({ url: '/get_mmm_ingredients/' + ingredient_type + '/', type: "GET", data: data, dataType: "json", success: function(data) { // empty value dropdown and add options ingredient.empty(); ingredient.append('<option>Select</option>'); $.each(data, function (index, text) { ingredient.append( $('<option></option>').val(index).html(text) ); }); } }); }); </script> -
How to hide id from url getting from django to html
I'm getting an ID from views def realtimeData(request): id = request.GET.get("id") site_url = ip+"/sites/list/" params = { 'id': id } sites = requests.request("GET", site_url, headers=headers, params=params) return render(request, 'realtime-data.html', {'sites': sites.json(), 'site': id}) site.html <td class="text-center" title="View Live Data"> <a href="{% url 'realtime-dashboard' %}?id={{site.id}}"> <span class="fas fa-eye"></span></a></td> <td>{{site.site_id}}</td> I wish to hide http://127.0.0.1:8000/sites/realtime-dashboard/?id=2 this site ID from url getting from views so that user cant see it -
HTML form sending duplicate files to the django server
The html form is displaying things correctly, but when i send it to Django part, the server is receiving (for example if I send 4 pictures, the first 3 pictures are just duplicates of the first picture, and the last picture is fine) duplicates of the first image and the last image. window.pageCount = 1; function addPage(el) { pageCount += 1; console.log(pageCount); window.el = el; window.div1 = el.parentElement.parentElement.parentElement.cloneNode(true); div1.id = 'p' + pageCount; console.log(div1.id); var children = div1.children; for (var i = 0; i < children.length; i++) { console.log(children[i]); if (children[i].tagName == 'DIV' && children[i].className.includes( 'img-thumbnail')) { children[i].children[1].src = '../media/add.png'; //.replace(/[^0-9]/g, ""); } } var subChildren = children[0]; subChildren.children[0].value = ''; subChildren.children[1].children[2].style.background = 'grey'; subChildren.children[1].children[3].value = ''; children[1].children[0].id += 1; document.getElementById('form').appendChild(div1); } window.image = null; function test(el) { var file = el.files[0]; console.log(file); var reader = new FileReader(); reader.onload = function (e) { // var image = el.nextElementSibling; image.src = e.target.result; console.log(image.id); //document.body.appendChild(image); // console.log('hello'); } reader.readAsDataURL(file); } function ChooseFile(el) { image = el document.getElementById('imagePick').click(); } function removePage(el) { el.parentElement.parentElement.parentElement.parentNode.removeChild(el.parentElement.parentElement.parentElement); pageCount -= 1; } function validate(el) { if (el.children.length > 0) { for (var i = 0; i < el.children.length; i++) { if (el.children[i].tagName === 'DIV' & el.children[i].className == 'page') … -
NoReverseMatch at /sitemap.xml ; error after installing sites framework
after installing sites framework (followed tutorial https://learndjango.com/tutorials/django-sitemap-tutorial) I can not access mywebsite/sitemap.xml file. URLS.PY from django.contrib.sitemaps import GenericSitemap # new from django.contrib.sitemaps.views import sitemap # new from newsfront.models import News info_dict = { 'queryset': News.objects.all()[:20], } urlpatterns = [ path('adminanoop/', admin.site.urls), path('',include('newsfront.urls')), path('sitemap.xml', sitemap, {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}}, name='django.contrib.sitemaps.views.sitemap'), ] MODELS.PY class News(models.Model): slug = models.SlugField(unique=True,null=True,blank=True) .............. def get_absolute_url(self): return reverse('Newsdetail', kwargs={'slug': self.slug}) -
How can I remove the border from this table
The thing is I want to add two anchor elements for every table row so I needed to add two more for those links, and the problem is that when I add them a border appears at the top of thead even when I set <th style="display:none;"></th> here's the table code .tablesgh table{ width: 80%; margin:auto; /* align-self: center; */ } <div class="tablesgh"> <table style="border-collapse: collapse;" class="table text-center table-responsive table-success table-hover table-bordered table-sm"> <thead> <tr> <!-- <div class="boldTd"> --> <th>Nom complet</th> <th>Num telephone</th> <th>Lien du profile</th> <th>Date ajouté</th> <th style="display:none;"></th> <th style="display:none;"></th> <!-- </div> --> </tr> </thead> {% for client in clients %} <!-- <script> var cli_name="{{client.name}}"; var cli_id="{{client.id}}"; </script> --> <tr> <td>{{client.name}}</td> <td>{{client.phone}}</td> <td>{{client.profile_link}}</td> <td>{{client.date_added}}</td> <td style="display:none;">{{client.id}}</td> <td><a style="position:relative;" href="{% url 'delete-record' client.id %}" class="btn btn-outline-danger">Effacer</a></td> <td><a href="{% url 'get-commandes' client.id %}" class="btn btn-outline-info">Afficher les commandes</a></td> </tr> {% endfor %} </table> <!-- </div> </div> --> </div> Here's a picture of the table -
Django - creating a model with circular relationship - from instance to another instance?
I am currently working on a small project. Two models are of interest: -Warehouse -BetweenWarehouseTransfers Note: each warehouse has multiple items in a different model (which are the products); Question: I want to be able to transfer the items from one warehouse to another. To this end in BetweenWarehouseTransfers I would like to have one field specifying the warehouse to which I am transferring speak item (to_warehouse) and one field specifying from which warehouse this item is coming (from_warehouse). Later on I would like to add autocomplete_fields to these two fields which only accept existing warehouses as inputs. Does anyone have an idea on how to create this circular relationship. I have posted a couple of solutions which I envisioned but each time there is a circular relationship problem: #0. (original version) from django.db import models from django_extensions.db.models import TimeStampedModel # from supply_chain.models.warehouse import Warehouse class WarehouseTransferProductVariant(TimeStampedModel): product_variant = models.IntegerField() amount = models.IntegerField() to_warehouse_id = models.CharField(blank=False, max_length=255) from_warehouse_id = models.CharField(blank=False, max_length=255) StatusChoices = models.TextChoices( "StatusChoices", "SENTREQUEST ACCEPTED DECLINED CANCELLED" ) status = models.CharField(blank=True, choices=StatusChoices.choices, max_length=255) # relation_from_to = models.ManyToManyField('warehouse.Warehouse', related_name="fromwarehouse_towarehouse") class FromWarehouseTransferProductVariant(TimeStampedModel): warehouse = models.ForeignKey(Warehouse, on_delete=models.RESTRICT) from_warehouse = models.CharField(max_length=255) class ToWarehouseTransferProductVariant(TimeStampedModel): warehouse = models.ForeignKey(Warehouse, on_delete=models.RESTRICT) to_warehouse = models.CharField(max_length=255) productvarariant = … -
How to use same ListView class for different model?
There are 3 models (companies, divisions and staffgroups) to display as list. I am trying to create a class base view extended from ListView to list various models through passing the model name in the URLpatterns. I had created individual class view for each model but there are essentially copy paste codes. Is there a way to streamline the code into just one class and get the model from urlpath. models.py from django.db import models ... class Company(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=100) is_active = models.BooleanField() ... class Division(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=100) is_active = models.BooleanField() ... class StaffGroup(models.Model): name = models.CharField(max_length=20) is_active = models.BooleanField() ... urls.py from django.urls import path from srrp.views import srrpIndexView, srrpListView app_name = 'srrp' urlpatterns = [ path('', srrpIndexView.as_view(), name='srrp_index'), path('<str:modelname>', srrpListView.as_view(), name='srrp_list'), ] views.py class srrpListView(ListView): template_name = 'srrp/srrplist.html' model = self.kwargs['modelname'] # I know this is wrong, this is just placeholder for the right solution paginate_by = 10 -
Got django.db.utils.IntegrityError: null value in column "currency_id" violates not-null constraint Error When i give post request from postman-DRF
I have got not null constraint error when I give post request, models.py from django.db import models from django_countries.fields import CountryField from hrm_apps.common.models import CurrencyMaster class Currency(models.Model): currency = models.OneToOneField(CurrencyMaster, on_delete=models.RESTRICT) conversion_rate = models.FloatField(null=False) def __str__(self): return str(self.id) serializers.py class CurrencySerializer(serializers.HyperlinkedModelSerializer): currency = serializers.ReadOnlyField(source='currency.name') class Meta: model = Currency fields = ["id", "currency", "conversion_rate"] class MasterSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CurrencyMaster fields = ('id', 'code', 'name') views.py class CurrencyViewSet(viewsets.ModelViewSet): queryset = Currency.objects.all() serializer_class = CurrencySerializer lookup_field = 'id' Any help Appreciated.. -
Access GCP VM via HTTPS
Hi everyone I have a GCP VM (Debian 10 image) running a Django REST API via Nginx and Gunicorn. Since I need to call the API via HTTPS I created a load-balancer with HTTPS frontend and HTTP connection to the VM on the backend. When I call the load balancer domain it connects via HTTPS to the VM. However, instead of the Django REST API, the standard NGINX message is displayed. If I call the IP of the VM directly, without the load balancer, it still displays the Django REST API. How can I access the Django REST API via the load balancer through HTTPS? Also if there are other easy-to-implement ways of accessing the VM via HTTPS without the load balancer I d be interested. Cheers -
django reference to an entire table, not to a specific entry
I'm currently working on a setting system. here i create settings for the display of different models. I'm just missing an efficient reference to the model/table. With the foregnkey you can set a reference to a specific instance, but I'm looking for a reference to an entire table. I'm currently doing it via a charfield, but find it inefficient. is there some kind of modelField? class A(models.Model): pass class B(models.Model): pass class C(models.Model): pass Classes A, B and C are any datastores for which I want to store settings. class foo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) classname = models.CharField(max_length=64) parameters of settings foo is the class in which I want to store the settings for the other classes settingsA = foo.objects.filter(user=user, classname = A.__name__) settingsB = foo.objects.filter(user=user, classname = B.__name__) settingsC = foo.objects.filter(user=user, classname = C.__name__) -
Update profile avatar DRF and Vue.js
I am not fully understanding why I can not update an image url in my DRF api. I am using djoser for the api endpoints and activation, django rest framework and vue.js for the frontend with axios making the API requests. I believe (and I may be wrong!) that I cannot make patch requests with Axios using FormData() so from googling I have found another method but Im still getting HTTP 500 error and Django error: Internal Server Error: /api/v1/users/me/ Traceback (most recent call last): File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/djoser/views.py", line 175, in me return self.partial_update(request, *args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/mixins.py", line 82, in partial_update return self.update(request, *args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/mixins.py", line 68, in update self.perform_update(serializer) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/djoser/views.py", line 149, in perform_update super().perform_update(serializer) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/mixins.py", line 78, in perform_update serializer.save() … -
Django VSCode debug raising exception for code that actually works
I have looked into similar questions, but found none exactly similar to the issue I'm facing. I am not using a virtual environment. I wanted to test debugging django project/app files in VSCode but I'm stuck with 'fake' import exceptions. Everything seems to be working as expected, but for some reason VSCode's debugger can't find my files. Here's the code snippet: from django.contrib import admin from .models import Paciente The first line doesn't raise any exceptions. The second one, though, raises this: Exception has occurred: ImportError attempted relative import with no known parent package So I put the parent folder in the path, like: from app.models import Paciente but then I get another exception: Exception has occurred: ModuleNotFoundError No module named 'app' So then, I tried removing the python path syntax, leaving just "models", as in: from models import Paciente I then get another exception, this time not in the admin file (the one I was trying to debug), but in the models file, complaining that: Exception has occurred: ImproperlyConfigured Requested setting USE_TZ, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Except it is configured in settings.py. It's there(always … -
does Django HttpResponseRedirect suffer from xss attack?
As title, because of urlpatterns are setting numeral parameter, i tend to think that HttpResponseRedirect won't suffer from xss attack, am i right? If not, how does HttpResponseRedirect suffer from it? urls.py from django.urls import path from hello import views app_name = 'hello' urlpatterns = [ path("", views.home, name="home"), # ex: /hello/5/ path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), ] views.py def detail(request, question_id): return HttpResponseRedirect(reverse('hello:results', args=(question.id,))) -
Has anyone else now got problems with Django emails?
I have a Django app which utilises the built in password reset option. This was working fine until a few days but now it doesn’t work (I now get a network error 500 error message). Has anyone else had similar problem with Django emails recently? -
Forigen Key not displaying in rendered model form
I am looking for guidance on where I am going wrong. My model form is rendering correctly however the author has no option to select or input. I suspect this is is because the author is a foreign key. How do I get around this so the form will display a list of users or allow to manually input a name. Any help would be greatly appreciated :) models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="workout_posts") updated_on = models.DateTimeField(auto_now=True) featured_image = CloudinaryField('image', default='placeholder') content = models.TextField(default='SOME STRING') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) class Meta: # ordered created on field starting with newest first ordering = ['-created_on'] def __str__(self): return self.title forms.py class MakeWorkOutForm(forms.ModelForm): class Meta: model = Post fields = '__all__' views.py def createWorkOut(request): form = MakeWorkOutForm context = {'form': form} return render(request, "add-workout.html", context) -
What's the difference between django.db.close_old_connections and django.db.connections.close_all?
I'm using Django command to do some schedule task. And before it start, I want to clear my old db connections.And it seems there're two ways to make it as below. import django django.db.close_old_connections() django.db.connections.close_all() Which one is better? Thanks -
In DJANGO, how do I query for records that do not exist after a certain date?
Assume I have a model as such: class Invoices(models.Model): customer = models.ForeignKey(Customer, ...) date = models.DateField() amount = models.FloatField() I want to know all customers that have not purchased for the last 30 days. Basically the inverse of this query: no_sales = Invoices.objects.filter( date__gte=certain_date_30_days_ago ).values( 'customer__code' ) using .exclude() just excludes the customers who have purchased in the last 30 days but not include the people who have not purchased in the last 30 days. Any thoughts? :) Thanks! -
Login, Register and Logout test failed AssertionError: 200 != 302 django
I am trying to create a test for my login, logout and register views but I keep on getting this error AssertionError: 200 != 302. Here are the codes: MODEL Here is the User model from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): full_name = models.CharField(max_length=300, null=True, blank=True) username = models.CharField(max_length=150) email = models.EmailField(unique=True) avatar = models.ImageField(upload_to='user-profile-images/', null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] VIEWS Here is the login and register function view def loginPage(request): context = {} if request.user.is_authenticated: return redirect('home') if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') try: user = User.objects.get(email=email) except: messages.error(request, 'User does not exist') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('home') return render(request,'registration/login.html', context) def registerPage(request): form = SignupForm if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() login(request, user) return redirect ('home') else: messages.error(request, 'An error occured during registration') return render(request, 'registration/register.html', {'form':form}) def logoutPage(request): logout(request) return redirect('home') URLS from django.urls import path from . import views urlpatterns = [ path('login/', views.loginPage, name='login'), path('logout/', views.logoutPage, name='logout'), path('register/', views.registerPage, name='register'), ] TEST from django.test import TestCase, Client from django.urls import reverse from mydp_app.models import User class … -
Django multiple filter in same table column
i want to get the type of enquiry and display the count for each product in that type In views.py def current(request): act=enquiry.objects.filter(type='Activity').values('product_name').distinct().annotate(Count('product_name')) wal=enquiry.objects.filter(type='Walkin').values('product_name').distinct().annotate(Count('product_name')) tele=enquiry.objects.filter(type='Tele').values('product_name').distinct().annotate(Count('product_name')) digital=enquiry.objects.filter(type='Digital').values('product_name').distinct().annotate(Count('product_name')) In models.py class product(models.Model): product_category=models.CharField(null=True,max_length=5000) product_category_id=models.CharField(null=True,max_length=5000) branch=models.CharField(default='',max_length=100) products=models.CharField(null=True,max_length=5000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return '{},{}'.format(self.products, self.product_category) class enquiry(models.Model): comment=models.CharField(default='',max_length=100,null=False) branch=models.CharField(default='',max_length=100) created_at = models.DateField(auto_now_add=True) updated_at = models.DateTimeField(default=timezone.now) created_by=models.CharField(default='',max_length=100) status=models.CharField(default='',max_length=100) commentupdate=models.CharField(default='',max_length=100) product=models.ForeignKey(product,models.CASCADE,default='') product_name=models.CharField(default='',max_length=100) product_category=models.CharField(default='',max_length=100) type=( ('Walkin','Walkin'), ('Activity','Activity'), ('TeleEnq','TeleEnq'), ('Digital','Digital'), ) type=models.CharField(choices=type, default='',max_length=100) status_type=( ('Retail','Retail'), ('Closed','Closed'), ) status_update=models.CharField(choices=status_type, default='open',max_length=100) In html {%for pr in act%} <tr> <td>{{forloop.counter}}</td> <td>{{pr.product_name}}</td> <td>{{pr.product_name__count}}</td> {%endfor%} {%for pr in wal%} <td>{{pr.product_name__count}}</td> {%endfor%} {%for pr in tele%} <td>{{pr.product_name__count}}</td> {%endfor%} {%for pr in digital%} <td>{{pr.product_name__count}}</td> {%endfor%} </tr> I want output like this: product walkin Activity Tele DIgital Total p1 4 1 3 0 8 p2 0 6 0 1 7 p3 2 1 3 0 6 p4 3 2 0 4 9 :------: :------: :-------: :----: :-------: :-----: total 9 10 6 5 30 -
Modals in Django are not showing
I am trying to add another model in django admin, called Posts. I have few other modules that are working and showing, but I don t know why this new one down not appear. Below is my code Models.py from django.db import models import datetime from django.contrib.auth.models import User STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_lenght=1048) slug = models.SlugField(max_lenght=1048) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post, Application, Message, FloaterMessage # Register your models here. admin.site.register(Post) admin.site.register(Message) admin.site.register(FloaterMessage) admin.site.register(Application) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'visionStudios', 'contact', 'crispy_forms' ] -
Django Admin panel overflows the selected model window
I have a problem in the Django admin panel. When I select any model from the list, it seems to open it "under" the main page, instead of opening a new window with it. Highlighted is what belongs to the Message model. How can I fix it? -
django ManyToMany doesn't retrieve relavant objects
I have a model as follows: class Question: text = models.TextField(_("Quiz")) votes = models.ManyToManyField( verbose_name=_("Votes"), related_name="questions", to="myapp.QuizVote", blank=True, ) def __str__(self): return self.text and another one: class QuizVote: quiz = models.ForeignKey( verbose_name=_("Quiz"), to="myapp.Question", on_delete=models.CASCADE ) vote = models.ForeignKey( verbose_name=_("QuizVote"), to="myapp.Vote", on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return "{}".format(self.vote.name) and the last one class Vote: name = models.TextField(_("Vote")) When I look into Question admin, in the field of votes I expect to see just those QuizVote records which have the same id as each specific Question. However each Question objects shows all available records in QuizVote without filtering based on ids. I tried to add this method to Question model this but doesn't work: @receiver(m2m_changed, sender=Question.votes.through) def retrieve_quiz_vote(sender, instance, action, **kwargs): if action == "post_add": instance._get_relavant_votes() in Question model added thid then: def _get_relavant_votes(self) -> None: if isinstance(instance, Question) \ and hasattr(instance.__class__, 'objects'): relevant_votes = instance.__class__.objects.filter( votes__name__in=instance.votes.all() ).distinct() return relevant_votes