Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python + Trying to reduce I/O operation to store Data in Table
Sample Data: sales_counts = [ { "sale_id": 1001 }, { "sale_id": 1002 }, { "sale_id": 1001 }, .... ] for sale in sales_counts: Order.objects.get_or_create(sales_number=sale['sale_id'], sale_type='online') For a Small Number of SalesCount, it is fine to have one by one iteration. But for a large number of sales counts, performance will be too bad and time-consuming. In the above example: sale_id would differ and the rest of the column will be the same. How can we reduce the number of iteration and data storing calls to DB. -
In Django How to set up dependent dropdown lists
I am attempting to set up dependent dropdown lists in a Django 3.1 site. The lists are populated via another app (Django-Machina) DB tables. I attempted to adapt the example here. However I am new to Django and Python and so far, I am not able to get this to work. My files are as follows: models.py from django.contrib.auth.models import AbstractUser from django.db import models from machina.core.db.models import get_model from django.db.models import Q Forum = get_model("forum", "Forum") class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) business_location_state = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft":1}) business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2)))) views.py from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm from .models import CustomUser from django.shortcuts import render from machina.core.db.models import get_model from django.db.models import Q Forum = get_model("forum", "Forum") class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def load_counties(request): parent_id = request.GET.get('business_location_state') counties = Forum.objects.filter(parent_id=parent_id).order_by('name') return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties}) accounts/urls.py # accounts/urls.py from django.urls import path from .views import SignUpView from . import views urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('ajax/load-counties/', views.load_counties, name='ajax_load_counties'), # ajax to load counties ] forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class … -
Filter two related models in django-filter with output in template file
I have two models in my django app that are related. models.py class security_incident(models.Model): asset = models.CharField(max_length=200) # security_incident has one asset actor = models.CharField(max_length=200) #security_incident has one actor action = models.CharField(max_length=200) # one action can have several attacks attributes = models.CharField(max_length=9, choices=CIA_CATEGORIES, default=C) # up to two attributes def __str__(self): return self.asset class attack(models.Model): action = models.ForeignKey(security_incident, on_delete=models.CASCADE) # one action can have several attacks attack_name = models.CharField(max_length=200) defense_mechanism = models.CharField(max_length=200) # attack_name can only have one defense_mechanism def __str__(self): return self.attack_name I am trying to filter these models with this django-filter: filters.py class SecIncFilter(django_filters.FilterSet): asset = django_filters.CharFilter(lookup_expr='icontains', distinct=True, label='Search for security incidents, related attacks and defense mechanisms to an asset') attributes = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple(), choices=CIA_CATEGORIES, label='Choose categories') class Meta: model = security_incident fields = ['asset','attributes'] def __init__(self, *args, **kwargs): super(SecIncFilter, self).__init__(*args, **kwargs) # at sturtup user doen't push Submit button, and QueryDict (in data) is empty if self.data == {}: self.queryset = self.queryset.none() This is then beeing rendered after clicking search into this template: generate_tree.html <div class="row"> <div class="card card-body"> <div class="col-md-12"> <h5>Search for related security incidents</h5> <form method="get"> <div class="well"> <div class="form-group col-sm-8 col-md-6"> {{ filter.form.asset.label_tag }} {% render_field filter.form.asset class="form-control" %} </div> <div class="form-group col-sm-8 col-md-12"> {{ … -
Cowardly refusing to install hooks with `core.hooksPath` set
i tried to run this command but it always show this error, i can't fix it with anyway. Help me, please! (venv)<...>pre-commit install [ERROR] Cowardly refusing to install hooks with core.hooksPath set. hint: git config --unset-all core.hooksPath -
Can Django admin url be on a swagger file using drf-yasg?
I am deploying a Django API on Google Endpoint. Google endpoint needs a documentatin generated with openapi2.0 to set all endpoint. If an url is not defined on the yaml file generated by openapi (here by drf-yasg) the endpoint can not be reached even if it is available. Thing is, it would be very very very useful for me to access my django admin zone on my api but when I generate my yaml file it skips my admin url. here is my url, basic: urlpatterns = [ # back path('', include('api.urls')), path('', include(spectacular_url)), path('admin/', admin.site.urls), ] Do you know how to do this ? Thanks -
Using Prefetch related on so many nested foreign keys for performance
I am trying to reduce the queries count from 14 to more less for a Custom Manager model. Initially I set the manager function like: def for_display(self): return self.select_related("customer",).prefetch_related( "lines", Prefetch( "lines__pooja_slot", queryset=TemplePoojaSlots.objects.select_related( "pooja", ).prefetch_related( Prefetch( "pooja", queryset=TemplePooja.objects.select_related( "pooja", ).prefetch_related( Prefetch( "deity", queryset=TemplePooja.objects.select_related( "deity", ), ), ), ), ), ), Prefetch("lines__user_profile"), Prefetch( "lines__temple", queryset=Temple.objects.select_related(), ), Prefetch( "lines__donation", queryset=DonationOrder.objects.select_related("donation_event"), ), ) This one had 14 queries running. I was able to reduce the number to 9 by doing so: def for_display(self): return self.select_related("customer",).prefetch_related( Prefetch( "lines", queryset=CheckoutLine.objects.select_related( "user_profile", "temple", "donation", "donation__donation_event", "pooja_slot__pooja", "pooja_slot__pooja__pooja", "pooja_slot__pooja__deity__deity", ), ) ) Is there any issue on going through multiple foreign keys like "pooja_slot__pooja__deity__deity" on the select related? Also, I see a N+1 query issue still on this. This is for displaying a cart item. When I add items one by one to cart, the query gets increased by 2 more for each. What should I do to control that ? -
Unable to lunch json file on index.html
views.py from django.shortcuts import render from django.http import HttpResponse import json booksData = open( r'C:\Users\Dhiraj Subedi\Desktop\pool1\books.json').read() data = json.loads(booksData) def index(request): context = {'books': data} return render(request, 'books\index.html', context) index.html <html> <head> <title></title> </head> <body> {% for book in books %} <p>{{book.title }} </p> <img src="{{book.url}}" width="200px"> {% endfor %} </body> </html> I am not able to lunch a JSON data on the index.html file and the image is not shown but its icon is seen and Books text is display there is no any Book text -
Can I make a class based view with 2 serializer classes DjangoREST
So while working on a recent project I found that I needed to query the database through 2 models, basically I need to know if it is possible to have 2 serializer_classes in my view (fyi I kinda need to use class based views only). Can anyone tell me how to do that? -
How to generate .exe file from django web?
Can anyone tell me how to generate .exe from the django project ? I tried pyinstaller and py2exe but im not able to get proper working exe .Does anyone know how to do that,I'm stuck there from past few days.Help me guyz. -
TypeError: NoneType object is not callable on GeoDjango
Although I have read many similar articles about PointField and 'NoneType' object error, I can't figure out how this field should be automatically save according to the latitude and longitude variables I received from the user. Here is my model: from django.db import models from django.contrib.gis.db import models from django.contrib.gis.geos import Point class Firm(models.Model): FirmName = models.CharField(max_length=50) address = models.CharField(max_length=1000, null=True, blank=True) FirmAddress = models.PointField(null=True, blank = True, geography=True, default=Point(0.0, 0.0)) lat = models.FloatField(null=True, blank=True) lng = models.FloatField(null=True, blank=True) Logo = models.ImageField(null=True, blank=True) @property def save(self, *args, **kwargs): self.FirmAddress = Point(self.lng, self.lat) super(Firm, self).save(*args, **kwargs) On the Django shell, I type from firm.models import Firm command first and then Firm.objects.create(FirmName="QWERTY", address="temp", lat=24, lng=54, Logo='logo.jpg') command. Here is the error I got at the end: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Deniz\Desktop\PROJECT\fenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Deniz\Desktop\PROJECT\fenv\lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) TypeError: 'NoneType' object is not callable But when I look at my database, I see that a value of type geography-point has been added to the FirmAddress column. When I remove the FirmAddress feature and update the model, I don't get any errors and everything works fine. … -
Check if a user is in a group to post something Django
I'm trying to verify if a user is in a group and only if he is in that group he can post something in it, otherwise he will be redirected. I am pretty new to Django, I'm trying to add some more lines and ideas in order to further develop a site on my own. This is my code: models.py from django.db import models from django.urls import reverse from django.conf import settings from groups.models import Group from misaka import html from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username, 'pk':self.pk}) class Meta(): ordering = ['-created_at'] unique_together = ['user','message'] views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views import generic from django.http import Http404 from django.contrib import messages from groups.models import Group,GroupMember from braces.views import SelectRelatedMixin from django.http import HttpResponseRedirect from django.urls import reverse from posts.models import Post from . import models from . import forms from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() @register.filter def has_group(user, group): return user.groups.filter(name=group).exists() … -
[Microsoft][ODBC Driver 17 for SQL Server]SSPI Provider: No Kerberos credentials available
I have developed Django app and connecting remote sql server from Django app. If I run it in anaconda environment its running fine, but if I build docker container it gives me error sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('HY000', '[HY000] [Microsoft][ODBC Driver 17 for SQL Server]SSPI Provider: No Kerberos credentials available (default cache: FILE:/tmp/krb5cc_0) (851968) (SQLDriverConnect)') (Background on this error at: http://sqlalche.me/e/dbapi) Here is Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN apt-get update \ && apt-get -y install gcc gnupg2 \ && curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \ && curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list RUN apt-get update \ && ACCEPT_EULA=Y apt-get -y install msodbcsql17 \ && ACCEPT_EULA=Y apt-get -y install mssql-tools RUN apt-get -y install unixodbc-dev \ && apt-get -y install python-pip \ && pip install pyodbc RUN pip install --upgrade pip RUN pip install Django RUN pip install python-dotenv RUN pip install --user django-crispy-forms RUN pip install pandas RUN pip install SQLAlchemy RUN pip install django-pyodbc-azure-2019 COPY . /app Here is the connection engine = create_engine('mssql+pyodbc://' + 'SQLserver' + '/' + 'database' + "?" + 'driver=ODBC Driver 17 for SQL Server') -
Incorporating Python and Django On GoDaddy
I've developed a small network of web pages with Python and Django. I can see them on my computer. But when I try to upload them to GoDaddy, I discover that their file structuring is way different to that of Django. For example, GoDaddy is expecting an index.html or a home.html in their root folder, but in Django, such a page is several subfolders deep, underneath your project folder and then your app folder, and then the templates folder, and finally the name of your app underneath the templates folder. So is Django incompatible with GoDaddy? If not, how do incorporate this file format into GoDaddy, so ultimately, I can see my web pages there? Anyone who has successfully incorporated a Django website on GoDaddy, I'd love to hear from you. Thanks. -
How to send a push notification to specific user in Django?
I’m using django as my backend and I want to use firestore for webRTC audio call. So that I need to send a notification to the user to answer the call. How can send the notification to the specific user using Django and I also haven’t made any authentication with firebase then how can I send a FCM to a specific user? -
please am new in django, what can i do to avoid repetition of the same query in different templates
1.This is my Home list view def get_context_data(self,*args,**kwargs): categories = Post.objects.values('category').annotate( posts_count = Count('category')) likes = Post.objects.values('likes').annotate(count_like=Count('likes')) display_menu = Category.objects.all() context = super( HomeListView , self).get_context_data(**kwargs) context ['categories'] = categories context ['display_menu'] = display_menu context ['likes'] = likes return context -
How to use self-signed and LetsEncrypt Certbot SSL certificates together in nginx?
I am hosting a django website on digital ocean. I have wish to access my website's IP using https with self-signed cert as Let's Encrypt does not provide certificates for public IP addresses. I followed this guide and wrote an nginx server block. I can access https://example-ip-address with: server { listen 443 ssl; listen [::]:443 ssl; include /etc/nginx/snippets/self-signed.conf; include /etc/nginx/snippets/ssl-params.conf; server_name 123.123.12.123; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/djangotemplates; } location / { include /etc/nginx/proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } server { listen 80; listen [::]:80; server_name 123.123.12.123; return 301 https://$server_name$request_uri; } And, I can access https://example.com and https://www.example.com with let's encrypt SSL cert by following this and this is the server block I wrote: server { server_name www.example.com example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/djangotemplates; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.com) … -
Django Foreign Key limit_choice_to with model object filter
I'm trying to limit the choices for a foreign key in my django admin tool. I stumbled across the limit_choices_to option for the ForeignKey model: https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to In my models, I have a Question_logic that has an attribute ifLogic which is a foreign key of the model Options (which represent the possible answers of options of a question). # Models.py class Options(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) option = models.CharField(max_length=200) class Question_logic(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) # error here: ifLogic = models.ForeignKey(Options, on_delete=models.CASCADE, limit_choices_to=Options.objects.filter(question=question)) thenLogic = models.CharField(max_length=200) However this approach does not work because apparently you can't reference an object in the model definition itself and I'm getting this error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. My logic is quite straightforward: I want the admin to chose only between the options that are relevant for the specific question. How do I implement this correctly? Thanks. -
500 Internal Server Error for some but not others
My site, https://hendrixia.com, gives an 500 Internal Server error for some users but not others. I have someone helping me debug, but without fruition. He is getting 500 internal server errors on his personal computer and at one of his webservers. I am able to load the site fine. We have no clue what is wrong. Obviously I'm not going to turn debugging on on a live site. But we are running out of options. Can anyone help? Site is built with python/django. postgresql db. hosted at heroku -
Other computers under same network cant access my django development server?
Steps taken: added in allowed_hosts ALLOWED_HOSTS = ["192.168.0.149"] cmd : python3 manage.py runserver 192.168.0.149:8000 Firewall not enabled in my mac I am getting ERR_CONECTION_TIMED_OUT This site cant be reached. both the computers are under same network. -
How do I make the Django form's choices elements dynamic?
I need to make a Django form containing two fields: region and city. Both fields contain options from the drop-down list. The city field should only be available after selecting region, and the options for the city field should depend on the previously selected region. Can this be done without resorting to js? -
How Can I store reviews from google to my database automatically in predefined timeframe?
I am pretty new to programming and I am thinking of how can I fetch the data from the google review API automatically in predefined time (twice daily) and store it in the django backend database ? I know I can fetch data using request package but everytime I fetch data it gives me all the data even that which was stored in the database in the earlier fetch. -
How to open multiple browser in one view using WordPress or Django?
I want to open multiple browser in one-page view. Please see the picture for better understanding my question. My willing page view -
Optimising DRF Serialization
I am facing a problem where I have to optimise the serialization of the ORM object. I have an object say Foo for which I have a huge serializer. I have mentioned a lot of fields, like class FooSerializer(ModelSerializer): bar = serializers.StringRelatedField(source="bar") apple = serializers.StringRelatedField(source="bar.food") cat = serializers.StringRelatedField(source="bar.animals.pet") ball = serializers.StringRelatedField(source="bar.toy") # a lot of other complex fields related with Foo # direct-indirect, 1-1 or 1-M relations class Meta: model = Foo fields = ['bar', 'apple', 'cat', 'ball', ....] Now, this is causing the serialisation to take a lot of time. I added logging and saw many SQL queries getting executed. A lot these queries are repeated. As per my understanding from documentations, even though Django QuerySet is lazily executed, the serialization in DRF is querying for each field to get populated. Please elaborate on how serialization fields are populated on lower level as well as it will help me more. What I want to achieve here is do minimal possible queries. In the example above, To get bar.food and bar.toy I want to do only one single query which will fetch bar object and I can access food and toy object. One possible solution I can think of is … -
Countdown in Django Html Template
I am trying to implement a countdown, that will give me the number of days and hours until the deadline. I have tried two different methods using the html filter but nothing is displayed. Is the filter not already part of Django? models.py class Quote(models.Model): deadline = models.DateTimeField(auto_now=False, blank=True, null=True) html filter Method 1: {{ quote.deadline|timeuntil:today }} Method 2: {{ quote.deadline|timesince:comment_date }} -
Can't redirect using urls patterns
When i try go to http://127.0.0.1:8000/1395ec37e4/ i get error: Page not found at ... I don't know why, twice, when i had changed variable getted_short_url to short_urlin urls.py and views.py(redirect_view) it could redirect me. I am confused... Log from page: Using the URLconf defined in cut_and_go.urls, Django tried these URL patterns, in this order: <str:getted_short_url> admin/ The current path, 1395ec37e4/, didn't match any of these. views.py: from hashlib import sha256 from .models import URL from .forms import URLInput from django.shortcuts import render, redirect def input_form(request): if request.method == 'POST': form = URLInput(request.POST) if form.is_valid(): getted_url = form.cleaned_data["full_url"] transformed_url = 'https://' + getted_url try: URL.objects.get(full_url=transformed_url) except URL.DoesNotExist: maked_url = sha256(transformed_url.encode()).hexdigest()[:10] URL(full_url=transformed_url, short_url=maked_url).save() else: form = URLInput() return render(request, 'shortener/input_form.html', {'form': form}) def redirect_view(request, getted_short_url): return redirect(URL.get_full_url(getted_short_url)) urls.py: from . import views from django.urls import path urlpatterns = [ path('', views.input_form), path('<str:getted_short_url>', views.redirect_view) ]