Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can we write queryset to compare two id of different models and fetch the id related data like name,address in html form
#This is the view where I tried to write the queryset to compare to different ids #and tried to get the data related to that id in html form. But failed and I am new to #django # need good insight. #This is my views.py class SalaryEnter(generic.CreateView,generic.ListView,LoginRequiredMixin,PermissionRequiredMixin): form_class = SalaryPaymentForm model = SalaryPayment template_name = 'payment/salary.html' success_url = reverse_lazy('payments:salist') def get(self,request,*args,**Kwargs): entered = self.request.GET.get('Staff_id','') if entered == StaffRegistration.Staff_id: self.result = StaffRegistration.objects.values() else: self.result = StaffRegistration.objects.none() return super().get(request,*args,**Kwargs) def get_context_data(self,**kwargs): return super().get_context_data(results = self.result,**kwargs) #This is my template <!DOCTYPE html> <html lang="en"> {% extends 'payment/payment_base.html' %} {% block group_content %} {% load bootstrap4 %} {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Salary Payment Form</title> <link rel="stylesheet" href="{% static '/css/form_design.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <br><br><br><br><br><br><br><br><br> <h3>Salary Payment Form</h3> <div class="container"> <form enctype="multipart/form-data" action="{% url 'payment:salary' %}" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="button" value="Submit" class="btn btn-primary"> </form> <script src="{% static '/js/navigation_bar/staff_salary.js' %}"></script> </div> </div> </body> </html> {% endblock %} -
Return function output to a function view django
I want to use the output from a function in a function-based view. Passing the get_context_data function output to ShowProfilePage function view def ShowProfilePageView(request, username): def get_context_data(self, *args, **kwargs): context = super(ShowProfilePageView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(UserProfile, id=self.kwargs['pk']) user_posts = Post.objects.filter(author= page_user.user).order_by('-post_date') username = page_user.user context['page_user'] = page_user context['user_posts'] = user_posts context['username'] = username return context context = {} return render(request, 'registration/user_profile.html', context) -
Django website running too slow on Google Cloud Platform(GCP)
I am planning to migrated from DigitalOcean(DO) to Google Cloud(GCP). I have taken trial on GCP and hosted Django website on it, but it is running too slow (it take 12-15 seconds to open page). Same website running on DO is very fast(it take hardly 1 second to open page). Website is hosted on Ubuntu 20 LTS (on DO & GCP) & Apache2 server On GCP there is no user right now, for testing I am only one user and it is running too slow. I have 2CPU and 8GB memory on VM. I am not able to find out the issue why it is running slow on GCP and running fast on DO? Can someone please help to find out solution? -
How do I create list the intended way I want
I have the following scripts: Does calculation for me and lists them function fromPortIdChange() { fromportid = $('#fromPortId').val(); console.log(fromportid); portIdRange(fromportid,toportid); listOfNumbers=[]; } function toPortIdChange() { toportid = $('#toPortId').val(); console.log(toportid); portIdRange(fromportid,toportid); listOfNumbers=[]; } function portIdRange(fromportid, toportid) { fromportid = $('#fromPortId').val(); toportid = $('#toPortId').val(); fromportidlastvalueSliced = fromportid.slice(-5); interfaceNameLength = fromportid.length-1; interfaceName = fromportid.substring(0, interfaceNameLength); console.log("length: " +interfaceNameLength); console.log("interface name: " +interfaceName); fromportidlastvalue = fromportidlastvalueSliced.split('/')[2] console.log(fromportidlastvalue+ " FROM port id"); console.log("range is " +fromportid+ " to " +toportid); toportidlastvalueSliced = toportid.slice(-5); toportidlastvalue = toportidlastvalueSliced.split('/')[2] console.log(toportidlastvalue+ " TO port id"); console.log(typeof(toportidlastvalue)); calculateRange(fromportidlastvalue, toportidlastvalue, interfaceName); } function calculateRange(fromportidlastvalue, toportidlastvalue, interfaceName) { fromportidlastvalue = parseInt(fromportidlastvalue); toportidlastvalue = parseInt(toportidlastvalue); console.log(fromportidlastvalue + " type is " + typeof(fromportidlastvalue)); console.log(toportidlastvalue + " type is " + typeof(toportidlastvalue)); currentValue = fromportidlastvalue; while(currentValue<=toportidlastvalue) { console.log(currentValue); listOfNumbers.push(interfaceName+currentValue); currentValue++; } $('#port_range').val(listOfNumbers); } Here is the html involved: The part it is on the page and the one I am going to clone <div id = first> <div class="port"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="subnet_bit">From Port ID</label> <select id="fromPortId" class="custom-select mb-3" onchange="fromPortIdChange();"> <option selected>Select</option> {% for items in righttable %} <option value={{items.0}}>{{items.0}}</option> {%endfor%} </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="subnet_bit">To Port ID</label> <select id="toPortId" class="custom-select mb-3" onchange="toPortIdChange();"> <option selected>Select</option> {%for … -
What is the best way to implement sitemap.xml (or django-sitemap) on cookiecutter-django?
When trying to install django-sitemaps over the default cookiecutter-django generated project, after following the steps in the documentation, the following error happens: django.core.exceptions.ImproperlyConfigured: app_dirs must not be set when loaders is defined. Looks like Step 2 in the documentation: Make sure your TEMPLATES setting contains a DjangoTemplates backend whose APP_DIRS options is set to True. It’s in there by default, so you’ll only need to change this if you’ve changed that setting. conflicts with the default Loaders-approach that comes with the default install, and as such this piece of code does not function: TEMPLATES = [ { .... "APP_DIRS": True, "OPTIONS": { ... "loaders": [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ], ... ] Commenting out the "loaders" part does the trick, but changes the way templating is thought in cookiecutter-django in the process. So the question is: what is the best way of harmonizing django-sitemaps and cookiecutter-django? Is there a loader that can be added to the list that does the trick, preserving the intent of the original way the templating was concieved? Or is it better to just go APP_DIRS: True and comment loaders out entirely? Pros and cons? -
The script sqlformat.exe is installed in directory , which is not on PATH
I am getting this warning while I was trying to install django in a virtual environment in pycharm. But while I open python in command prompt then I don't get any warning like 'python is not in path or something', then why am I getting this warning now in pycharm? pls help me fix this, thankyou in advance. -
define an element as default value in a list created by a for loop in a django template
here is my html <div class="modal-body"> <form action="#" id="periodeOptionForm"> <div class=" card-body"> <div class="form-group form-elements"> <div class="form-label">Options</div> <div class="custom-controls-stacked"> {% for periode in periodes %} <label class="custom-control custom-radio" id'{{periode.labelle}}'> <input type="radio" class="custom-control-input" name="example-radios" value="{{periode.valeur}}"> <span class="custom-control-label">{{periode.labelle}} </span> </label> {% endfor %} </div> </div> </div> </form> </div> My fbv def periodes(request): ... periodes = [{"labelle":"10 minutes","valeur":10},{"labelle":"30 minutes","valeur":30},{"labelle":"1 heure","valeur":60}] .... return render(request,"my_template.html",{"periodes":periodes} When I display the html page no elements are selected. I want the first element of my periodes list to be selected by default. How can I do it? -
Failed to decode response from marionette selenium without of docker
I have a django app that runs a selenium script that scrapes data from youtube channels, and I randomly get this error during collection Message: Failed to decode response from marionette I'm running this on my mac locally and I have only been able to find issues of this related to running it inside a docker, but I'm not running this inside anything except my virtual environment that has selenium installed. It seems like the solution is increasing the amount of memory allocated to the process, but I think I already have more than enough. I am working on a brand new 2021 macbook air. Any idea on what I should do to fix this? -
New modules installed not found using pip
I was trying to do my first deploy using heroku, and for that I installed modules python-decouple and dj-database-url with pip, but python is not recognizing this new modules, even packages like Pillow and colorama are not being recognized, the packages are installed in the env with the path: D:\User\Documents\My_Repository\training\env\Lib\site-packages The error when I type python manage.py runserver is quite extensive: vscode error -
Django queryset not updating on live server unless the server is restarted, but updates on local
I am using Django version 3.2 This queryset updates on local and on live: variable1 = serialize('json', Calls.objects.order_by('-time_pulled','-time')[:15].using('myDatabase')) These two querysets only update on live after a server restart and then never refresh: variable2 = Calls.objects.filter(local_date = current_local_date).using('myDatabase').count() variable3 = serialize('json', Calls.objects.all().filter(local_date=current_local_date).using('myDatabase')) I did read in the Django docs that .count() does not return a new queryset, but .filter() is supposed to. I tried to use Calls.refresh_from_db but this doesn't refresh the queryset either. I also tried calling Calls.objects.all()[:15].using('myDatabase') at the beginning of the view function to see if it would fetch a new queryset, but don't see the results in the latter calls. Any help would be appreciated. Thank you in advance. -
Django ORM shows empty JSONField but postgreSQL shows contents
I am using a Django (3.2.6) JSONField to store geoJSON data, with postgreSQL 10.14 on the back end. The fields are generally defined in a class in the following manner: from django.db import models from django.core.serializers.json import DjangoJSONEncoder class BaseComponent(models.Model): class Meta: abstract = True name = models.CharField(max_length=256, null=True, blank=True) x = models.FloatField(null=True, blank=True) y = models.FloatField(null=True, blank=True) geometry = models.JSONField(null=True, blank=True, default=dict, encoder=DjangoJSONEncoder) I store values to these objects and later want to retrieve the JSON field. I do the following in the Django shell and can show that the geometry field is a NoneType with apparently no data. In [14]: obj.geometry In [15]: type(obj.geometry) Out[15]: NoneType In [16]: obj.id Out[16]: UUID('aed2fd38-28de-477d-bf4b-0d78b68bd729') However, when I call the same data back from the associated database, I see the following: SELECT id, geometry FROM basecomponent_table WHERE id='aed2fd38-28de-477d-bf4b-0d78b68bd729'; id | geometry --------------------------------------+--------------------------------------------- aed2fd38-28de-477d-bf4b-0d78b68bd729 | {"type": "Feature", "geometry": {"type": "Polygon", "coordinates": [[[-121.018614, 42 .377513], [-121.01859, 42.377513], [-121.01859, 42.378199], [-121.018614, 42.378199], [-121.018614, 42.377513]]]}, "propertie s": {...}} (1 row) How could this be? The data stored even appears to be valid JSON. A few basic things I have tried thus far: Restarting my Docker environment Rolling back and migrations associated with the JSON field Varying … -
Semantic UI Dropdown ApiSettings not working
I simply want to make this dropdown a dynamic search but for some reason jquery isn't working correctly. The field becomes searchable but no dropdown results. Django isn't receiving any api requests on input. //HTML <div class="ui fluid search selection dropdown" id="origin-search"> <div class="text">Search Origin</div> <i class="dropdown icon"></i> <input type="hidden" name=""> </div> //JS $(".location-search").dropdown({ apiSettings: { url: url, } }); libraries used: <script src="{% static 'javascript/jslib/moment.2.20.1.js' %}"></script> <script src="{% static 'javascript/jslib/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'javascript/jslib/jquery.datatables.min.js'%}"></script> <script src="{% static 'javascript/jslib/jquery.formset.js' %}"></script> <script src="{% static 'semantic/dist/semantic.min.js' %}"></script> Any idea why? This in django. -
I want to set an API on django rest framework just like it https://docs.microsoft.com/en-us/rest/api/power-bi/reports/get-reports-in-group#code-try-0
I want to set an API on django rest framework which take sheet_id of google drive. I want same functionality but google.drive. https://docs.microsoft.com/en-us/rest/api/power-bi/reports/get-reports-in-group#code-try-0 -
Django Middleware user is always anonymus (REST, SimpleJWT)
I am using Django REST Framework alongside with rest_framework_simplejwt and trying to write my own middleware, that will update user.last_request every time user performs one. from django.utils.timezone import now class LastRequestMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: request.user.last_request = now() request.user.save() response = self.get_response(request) return response``` But every time `user.is_authenticated` returns `False' -
subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method
I am working on a Django project integrated with MongoDB as the database. I have set up my models for a simple blog post, views(function-based views), and URLs but I experience this error when I want to add a post(from the admin area for now): NotImplementedError at /admin/mongo/post/add/ subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) verbose_name = 'Post' verbose_name_plural = 'Posts' def __str__(self): return self.title def get_absolute_url(self): return reverse("mongo:post_detail", args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_list(request): posts = Post.published.all() return render(request, 'blog\post\list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) -
What is best practice to remove values in M2M relation in DRF?
could you please point this out... What is the best practice in django rest framework should be if I wanna remove some m2m objects from base model object? Should I just be satisfied with views method PATCH and update method in serializers (orm m2m method "set" to reset and install all values from scratch) and to use obj.m2m.set(*[list_values]) OR should I implement a views action method DELETE to remove specific values (orm m2m method "remove" to remove specified in list objects) and to use obj.m2m.remove(*[list_of_values])? -
Django Modelform with one custom field doesn't save
We use a JSONField to store some dynamic data on our application. We would like to present this data in a user friendly manner and decided on a table with keys and values. For this we adjusted the ModelForm in our forms.py: class UserEditForm(ModelForm): class Meta: model = OUR_MODEL fields = ['description', 'reference'] widgets = { 'reference': CustomJSONWidget(), } The CustomJSONWidget is defined as follows: class CustomJSONWidget(Widget): template_name = 'jsonwidget.html' def get_context(self, name, value, attrs=None): return {'widget': { 'name': name, 'value': json.loads(value), 'type': 'table' }} def render(self, name, value, attrs=None, renderer=None): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name).render(context) return mark_safe(template) And finally the jsonwidget.html looks like this: <table name="{{ widget.name }}"> ... <tbody> {% for key, val in widget.value.items %} <tr> <td><input {% if key != None %} value="{{ key|stringformat:'s' }}"{% endif %} /></td> <td><input {% if val != None %} value="{{ val|stringformat:'s' }}"{% endif %} /><td> <tr> {% endfor %} </tbody> </table> It looks good on the page, exactly like we envisioned it, but the saving doesn't work: when trying to update the description it throws that reference is a required field and changing the table doesn't do anything. Where do we have to overwrite the save? Is … -
Fake installization in django
When I install django (pip install django) the cmd say Requirement already satisfied but when I do this (django-admin --version) to get the version the cmd say 'django-admin' is not recognized as an internal or external command, operable program or batch file. -
Django ORM Annotate Count Items and Order by Specific Order?
I have a graph showing different licence types by region and how many active licences there are in each region. Is there a way to order the items in a specific order in the queryset to be output to the graph? These are my models: class Licence(models.Model): status = models.CharField(choices=STATUS, max_length=1000) number = models.CharField(unique=True, max_length=1000) licence_type = models.ForeignKey( "LicenceType", on_delete=models.SET_NULL, null=True ) class LicenceType(models.Model): region = models.ForeignKey( "Region", on_delete=models.SET_NULL, null=True ) class Region(models.Model): slug = models.SlugField(primary_key=True) Here is my view: @login_required(login_url="/login/") def dashboard(request): # total number of active licences across regions active_licences = ( Licence.objects.values("licence_type", "licence_type__region") .annotate(total=Count("id")) .order_by("licence_type") ) return render(request, "dashboard.html", "active_licences": active_licences) Is there a way that I can specify the order in which the regions appear? For example, they are currently in the order (by pk) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] but I want them to appear as [1, 3, 2, 4, 5, 6, 7, 8, 9, 10]. -
Saving a list on a djago model
Hi guys I'm working with python, django and django rest framework I want to sabe the information that i have on a dictionary into a model but I don't know how to do it I would be really thankful if you explain me how can I do it This is the list [{'evolution': 'charizard', 'height': 11, 'id_pokemon': '5', 'name': 'charmeleon', 'stats': [[80, 'speed'], [65, 'special-defense'], [80, 'special-attack'], [58, 'defense'], [64, 'attack'], [58, 'hp']], 'weight': 190}, {'evolution': 'charmeleon', 'height': 6, 'id_pokemon': '4', 'name': 'charmander', 'stats': [[65, 'speed'], [50, 'special-defense'], [60, 'special-attack'], [43, 'defense'], [52, 'attack'], [39, 'hp']], 'weight': 85}, {'evolution': 'None', 'height': 17, 'id_pokemon': '6', 'name': 'charizard', 'stats': [[100, 'speed'], [85, 'special-defense'], [109, 'special-attack'], [78, 'defense'], [84, 'attack'], [78, 'hp']], 'weight': 905}] #_____________________________________ #And i want to save it on this model class Pokemon(models.Model): """Database model for pokemon information""" id_pokemon = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) weight = models.IntegerField() height = models.IntegerField() special_defense = models.IntegerField() special_attack = models.IntegerField() defense = models.IntegerField() attack = models.IntegerField() hp = models.IntegerField() speed = models.IntegerField() evolution = models.IntegerField() -
Django Rest-Framework During Validation, Check the Request Method Type
I am working on API Validation Errors to be called. I have to make sure 2 dates don't overlap when making new "POST" calls, which is working fine. I am doing a model.objects.Filter() query and if anything gets returned, I return a validation error. However, I want to return this error only during POST requests. I have tried if request.method == "POST": do something but I get errors under the "request" word saying "request" is not defined. is there another way to check the Method Type during validation? I am doing this in my serializer. Thanks! -
AttributeError: 'int' object has no attribute 'pk' - Django
I'm trying to return a very simple serialised queryset and I get this error: AttributeError: 'int' object has no attribute 'pk' Models: class Portfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False) class Image(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) portfolio = models.ForeignKey(Image, related_name="images", on_delete=models.CASCADE) thumb = models.URLField(blank=True, null=True) View: class PortfolioViewSet(viewsets.ModelViewSet): serializer_class = serializers.PortfolioSerializer queryset = models.Portfolio.objects.all() permission_classes = (permissions.IsAuthenticated, core_permissions.IsMineOnly) def get_queryset(self): portfolios = self.request.user.portfolio_set.all() ser = self.serializer_class(portfolios, many=True) data = ser.data return data serialisers: class PortfolioSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = models.Portfolio exclude = ('user',) class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' I read this answer that says we should use validated_data after calling is_valid() first but I don't serialise data but a queryset so I can't call this method. -
Is there a way to access lower and upper values in Django PostgreSQL specific fields?
More specifically I need to get start and end dates from a DateRangeField. -
Not loading svg logo in html page in django site (logo broke)
I'm trying to use svg format for my logo but getting this, can't figure out why? <div class="bgimg"> <div class="topleft"> <p><img src="{{STATIC_URL}} svg/logo.svg"/> Page title</p> </div> It look like this... -
django project-level object instantiation
Suppose I would like to create an object that performs some action every n seconds. For example, an object that does machine learning calculations on server data every hour. What is the correct way to instantiate such object in Django immediately after an app is loaded.? What is the correct way to call an infinite loop of this object? What is the correct way to call an on-server-shutdown object's method? For the first question, I think it is somehow related to the app's module apps.py, but do not know how to implement this: from django.apps import AppConfig from django.contrib.auth import get_user_model class MyAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myapp' def ready(self): print("my app has been loaded!")