Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django full text search with PostgreSQL, across multiple different models
I need to perform FTS across multiple different models. I want to get any model type in search result. I would like to sort results by rank, to get most relevant result. I can run search one by one, but not sure how can I combine results, especially preserving rank relevancy. Here are models, its an example from Making queries manual page. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() -
Edit Django files on Heroku without editing my database files
I wanna make some changes to my Django site running on Heroku, how can i upload my new changes with git push without touching my database, so i don't loose any data? -
How can I generate a dynamic shorturl with expiring time?
I have a python code with django that make shorturl with hash decoder, but it cannot generate dynamic code for especial full url. In fact i want to generate shorturl codes with expiring time so that when its time expired, i woud be able to generate new shorturl for my full url. Thanks you for your answers! model.py class URL(models.Model): full_url = models.URLField(unique=True) short_url = models.URLField(unique=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.id: self.short_url = md5(self.full_url.encode()).hexdigest()[:8] validate = URLValidator() try: validate(self.full_url) except ValidationError as e: raise GraphQLError('invalid url') return super().save(*args, **kwargs) -
Django Nginx Gunicorn Upstream Premature closed connection while reading response
nginx conf server { listen 80; server_name private.com; client_max_body_size 4G; client_body_buffer_size 8000M; client_body_timeout 120; proxy_connect_timeout 900s; proxy_read_timeout 900s; location = /favicon.ico { access_log off; log_not_found off; } autoindex on; location / { include proxy_params; proxy_pass http://unix:/home/dm/stat.cok; } } gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=Pa Group=www-data WorkingDirectory=/home/un/foldername ExecStart=/home/un/foldername/bin/gunicorn \ --access-logfile - \ --workers 3 \ --timeout 450 \ --bind unix:/home/dm/stat.sock scistat.wsgi:application [Install] WantedBy=multi-user.target I upload a large excel file 90mb size, It contains 450000+ rows and 6 columns. After the file upload, It calculate the row and columnf of excel file the multiply it to compute the total row and column of excel file, but this error show "upstream prematurely closed connection while reading response header from upstream" -
Django 3.0 App is not a registered namespace
I have the app_name as basicapp in the urls.py folder of my app but still when django says basicapp is not a registered namespace. here is my urls.py of basicapp from django.urls import path from basicapp import views from django.urls import include #template tagging app_label = 'basicapp' urlpatterns = [ path('relative/',views.relative,name='relative'), path('other/',views.other,name='other'), ] template file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Welcome to relative url</h1> <a href="{% url 'basicapp:other' %}"></a> </body> </html> Please let me know how to fix this mistake. -
Django channel not getting message
I am using django channel in my current project. From one of my django app, I am sending notification to the channel layer, so that websocket can broadcast the message. But problem is consumer is not getting my message. Utils in django app for sending notification to channel: from asgiref.sync import AsyncToSync from channels.layers import get_channel_layer import json def async_send(group_name, text): channel_layer = get_channel_layer() AsyncToSync(channel_layer.group_send)( group_name, { 'type': 'notify', 'text': json.dumps(text) } ) My consumer file is: from channels.generic.websocket import AsyncWebsocketConsumer class InformationConsumer(AsyncWebsocketConsumer): async def connect(self): self.channel_layer.group_add(str(self.scope['user']), self.channel_name) await self.accept() async def notify(self, event): await self.send_json( { "message": event['text'], }, ) print(event['text']) I am supposed to get the output of event['text'], but getting nothing :( -
ERROR 2026 - SSL connection error - Ubuntu 20.04
I've recently upgraded my local machine OS from Ubuntu 18.04 to 20.04, I'm running my MySQL-server on CentOS (AWS). Post upgrade whenever I'm trying to connect to MySQL server it is throwing SSL connection error. $ mysql -u yamcha -h database.yourproject.com -p --port 3309 ERROR 2026 (HY000): SSL connection error: error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol But if I pass --ssl-mode=disabled option along with it, I'm able to connect remotely. $ mysql -u yamcha -h database.yourproject.com -p --port 3309 --ssl-mode=disabled Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 22158946 Server version: 5.7.26 MySQL Community Server (GPL) Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> Queries: How to connect without passing --ssl-mode=disabled How to pass this --ssl-mode=disabled option in my Django application, currently I've defined it as shown below, but I'm still getting the same error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'yamcha', 'USER': 'yamcha', 'PASSWORD': 'xxxxxxxxxxxxxxx', 'HOST': 'database.yourproject.com', 'PORT': '3309', 'OPTIONS': {'ssl': False}, } -
how can I properly validate lesson modules per user rights?
I want to validate if my lesson material belongs to a xyz user with pro rights and each lesson has matched properly with the rights but if not it will display become a member , but however if I change the allowed_memberships id to pro only it doesnt work as expected it always goes to become member class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user.email id,stripe_customer_id,membership_id,user_id "1" "xxxxxx" "1" "63ce34cb8fe647a9bb1d28f61918e1bf" "3" "xxxxxx" "2" "c133546e6ed846c48a3938ccca8ffcbb" class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) def __str__(self): return self.membership_type id,membership_type,price,stripe_plan_id "1" "1" "Free" "0" "xxxxxxx" "2" "2" "Professional" "40" "xxxxxxx" class Lesson(models.Model): allowed_memberships = models.ManyToManyField(Membership) id,lesson_id,membership_id "1" "1" "1" "2" "2" "1" "3" "3" "1" "4" "4" "1" "5" "5" "1" "11" "6" "1" "64" "7" "2" views def get(self, request): template = loader.get_template(self.template_name) template_member = loader.get_template(self.template_payment) if UserMembership.objects.filter(user=request.user,membership_id=2).exists(): return HttpResponse(template.render()) else: return HttpResponse(template_member.render()) -
Getting one to many result
I am doing some trial and error in my django query. I'm trying to get a field with one column value beside it contains lists of elements. Basically I'm trying to figure out how to attain this result: { feed: {}, [{ id: 1, media_id: 11 }, { id: 2, media_id: 22 }] } I tried in python shell this query and it gave me this result: >>> query = Feed.objects.filter(Q(feedmedia__isnull=True)|Q(feedmedia__isnull=False)).values('message','feedmedia__id','feedmedia__media_id').distinct() >>> print(query) <FeedQuerySet [{'message': 'Classic motorcycles <3', 'feedmedia__id': 145, 'feedmedia__media_id': 152}, {'message': 'sample video', 'feedmedia__id': 147, 'feedmedia__media_id': 153}, {'message': 'Classic motorcycles <3', 'feedmedia__id': 146, 'feedmedia__media_id': 151}]> On the result I understand why the 'message' (one of the field in Feed table) is included, and the problem is that I don't know how I'm going to exclude it in order to get the desired output. These are the three models involved on this operation: class Media(models.Model): original_url = models.CharField(max_length=200, null=False, unique=False) small_url = models.CharField(max_length=200, null=True, unique=False) medium_url = models.CharField(max_length=200, null=True, unique=False) large_url = models.CharField(max_length=200, null=True, unique=False) uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "media" class Feed(models.Model): message = models.CharField(max_length=3000, null=True, unique=False) type = models.CharField(max_length=50, null=False, unique=False) category = models.CharField(max_length=50, null=False, unique=False) priority_level = models.IntegerField(default=0, null=False, unique=False) origin_location = models.CharField(max_length=100, null=True, … -
in Django, can I use a class only to group functions?
I am creating an application using Django. The application has user registration and login functionality. I have three functions related to user authentication as of now, login, registration, and email_check (which is called when the user types email address to see if it is available). I was trying to group these functions under a class for better organisation and easy accessibility. So I wrote a class and function like so: class user_auth: def check_email(email): with connection.cursor() as conn: conn.execute('select count(*) from user_info where email = %s', [email]) row = conn.fetchall() response = bool(row[0][0]) return(response) However, when I do this, I get a pylint error saying Method should have "self" as the first argument. If I save this and call it as user_auth.check_email('abc@xyz.com'), it works just fine. But if I add self as the first argument, it stops working. Am I using classes in an incorrect way? If yes, what is a better way to create a group of functions like this which can be easily imported using a single statement in other files? -
i am unable to list all data at once,is there any method like join or i need to use query method ...thank you in advance
models.py class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) def __str__(self): return self.first_name class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE, related_name='album_musician', null=True, blank=True) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() def __str__(self): return self.name serializer.py class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album # fields = ('id', 'artist', 'name', 'release_date', 'num_stars') fields = '__all__' class MusicianSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) instrument = serializers.CharField(max_length=30) album_musician = AlbumSerializer(many=True) def create(self, validated_data): albums_data = validated_data.pop('album_musician') musician = Musician.objects.create(**validated_data) for album_data in albums_data: Album.objects.create(artist=musician, **album_data) return musician def update(self, instance, validated_data): albums_data = validated_data.pop('album_musician') albums = (instance.album_musician).all() albums = list(albums) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.instrument = validated_data.get('instrument', instance.instrument) instance.save() for album_data in albums_data: album = albums.pop(0) album.name = album_data.get('name', album.name) album.release_date = album_data.get('release_date', album.release_date) album.num_stars = album_data.get('num_stars', album.num_stars) album.save() return instance views.py class MusicianView(generics.RetrieveUpdateDestroyAPIView): serializer_class = MusicianSerializer queryset = Musician.objects.all() -
Django CreateView Model Form not uploading File
the problem that I have is that my Model Form is not uploading a file, I had it working and after adding more code now is not working. It uploads all the other fields except for the file, the strange thing is that if I do it from the admin site it does work. models.py class Polizas(models.Model): nombre = models.CharField(max_length=30, blank=True, null=True) numero = models.CharField(max_length=30, unique=True) aseguradora = models.CharField(max_length=20, blank=True, null=True) carro = models.ForeignKey( Carros, on_delete=models.CASCADE, blank=True, null=True) inicio_poliza = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) fin_poliza = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) documento = models.FileField(upload_to='polizas/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Polizas" ordering = ['nombre'] def __str__(self): return self.nombre def get_absolute_url(self): return reverse('polizas') forms.py class PostPolizas(forms.ModelForm): class Meta: model = Polizas fields = ('nombre', 'numero', 'aseguradora', 'carro', 'inicio_poliza', 'fin_poliza', 'documento') widgets = {'inicio_poliza': forms.DateInput(attrs={'type': 'date'}), 'fin_poliza': forms.DateInput(attrs={'type': 'date'}) } views.py class PolizaCreate(LoginRequiredMixin, CreateView): login_url = '/login/' redirect_field_name = 'redirect_to' form_class = PostPolizas template_name = "add_insurance.html" Terminal [06/May/2020 22:32:17] "POST /insurance/add/ HTTP/1.1" 200 4557 [06/May/2020 22:32:25] "POST /insurance/add/ HTTP/1.1" 302 0 I have tried to validate the form and it is not working, this is error is happening in my other model forms that upload … -
django local variable 't' referenced before assignment
I saw this was a common error and I did look through other post, but they did not help me. I am getting the error Exception Value: local variable 't' referenced before assignment But my t variable is declared 3 lines above where it is saying it is not, inside my if validation. Scope should be fine for my return. function in question: def create(response): #response.user if response.method == "POST": form = CreateNewTrade(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = AssetList(name=n) t.save() response.user.assetlist.add(t) return HttpResponseRedirect("/userdash/%i" %t.id) #we fail at this t variable complete code: $ cat userdash/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import AssetList, Items from .forms import CreateNewTrade # Create your views here. #def index(response): # return HttpResponse("<h1>Hello Dark World!</h1>") def userdash(response, id): ls = AssetList.objects.get(id=id) if response.method == "POST": print(response.POST) if response.POST.get("save"): for item in ls.items_set.all(): if response.POST.get("c" + str(item.id)) == "clicked": item.sell_asset = True else: item.sell_asset = False item.save() elif response.POST.get("newItem"): txt = response.POST.get("new") if len(txt) > 2: #this validation is retarded and needs to be fixed ls.items_set.create(user_asset=txt, sell_asset=False) else: print("invalid") #items = ls.items_set.get(id=1) #return HttpResponse("<h1>User Dashboard!</h1><h2>%s</h2><br></br><p>%s</p>" %(ls.name, str(items.user_asset))) return render(response, "userdash/list.html", {"ls":ls}) def home(response): #pass return render(response, "userdash/home.html", {}) def … -
How to add data in table dynamically in django?
I have following two models in my models.py. class Book(models.Model): book_id = models.AutoField book_name = models.CharField(max_length=50) book_author = models.CharField(max_length=50) book_category = models.CharField(max_length=50) class Author(models.Model): author_id = models.AutoField author_name = models.CharField(max_length=50) author_description = models.CharField(max_length=500) So whenever I add new row in Book table, it automatically do entry in Author table ( Only author_id and author_name, author_description i will add manually ). How to do it? -
Django Rest Framework API POST receiving status code 200 instead 201
I am new to Django and python. I have a website that already in production using docker. And the API URL is on: http://gmlews.com/api/data. When I want to test the API using postman, the GET method working fine, but for the POST method is returned response 200 OK not 201 created. Because of that, my data can't be saved in the API. Here is my code for the API : restapi/serializers.py: from .models import Data,Node from rest_framework import serializers class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' class NodeSerializer(serializers.ModelSerializer): class Meta : model = Node fields = '__all__' restapi/views.py: import json from django.views.generic import View from django.shortcuts import render from rest_framework import routers, serializers, viewsets from rest_framework.response import Response from restapi.serializers import DataSerializer, NodeSerializer from restapi.models import Data, Node from django_filters.rest_framework import DjangoFilterBackend from django.http import HttpResponse from rest_framework.views import APIView # Create your views here. class DataViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class = DataSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['node_id'] class MapViewSet(viewsets.ModelViewSet): queryset = Data.objects.filter(node_id=1).order_by('-id')[:1] serializer_class = DataSerializer class NodeViewSet(viewsets.ModelViewSet): queryset = Node.objects.all() serializer_class = NodeSerializer Can someone help me with this issue? I really don't have an idea why the POST method received status 200. I want … -
I want to show some news in my index page
I am working in a Django project in which a user would need to create an account and register to get some functionality of the web app, so for each user when they log in i would like to show some news of the day or something like so, i would like to know which way would you recommend to use, web scrapping or use any API like cnn or something related to news? Or if there is a better way to do this task which one would you recommend? -
NoReverseMatch at / Reverse for 'article' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<article_id>[0-9]+)$']
for some reason I cannot seem to solve this bug. I am using Django 3.0.5 The actual error I get is NoReverseMatch at / Reverse for 'article' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<article_id>[0-9]+)$'] In my project dir I have this urls.py from django.urls import path from . import views urlpatterns = [ path('', views.presse, name='listings'), path('<int:article_id>', views.article, name='article'), ] My view looks like this def article(request, article_id): article = get_object_or_404(Article, pk=article_id) context = { 'article': article } return render(request, 'article/article.html', context) and my html is <h4 class="uk-margin-small-bottom"><a href="{% url 'article' article.id %}"> -
What is the most efficient way to store images feature vector?
I'm working on project that needs to deal with images, I extract their feature vector instantly when any image uploaded then I store the feature vectors in MySQL database as text per each image. Also I'm using django framework. def search_images_by_features(query_image: ImageFieldFile, images): featured_images = [ (calculate_similarity(load_features_from_str(image.features), get_image_feature(query_image)), image.item) for image in images if image.features is not None] ... But looping on each image isn't a big deal as it takes more time as images increase. Also my feature vector in database stored like that: 0.0010601664,0.0003533888,0.8969008,0.0014135552,... Also is there a way to make MySQL database engine calculate similarity from feature vectors? -
DJANGO : How can i use fieldsets in forms.py
How can i use fieldsets in form.py i need to use like this in forms.py fieldsets = [ ( '', { 'fields': ['paysPartenaires', 'instrumentJuridique',('partenaire','gouvernement','paysP','etat','adefinir'),'objet', 'axeCooperation'] }), ('Autres élements à rajouter ?', { 'fields': ['infoPlus', ] }), ('', { 'fields': [ 'acteJuridique',('dateSignature','dateEntreeVigueur' ),('duree','dureeplus5ans', 'renouvellement'), ('pays', 'villeSignature')] }), ('Base Documentaire', { 'fields': [], 'description': 'Joindre le(s) fichier(s) '}), ] ``` -
Why is the "on_update" option not present in Django Relationship fields?
I'm using Django 3.0 + MariaDB. I've created a models.py from an existent database with the "python manage.py inspectdb > models.py" command. I need now to set the options for the Foreign Keys. As you know in a database you can have multiple options for the Foreign Keys: the first classic is "ON_DELETE" and the second is 'ON_UPDATE' (You can even have more options in PostgreSQL). In Django, there is just an "on_delete", but no "on_update" option, what I found very surprising. I found nothing on the official documentation about this. Neither on some old posts with the same question, the responses were not conclusive and focused on the "on_delete". I'm asking about the "ON_UPDATE' option, nothing else. So, where is this option, or why is it not present in Django's ORM ? -
moving Django Project from windows to Mac migration
I moved my project from my windows machine to Mac using GitHub when I run python manage.py runserver it worked fine showing my login page and since I didn't do any migration the app crashed, so I executed python manage.py makemigrations I thought this will solve the problem but after that when I am trying to runserver I am getting the dejango home page also all my clasess are Undefined undefined class issue Django Home Page and my database which is postgresql not showing any of my models in the table and make migrations showing below error every time after that and ython manage.py migrate showing below Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. No changes detected setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'xadmin', 'django_filters', 'crispy_forms', ] database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'crashDB', 'USER': 'postgres' , 'PASSWORD': '1234', 'HOST': 'localhost', } } what is the issue in here ?? and what is the best way to move my project from windows to Mac ? -
Django DateTimeField Doesn't Translate Time While Saving To Db
I have a Django model named "Event". class Event(models.Model): screen_name=models.CharField(max_length=256) description=models.TextField(max_length=512) date_time=models.DateTimeField() Everyhing looks nice, and I see the datetime picker on the Admin interface. My settings.py has the following: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True My question is: My browser time is 2 hours ahead of the server time. When I pick a date and time (e.g 05:00:00), it is saved in the Db as 05:00:00. The Db record does not keep record of the timezone. As far as I know, Django considers DB records as UTC strings. I want it to be translated from my timezone (GMT +2) to (UTC) before saving it to the Db. (e.g 03:00:00) What am I doing wrong? I would be glad if you help me solve this. Thanks! -
Login Authentication - Django
I am having a really hard time trying to understand the following: I am new to web development and i use django for my project, i already added the @login_required decorator to the views that need an authenticated user to show up, everyhting works fine until there, but when i hit the logout button which redirects me to the index page of the webapp and i hit the back arrow of the navigator again, everything that must need to show up only if there is a user authenticated shows up again, i don't think that is the correct behavior of django or what am i doing wrong? Is there any other decorator or function call i must do so that this doesnt happen anymore? -
Django Select2 not working on all fields in form
MODEL class VeriEnvanteri(models.Model): Departman = models.ForeignKey(Departman, on_delete=models.CASCADE,verbose_name="Departman") Faaliyet = models.ForeignKey(Faaliyet, on_delete=models.CASCADE,verbose_name="Faaliyet") VeriKategorileri = models.ForeignKey(VeriKategorileri, on_delete=models.CASCADE,verbose_name="Veri Kategorileri") KisiselVeri = models.ForeignKey(KisiselVeri,null=True,blank=True, on_delete=models.CASCADE,verbose_name="Kişisel Veri") OKisiselVeri = models.ForeignKey(OKisiselVeri, null=True,blank=True,on_delete=models.CASCADE,verbose_name="Özel Nitelikli Kişisel Veri") VeriIslemeAmaci = models.ForeignKey(VeriIslemeAmaci, on_delete=models.CASCADE,verbose_name="Veri İşleme Amacı") VeriKonusuKisiGruplari = models.ForeignKey(VeriKonusuKisiGruplari, on_delete=models.CASCADE,verbose_name="Veri Konusu Kişi Grupları") HukukiSebebi = models.ForeignKey(HukukiSebebi, on_delete=models.CASCADE,verbose_name="Hukuki Sebebi") VeriSaklamaSuresi = models.ForeignKey(VeriSaklamaSuresi, on_delete=models.CASCADE,verbose_name="Veri Saklama Süresi") Deger = models.CharField(max_length=1000,verbose_name="Değer", default='') VeriAktarimAlicilari = models.ForeignKey(VeriAktarimAlicilari, on_delete=models.CASCADE,verbose_name="Veri Aktarım Alıcı Grupları") YabanciUlke = models.ForeignKey(YabanciUlke, on_delete=models.CASCADE,verbose_name="Yabancı Ülkelere Aktarılma Durumu") IdariTedbirler = models.ForeignKey(IdariTedbirler, on_delete=models.CASCADE,verbose_name="Idari Tedbirler") TeknikTedbirler = models.ForeignKey(TeknikTedbirler, on_delete=models.CASCADE,verbose_name="Teknik Tedbirler") Kurum = models.ForeignKey(KurumBilgileri, on_delete=models.CASCADE,verbose_name="Kurum Adı",default=1) IslemTarihi = models.DateTimeField(auto_now_add=True,verbose_name="İşlem Tarihi") FORM class VeriEnvanterForm(forms.ModelForm): class Meta: model = VeriEnvanteri fields = ['Departman','Faaliyet','VeriKategorileri','KisiselVeri','OKisiselVeri','VeriIslemeAmaci','VeriKonusuKisiGruplari','HukukiSebebi','VeriSaklamaSuresi','Deger', 'VeriAktarimAlicilari','YabanciUlke','IdariTedbirler','TeknikTedbirler'] widgets = { 'Departman' : s2forms.Select2Widget , 'Faaliyet' : s2forms.Select2Widget , 'VeriKategorileri' : s2forms.Select2Widget , 'KisiselVeri' : s2forms.Select2Widget , 'OKisiselVeri' : s2forms.Select2Widget , 'VeriIslemeAmaci' : s2forms.Select2Widget , 'VeriKonusuKisiGruplari' : s2forms.Select2Widget , 'HukukiSebebi' : s2forms.Select2Widget , 'VeriAktarimAlicilari' : s2forms.Select2Widget , 'IdariTedbirler' : s2forms.Select2Widget , 'TeknikTedbirler' : s2forms.Select2Widget } Select2 widget only work for KisiselVeri and OKisiselVeri. I cant figure out. -
Writing an efficient node.all_siblings_leaf() method for django-mptt
I have a tagging system, where the tags exist in a hierarchy. I've used django-mptt to build the Tag model. I want to display a group of tags differently if every sibling in the group is a leaf node. To do this, I want a model method called all_siblings_leaf(). Here's my first take on that method: def all_siblings_leaf(self): """Return True if all siblings, including self, are leaf nodes.""" siblings = self.get_siblings() return all([sibling.is_leaf_node() for sibling in siblings]) This works, but it's one trip to the db for the get_siblings() call. When I want to call all_siblings_leaf(), I've already queried for all the tags I want to use. Using this method repeatedly with a set of several hundred tags means several hundred new db calls. Since I already have all the tags, I feel like I should be able to get the information about leaf nodes without any additional trips to the db. Here's what I've come up with: def all_siblings_leaf(self, all_tags): """Return True if all siblings including self are leaf nodes. all_tags should be a queryset that used select_related('parent') """ if self.level == 0: siblings = [t for t in all_tags if t.level == 0] else: siblings = [t for …