Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how Count() works in django
I can get the count of a foreign key relationship for each row using django.db.models.Count like below from django.db.models import Count Publisher.objects.annotate(num_books=Count('book')) but the Count() function is weird for me and I think it works like magic, can you explain how it works? I read this page but I don't found anything related to my question https://docs.djangoproject.com/en/3.1/topics/db/aggregation/ and I tried to print Count() print(Count("book")) //Count(F(book)) and I don't understand this too -
Excluding the Data of Child Class Model From The Super Class Model in Django
I have some models like this: class Super(models.Model): attr1 = ... attr2 = ... class Child(Super): child_attr1 = ... child_attr2 = ... Now I when I do Child.objects.all(), it gives child objects only. However, when I do Super.objects.all(), it gives all the super and child objects. Is there a queryset like Super.objects.exclude(...) which I can use to get the objects of Super class model only? -
Allauth signup customization
Hello everybody i was exploring a way to create a good registration and login system and i found the allauth lib that was very good in configurations and had many good sides. The question is how can i customizate the signup page because i have many fields in the registration form and i don't found a way to use my own design and add more fields i have searched in google in youtube and stackoverflow but nothing was helping and everybody was adding a boostrap design and that was all ( i will very thankfull if anybody will show me a way, sorry for my bad literature. -
django - rest framework response content negotiation not happening
I upgraded djangorestframework from version 3.2.5 to version 3.5.3. Since then response content negotiation (not sure if term is correct) is not happening. Sample code: serializer = SessionSerializer(active_sessions, many=True) print(serializer.data) response = Response(serializer.data) print(response.data) Output when using version 3.2.5 {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"count": 1, "previous": null, "results": [{"session_id": "16a635d0-0f7a-4366-b648-a907ea4f4692"}]} Output when using 3.5.3 {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} I am using below rendered 'DEFAULT_RENDERER_CLASSES': ( 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', ), I tried a lot of things, but nothing seems to work. -
How to go about creating a paint app in Django [closed]
I wanted to create a paint app in Django. Can someone guide me through the steps I need to go through to achieve this. Thanks! -
Is it possible to show only a certial fields when using django-material forms
{% form form=form %}{% endform %} this thing renders the complete form https://pypi.org/project/django-material/0.5.1/ -
Django/PostgreSQL custom TimeRangeField
I'm trying to create a TimeRangeField but am having some problems saving to the database (PostgreSQL version 9.5.23). from psycopg2.extras import DateTimeRange from django import forms from django.contrib.postgres.forms import BaseRangeField from django.contrib.postgres.fields.ranges import RangeField from django.db import models class TimeRangeFormField(BaseRangeField): default_error_messages = {'invalid': 'Enter two valid times.'} base_field = forms.TimeField range_type = DateTimeRange class TimeRangeField(RangeField): base_field = models.TimeField range_type = DateTimeRange form_field = TimeRangeFormField def db_type(self, connection): return 'tsrange' The error when saving seems pretty self explanatory - pretty sure I need to cast the time object to a string but I have no idea how to do that. function tsrange(time without time zone, time without time zone, unknown) does not exist LINE 1: ...('b9925dd3-d4a8-4914-8e85-7380d9a33de5'::uuid, 1, tsrange('1... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. -
Django admin misbehaves after adding for django.contrib.sites on server
Django Admin Site was working fine on local server. But the same thing when deployed on server. Admin CSS misbehaves See Screenshot Admin panel screenshot on server admin panel site also working fine on mobile responsive view or small screens On localhost it looks something like this. I have ran collect static several times on server but nothing happens. Tried Clearing Cache many time. Nothing worked But localhost seems to work fine -
no such table: Append_employeemodel Django
GitHub repository When I send a post request I get this. I previously try python manage.py syncdb ./manage.py migrate python manage.py migrate python manage.py createsuperuser python manage.py makemigrations python manage.py migrate but I still got an error. The Git Hub link is above please help me. -
Django Form Validation : shows enter a valid date but the date given is correct
I'm working in a project where i've to implement Nepali calender. The calender is working fine but django validation does not accept the date. The date selected is valid according to BS (Bikram Sambat) calender but it is not valid as per AD calender. If i choose the date upto 2077-04-30 it works fine but it does not accept 31 and 32 on 4th month. There are 32 days on 4th month of BS calender. How can i make django accept this date? Any suggestion is highly appreciated. Thanks. -
Multiple user types Django + React
I am currently planning out an application that I plan to build with Django (backend) and React (frontend). Where I am currently hitting a roadblock is the implementation of multiple user types. I am choosing Django as the backend for the sake of the fact that it will handle authentication, session management, etc.. I'd like to create an API to pull the information to the frontend which I will be using the django-rest-framework to do so. User types: Company - Company will fulfill orders - Company can have multiple Clients Client - Client will submit orders - Client can have multiple Company's to submit orders to There is no need for users to switch between accounts, and I would like to do away with the the default username and implement email to login/register. Thanks for your input -
How to manually render formset form select choices as radio button
I'm trying to manually render my form choices in a formset as radio buttons. I think I've got close to the right idea, but I'm somehow missing something with the values set in the input tag. This is a solution that seems to fit my needs better than using {{ form.as_p }}, because I'm zipping a formset and a list and displaying both simultaneously. I'm really hoping to have the input tag's syntax correct, but I'm not sure what I'm missing. <div class="" style="flex-wrap: wrap; display: flex;"> {{ formset.management_form }} {% for form in formset %} {% csrf_token %} <div class="col "> <table style="border-radius: 21px;"> <p style="font-weight: 500;" class="question-text"> </p> <tr class="bubbles"> <td class="bubble-text-left">Not interested&nbsp;</td> {% for choice in form.value %} <td> <label class="container"> <input type="radio" name="{{ form.value.choice.name }}" value="{{ form.value.choice.0 }}" id='{{ form.value.choice.auto_id }}' class="{{ radio_input.choice_value }}"> <span class="checkmark"></span> </label> </td> {% endfor %} <td class="bubble-text-right">Very interested</td> </tr> </table> <br> </div> {{ form.id }} {{ form.question }} {% endfor %} </div> -
Creating more than 1 html files on public directory
I want to use React with Django. For this, i thinked this structure: Project |_ back-end (django) |_ front-end (builded react) |_ index.html |_ about.html |_ contact.html |_ <other files and bundles> But i can create only index.html. I dont know how can i create other html files on react, for use with django. -
how to display registered image on django ImageField
I need to make a custom ImageField with django. with dropify.js, I could make drag & drop image field but I need to display current image when it has image already (when user need update the image file after create a post once) dropify has attribute named "data-default-file" so I am trying to modify my forms.py as below. Please kindly guide me to input the image's url when it has the image... thanks in advance! Forms.py ... from django import forms from django.forms import ModelForm from shop.models import Product from event.models import * class ProductRegisterForm(forms.ModelForm): detailVN = forms.ImageField(label='Detail(VN)', widget=forms.FileInput(attrs={ 'id':'detailVN', if it has image: 'data-default-file': image-url })) Models.py class Product(models.Model): ... detailVN = ProcessedImageField(upload_to = img_path, processors=[ResizeToFit(width=1150, upscale=False)], format='JPEG', options={'quality':90}, blank=True, null=True, ) -
libscca-python failed on jenkins build
I have django app try to build it on Jenkins, However when it reaches Install pip dependencies stage it fails because of libscca-python library. I got long error but I will paste here what I think it may help on finding the issue: Building wheels for collected packages: libscca-python Building wheel for libscca-python (setup.py): started Building wheel for libscca-python (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /home/jenkins/agent/workspace/SI_backend_develop/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-e6l9je1l/libscca-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-e6l9je1l/libscca-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-pwlznjn1 cwd: /tmp/pip-install-e6l9je1l/libscca-python/ from common/types.h:34, from pyscca/pyscca_integer.c:23: /usr/include/fortify/string.h:144:1: error: 'mempcpy' undeclared here (not in a function); did you mean 'memccpy'? 144 | _FORTIFY_FN(mempcpy) void *mempcpy(void *__d, const void *__s, size_t __n) | ^~~~~~~~~~~ /usr/include/fortify/string.h:145: confused by earlier errors, bailing out error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /home/jenkins/agent/workspace/SI_backend_develop/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-e6l9je1l/libscca-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-e6l9je1l/libscca-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-e7hsbwat/install-record.txt --single-version-externally-managed --compile --install I'm totally new to devOps, your help is appreciated! -
How to use @property in models choices?
My model: **class SomeModel(models.Model): ... models.CharField(max_length=255, choices=BookPage.choices)** My choices: from enum import Enum class BookPage(Enum): MAIN = "Main" SIDEBAR = "Sidebar" @property def choices(self): return [(key.value, key.name) for key in self] I got this error Where I'm wrong? choices' must be an iterable (e.g., a list or tuple). -
How to display value form database with javascript in django
So i have this dropdown field in a form that comes from a model that consists of foreign keys, and i want to display the values from database based on that foreign key when i chose the dropdown field in the form with Javascript, but i really have zero knowledge in javascript. So i was wondering if anyone could help me This is my forms class DssPostForm(forms.ModelForm): class Meta: model = Simulation fields = ['cpu_name'] my model class Simulation(models.Model): build_name = models.CharField(blank=False, max_length=150) mtb_name = models.ForeignKey(Motherboard, on_delete=models.CASCADE) cpu_name = models.ForeignKey(Cpu, on_delete=models.CASCADE) vga_name = models.ForeignKey(Vga, on_delete=models.CASCADE) ram_name = models.ForeignKey(Ram, on_delete=models.CASCADE) str_name = models.ForeignKey(Storage, on_delete=models.CASCADE) def __str__(self): return self.build_name my views def DssPostView(request): if request.user.is_authenticated: form = DssPostForm() return render(request, "dss_form.html", {'form': form}) else: messages.info(request, 'Silahkan Login Terlebih Dahulu.') return redirect('accounts:login') and my templates <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-secondary">Add CPU</button> </form> -
DRF Custom throttle rate doesn't work, default rate works
I'm trying to set up the throttle rate for all users to 100 requests per 15 minutes. The problem is that when I override AnonRateThrottle and UserRateThrottle, the throttling doesn't work at all. REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { # I've lowered the rates to test it 'anon': '2/min', 'user': '2/min' } } Works perfectly. This does not work: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'DEFAULT_THROTTLE_CLASSES': [ 'api.throttle_rates.AnonHundredPerFifteenMinutesThrottle', 'api.throttle_rates.UserHundredPerFifteenMinutesThrottle', ], } api.throttle_rates from rest_framework.throttling import AnonRateThrottle, UserRateThrottle class AnonHundredPerFifteenMinutesThrottle(AnonRateThrottle): def parse_rate(self, rate): return (2, 60) class UserHundredPerFifteenMinutesThrottle(UserRateThrottle): def parse_rate(self, rate): return (2,60) Do you know where is the problem? -
How can I display many to many field as a drop down in filter?
fillter snapshot This is what I am getting in filter, I want it as a drop down list to look nicer. The codes I have tried until now is: filters.py class WinsFilter(django_filters.FilterSet): class Meta: model = Wins fields = ['playerdetail',] my views.py looks like below class MatchWinsView(ListView): model = models.Wins template_name = 'match_wins.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = WinsFilter(self.request.GET, queryset=self.queryset) return context And below is the model I have created. class Wins(models.Model): matchdetail = models.ManyToManyField(Matches) playerdetail = models.ManyToManyField(Players) I have tried referring documentations but I am not able to get the correct solution yet? What changes should I do to make proper drop down in my filter? -
What {% %} and {{ }} mean in HTML?
I have recently started to learn Django, so I came across with some HTML templates, but those are pretty unfamiliar for me, they mostly consist of {% and {{ For example: <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> What are they? Implementations from other languages or HTML syntax? I'd be happy to get some docs, websites or examples too. -
Django pages load slow
I'm pretty new to Django and I'm trying to develop a streaming service application. I'm running into a problem with the page load times. In my main python file, I have a loop that runs through my Cassandra db and retrieves all content in there. Each 'content' is stored as a dictionary. So when I pass the content to my templates, I'm essentially passing a dictionary of dictionaries. I'm sending in a max of 15 dictionaries at a time (for bandwidth conservation), but I'm experiencing page load times up to 8 seconds. This causes the videos to buffer before playing, and a poor user experience. Am I sending too much to the templates? Or is there a way to speed up the process? -
How to automatically show selected field in MultiSelectField in Django?
Let's say I have a model with MultiSelectField from django-multislectfield as shown below. User can check as many fields as they want to and then they submit the form. Now what I want is that when they come back to form page the fields that user checked before remain there the same. How can I do that? example of model and form class class Test(models.Model): names = MultiSelectField(choices=....) class TestForm(forms.ModelForm): Class Meta; model = Test fields = '__all__' -
Unable to import PIL with Pillow installed - Django project under venv
I've been struggling for hours trying to debug this and none of the solutions I've found worked for me. I have a Django project running in a virtual env and installed Pillow to use Image. The problem is that I can't import it. VScode tells me that it is "Unable to import 'PIL'" I have other packages like crispy_forms that are installed and work perfectly fine. If I open the Python shell using py manage.py shell then run from PIL import Image I get no errors. Furthermore if I now type Image It returns the correct infos : <module 'PIL.Image' from 'C:\\Users\\XXXX\\Documents\\webDev\\djangoProjects\\env\\lib\\site-packages\\pillow-7.2.0-py3.8-win32.egg\\PIL\\Image.py'> I tried to uninstall Pillow then reinstall it, even using easy_install Pillow. This is clearly not a problem of pathing or different versions of Python as I'm in my virtual env AND as show above I can run the import on my shell and find the files. Thanks for your help. -
form is not saving changes in dialog modal (popup) Django
I’m really new in Django and I need your help, please I’m trying to implement Modal dialog using forms. The problem is that even when I make some changes in my form, this changes are not shown in database… I have no idea why. When I test form outside Modal dialog, form is working… Here is my form.py: class anomalie_location_form(ModelForm): class Meta: model = Anomalie fields = ['localization', ] here is my view.py @login_required(login_url='login') def fix_anomalie_stock(request, pk, type_anomalie): anomalie_pk = Anomalie.objects.get(id=pk) # form to change anomalie position form_location = anomalie_location_form(instance=anomalie_pk) if request.method == 'POST': print('printinng anomalie_location_form POST ', request.POST) form_location = anomalie_location_form( request.POST, instance=anomalie_pk) if form_location.is_valid(): form_location.save() return redirect('/') context = {'anomalie_pk': anomalie_pk, 'form_location': form_location} return render(request, "anomalie/fix_anomalie_stock.html", context) and my html: <div class="modal fade" id="myModal2" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4>{{product.product_name }} </h4> </div> <form action="" method="POST"> {% csrf_token %} <div class="modal-body"> {{form_location}} </div> <div class="modal-footer"> <input type="submit" class="btn btn-primary" value="Treter" data-dismiss="modal"> </div> </form> </div> </div> </div> So the question is why form is working outside of Dialog Modal ? I would appreciate your help. Thanks a lot -
i am calling django server from angular js but cors error is occuring while executing so what should i do to call django url from angular js?
Here is the angular js code where URL is of Django server and I am calling testapi URL from that. ''' app.service('$reportsService', ['$http', function($http) { this.getReport = function(moduleName, moduleKey, reportFormat, intervalFromDays, intervalToDays, fromReportTime, toReportTime, reportID ,phononUUID,attemptID,requestID,queueIds,flowIds,callStatus) { return new Promise((resolve, reject) => { $http({ url:"http://localhost:8000/testapi/", method: "POST", data: { reportStandardName: moduleName, moduleKey, reportFormat, intervalFromDays, intervalToDays, fromReportTime: moment(fromReportTime, "HH:mm:ss").format('HH:mm:ssZZ'), toReportTime: moment(toReportTime, "HH:mm:ss").format('HH:mm:ssZZ'), reportID, phononUUID, attemptID, requestID, queueIds, flowIds, callStatus, sourceOfRequest: "API", priority: 1, reportTime: new Date().toLocaleTimeString(), } }).then(function(res) { if (res.status === 200) { console.log('getReport fetched : ', res.data); resolve(res.data); } }).catch(e => { console.error("getReport failed with error: ", e); reject(); }) }) } ''' Here is my djago urls file urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^testapi/', views.getResponse) ] Pls give me the solution of the above cors error that occurs when i am calling django server from angular server. Both file are on the same machine.