Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotate a Foreign Key field in Django
Let's say I have three Models: class Product(models.Model): name = models.CharField(max_length=255) class Plan(models.Model): products = models.ManyToManyField( Product, ) class User(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) I want to make a query to get a list of Users, prefetch their plan, and annotate their plan with the count of Products. I'm trying something like this: plan_queryset = Plan.objects.all().annotate(num_product=Count('products')); queryset = User.objects.all() \ .prefetch_related( Prefetch('plan', queryset=plan_queryset ) ) But unfortunately, the query doesn't execute. Passing the queryset into a serializer I get an error saying "num_product" is not defined. What's the best way to go about annotating a foreign key field without making a query for each object? (n + 1 problem). -
Django - Form data won't save to the database
I created a "vanilla" form that when submitted should check to see if an Item exists based on the text input. If it does will increment a counter on that items "item_selected" field then continue to create a requisition record using that item and the rest of the submitted fields. Else the item does not exist and it will create the item record as well as creating the requisition record. When submit my form nothing is happening. I made sure the url routing was correct and is being submitted to the correct view. I dont believe I can use a ModelForm because ModelForms bind to one model and here I am trying to update multiple tables. Thank you in advance! Views.py def create_req(request): if request == 'POST': req_form = ReqForm(request.POST) if req_form.is_valid(): try: item_record = ItemMaster.objects.get(item=req_form.cleaned_data['item']) item_record.save(commit=False) item_record.item_selected = F('item_selected') + 1 item_record.save() requisition_record = Requisition.objects.create(item=req_form.cleaned_data['item'], signature=req_form.cleaned_data['signiture']) requisition_record.save(commit=False) requisition_record.username = CustomUser.objects.get(username=request.user) requisition_record.save() except ItemMaster.DoesNotExit: item_record = ItemMaster.objects.create(item=req_form.cleaned_data['item'], description=req_form.cleaned_data['description'], price=req_form.cleaned_data['price'], item_selected=1) item_record.save() requisition_record = Requisition.objects.create(item=req_form.cleaned_data['item'], signature=req_form.cleaned_data['signiture']) requisition_record.save(commit=False) requisition_record.username = request.user requisition_record.save() return HttpResponseRedirect(reverse('home') ) else: req_form = ReqForm() return render(request, 'req/create_req.html', {'req_form':req_form}) forms.py class ReqForm(forms.Form): item = forms.CharField(min_length=3, max_length=20) description = forms.CharField(min_length=0, max_length=50, empty_value='' ) price = forms.DecimalField(max_digits=19, decimal_places=2) signiture = … -
what is the meaning of error "FOREIGN KEY constraint failed" in Django?
I'm getting error FOREIGN KEY constraint failed in django and my database is SQLite. I got this error while updating my data from Django admin. I'm not understanding the meaning of this error. Even I haven't used Foreign Key field in my model. Please any one can help to resolve this problem -
Http Call from android from Rest API
How do I get rest api data that I created using Django's rest framework ? Also just for the information I am not being able to access this link from my android phone browser either so quiet obviously if I do a volley /http reqest it won't do anything. enter image description here -
Using AppConfig to import signals is not working Django 2.08
I have an app companies. Inside the app there is a file called signals.py with the following code: post_save.connect(update_descendants, sender=Company) Inside companies apps.py I have: class CompaniesConfig(AppConfig): name = 'apps.companies' def ready(self): from . import signals But the signals are not imported/called. If I import the file in models.py it work but it creates a circular import issue, and I need to this imports inside functions not at top. Structure: - companies -apps -models -signals Why app config is not working ? -
Angular post data is not going to Django REST API
I'm using Angular 6 and Django REST Framework The view of DRF is class AmountGivenViewSet(viewsets.ModelViewSet): serializer_class = AmountGivenSerializer permission_classes = (IsAuthenticated, AdminAuthenticationPermission,) def get_queryset(self): return AmountGiven.objects.filter( contact__user=self.request.user ) def perform_create(self, serializer): save_data = {} print(self.request.POST) # validate user and to save_data dictionary contact_pk = self.request.POST.get('contact', None) print(contact_pk) if not contact_pk: raise ValidationError({'contact': ['Contact is required']}) contact = Contact.objects.filter( user=self.request.user, pk=contact_pk ).first() if not contact: raise ValidationError({'contact': ['Contact does not exists']}) # add contact to save_data dictionary save_data['contact'] = contact # process mode_of_payment is in request mode_of_payment_pk = self.request.POST.get('mode_of_payment', None) if mode_of_payment_pk: mode_of_payment = ModeOfPayment.objects.get(pk=mode_of_payment_pk) if not mode_of_payment: raise ValidationError({'mode_of_payment': ['Not a valid mode of payment']}) # add mode_of_payment to save_data dictionary save_data['mode_of_payment'] = mode_of_payment # pass save_data dictionary to save() serializer.save(**save_data) AmountGivenSerializer in serializers.py class AmountGivenSerializer(serializers.ModelSerializer): class Meta: model = AmountGiven depth = 1 fields = ( 'id', 'contact', 'amount', 'interest_rate', 'duration', 'given_date', 'promised_return_date', 'mode_of_payment', 'transaction_number', 'interest_to_pay', 'total_payable', 'amount_due', 'total_returned', 'comment', 'modified', 'created' ) and in Angular component import { Component, OnInit } from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {AmountGiven} from '../amount-given.model'; import {AmountGivenService} from '../amount-given.service'; import {ActivatedRoute} from '@angular/router'; @Component({ selector: 'app-amount-given-add', templateUrl: './amount-given-add.component.html', styleUrls: ['./amount-given-add.component.css'] }) export class AmountGivenAddComponent implements OnInit { addMoneyForm: FormGroup; … -
Django QuerySet Lookup Fails When Testing for Value "Local"
I have a QuerySet which returns a list of user-defined tags. In some cases, I'd like to exclude any of the tags that start with the word "Local", but this seems to be causing me problems. The following examples work when I'm testing for other values (like HVAC below): queryset = queryset.exclude(tags__tag__tag_name__icontains = 'HVAC') queryset = queryset.exclude(tags__tag__tag_name__istartswith = 'HVAC') but when I try the same with "Local", it excludes everything, not just the values that contain or start with the word "Local". Both examples below exclude everything: queryset = queryset.exclude(tags__tag__tag_name__icontains = 'Local') queryset = queryset.exclude(tags__tag__tag_name__istartswith = 'Local') As an additional note, the following does work, but it only excludes that exact value and I can't anticipate / list all of the values that start with "Local": queryset = queryset.exclude(tags__tag__tag_name = 'Local 123') My best guess is that "Local" is a reserved word in python? Any ideas on ways around this or is there something else I'm missing? -
Django When() filtering raise an error
I'm trying to use a huge request to minimize the number of requests in my app. In my database I have some cards, each card has multiple amounts link to it, and each amount is linked to a category. I try to get the Sum of amounts for a category between 2 dates and the same thing for 2 previous dates (dates are in cards) compare them and get the percentage evolution. Everything works fine for all cases but one: If my sum for a category is 0 for the previous period, I have an error "Divide by 0" when I try to calculate the evolution. So I tried to get the evolution, only if the sum of the previous period is != 0, and return 'N/A' if = 0. For this I use Case(When()). But I have an error and I'm not sure to understand why. Here my request: categories = Category.objects.filter( Q(amount__card__date__range=( start_day_compare, stop_day_compare )) | Q(amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare )) ).annotate( evolution=Case( When( Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) != 0, then=Value( ( ( Sum( 'amount__amount', filter=Q( amount__card__date__range=( start_day_compare, stop_day_compare ) ) ) - Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) ) * … -
Do we need to upload virtual env on github too?
This is my GitHub repo https://github.com/imsaiful/backmyitem I push from my local machine and pull the changes in Amazon EC2. Earlier I have not added the virtual env file in my repo but now I have changed some file in admin directory which is containing in the virtual env. So should I go for to add the virtual env too on my GitHub or instead I change the same thing on my remote server manually? -
Should I learn Python Django or PHP to create a web app assessment with interactive plots?
I have a specific long-term goal for a web app but can't determine whether to use Python (with Django, perhaps) or PHP. Within a year or two, I would like to create a web app that administers an assessment to users, analyzes the responses, and displays interactive plots of the results back to the users. I say "year or two," because I first need to learn the programming/scripting languages and frameworks necessary to do it. The question is whether I should pursue learning Python or PHP to do the above. Some skill background: I currently use R, Rmarkdown, and RBokeh to analyze and visualize data at work. I've learned new programming languages before (i.e., Java, Perl), but my experience applying object-oriented programming is limited. (I started with Basic when I was a kid, a million years ago.) I'm proficient in HTML and CSS. I know a little Javascript but haven't used it much. I designed a web journaling program before blogs were around, so I think I can do this, but... Python Django looks daunting, and PHP for data analysis and graphing looks too basic. If I go with Python, I think I could use Bokeh for plotting (since I … -
Modifiable bullet list in Django
I currently have a list generated in views.py that is displayed by bullet points on the wanted page by the template. I would like so the user can add/remove/adjust the bullet points and save the adjusted bullet points so that when they go back on the page, their new changes are there instead. I have no idea how to implement this, nor could I find much on it. Would I use a model for this? JS? Just views.py/html and css within the template? -
Django to_html() update to allow users to select row
I am asking users to enter a string, and presenting them with some options to select from. These options are stored as a dataframe and I render them using the to_html() function. However, I cant find any information on how to edit the to_html() call to allow me to make it so the table can have selectable rows. Everything else work lovely! Here is relevant lines from views.py def result(request): search_term=request.POST.get('q','') search_term=str(search_term) lkp = run_lkp(SearchString) result = [] for l in lkp: result.append(dfCorpus.ix[l]) df= result[0] html_df=df.to_html(index=False) return render(request, 'result.html', {'html_df': html_df,'post_output': request.POST.get('q','')}) Here is result.html; <html> <h1><strong>lookup</strong></h1> <head> <title>select right one</title> </head> <body> <h3>You searched for:</h3> {{ post_output }} <h3>Your results:</h3> {{ html_df|safe }} </body> </html> Im assuming this is possible, but I cant figure out how! Thanks in advance! -
Django-postman implementation
I am trying to build user to user messaging feature and I am trying to use django-postman framework. I am finding hard to understand the documentation. All I have done so far is included postman URL to the base URLs file and included 'postman' in INSTALLED_APPS at settings.py What changes do I have to make to give the correct user interface so that users can have user to user conversation. I have asked a question previously as well. can you help me? -
How to make an array at the object's JSON field?
There was such a problem. I can pass a JSON format object [ { "title": "test", "address": "55.99752311227003,49.08959250252893" }, { "title": "test122", "address": "63.08891623673952,46.243883499999946" }, { "title": "test1111", "address": "55.69684742706125,37.59635133512744" }, { "title": "kgeu", "address": "55.816852257889856,49.09529045886616" } ] But I need to get a JSON object format [ { "title": "kgeu", "address": [55.816852257889856,49.09529045886616] } ] setting.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ) } serializers.py class FactorySerializer(serializers.ModelSerializer): class Meta: model = Factory fields = ['title', 'address'] views.py class FactoryListView(generics.ListCreateAPIView): queryset = Factory.objects.all() serializer_class = FactorySerializer How to do it? Thanks in advance for the help -
(1045, "Access denied for user 'root'@'cloudsqlproxy~[cloudsql instance ip]' (using password: NO)")
I'm trying to migrate a django app to google kubernetes engine and can't get it to work. The response from the app is: Exception Value: (1045, "Access denied for user 'root'@'cloudsqlproxy~[cloudsql instance ip]' (using password: NO)") If I fire up a bash shell into the running container in which the django app lives, I can connect to the cloud sql instance. I have my database credentials in environment variables but django doesn't seem to care about the username and password specifically. django connection settings from inside the container: from django.db import connection connection.settings_dict {'ENGINE': 'django.db.backends.mysql', 'NAME': 'aesh_db', 'USER': None, 'PASSWORD': None, 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, 'TEST': {'CHARSET': 'utf8mb4', 'COLLATION': 'utf8mb4_unicode_ci', 'NAME': None, 'MIRROR': None}, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'TIME_ZONE': None} the env vars are set correctly in the container, this works: >> import _mysql >> import os >> conn = _mysql.connect(db=os.getenv('DB_NAME'), user=os.getenv('DB_USER'), passwd=os.getenv('DB_PASS'), host=os.getenv('DB_HOST')) django db settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASS'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), 'OPTIONS': { # Tell MySQLdb to connect with 'utf8mb4' character set 'charset': 'utf8mb4', }, 'TEST': { 'CHARSET': 'utf8mb4', 'COLLATION': 'utf8mb4_unicode_ci', } } } deployment.yaml: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: aesh-web … -
Django Form Error Message Like "Please fill out this field" for Field Validation
I have a RegexValidator for a telephone field. It works to return the error when I render the form again. However, I noticed the "Please fill out this field" error message when trying to submit the form with a blank input, which doesn't re-render the form to show the message. How can I use this type of message for my own validator? Models.py class Proveedor(models.Model): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', code='invalid_phone_number', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") telefono = models.CharField(max_length=15, validators=[phone_regex], verbose_name='Teléfono') telefono_de_representante = models.CharField(max_length=15, validators=[phone_regex], verbose_name='Teléfono de representante') ... Forms.py - I thought the error_messages part was a potential solution but it didn't change anything class ProveedorForm(BaseModelForm): class Meta: model = Proveedor fields = ('nombre', 'telefono', 'representante', 'telefono_de_representante', 'correo_electronico') def __init__(self, *args, **kwargs): super(ProveedorForm, self).__init__(*args, **kwargs) self.fields['telefono'].error_messages = {'invalid_phone_number': 'Phone number must be entered in the format: \'+999999999\'. Up to 15 digits allowed.'} Views.py - I can access the errors from the last render statement (if form not valid) but this requires the page to be rendered again def proveedores(request, error=None): if request.method == "POST": form = ProveedorForm(request.POST) if form.is_valid(): form.save() return redirect('menu:proveedores') return render(request, 'menu/proveedores.html', {'form': form}) Ideally, I would like a … -
Convert AJAX example from php to python/django
I'm reading an AJAX tutorial at www.w3schools.com. Their examples uses php and I only know django. I got most of the conversion done myself but would greatly appreciate someone helping with the rest. Here is the php, I think I get down to the foreach block without having trouble: <?php // Array with names $a[] = "Anna"; $a[] = "Brittany"; $a[] = "Cinderella"; $a[] = "Diana"; $a[] = "Eva"; $a[] = "Fiona"; $a[] = "Gunda"; $a[] = "Hege"; $a[] = "Inga"; $a[] = "Johanna"; $a[] = "Kitty"; $a[] = "Linda"; $a[] = "Nina"; $a[] = "Ophelia"; $a[] = "Petunia"; $a[] = "Amanda"; $a[] = "Raquel"; $a[] = "Cindy"; $a[] = "Doris"; $a[] = "Eve"; $a[] = "Evita"; $a[] = "Sunniva"; $a[] = "Tove"; $a[] = "Unni"; $a[] = "Violet"; $a[] = "Liza"; $a[] = "Elizabeth"; $a[] = "Ellen"; $a[] = "Wenche"; $a[] = "Vicky"; // get the q parameter from URL $q = $_REQUEST["q"]; $hint = ""; // lookup all hints from array if $q is different from "" if ($q !== "") { $q = strtolower($q); $len=strlen($q); foreach($a as $name) { if (stristr($q, substr($name, 0, $len))) { if ($hint === "") { $hint = $name; } else { $hint … -
Related Manager is empty in one direction but not the other
I have a method on a Django Model in which I create a new related instance by passing self into get_or_create: def increment_or_create_item(self, product) item, created = Item.objects.get_or_create(cart=self, product=product) Weirdly enough the item the does not show up in self.items.all() directly after calling the above line. This works: assert self == item.cart # does not raise but this raises: assert self.items.all() == item.cart.items.all() #does raise self.items.all() returns an empty QuerySet whereas item.cart.items.all() return the correct filled QuerySet. I tried calling self.refresh_from_db() without success. How can this be? Thanks! -
Django - View or condition in urls chooses one of two url patterns with regard to whether the parameter has the value or is NONE
There are two models: groups and posts. The post can be of one of two kinds: assigned to the group, and not assigned to the group. The foreign key field in posts model, which assigns the group to the post, is optional. The post, which belongs to a group, should have a different address than one, which does not belong to the group. Here is the general rule. The former address is when a post does not belong to any group and the latter one if it does. .../posts/[year]/[month]/[day]/[slug of the post]/ .../groups/[name of the group]/posts/[year]/[month]/[day]/[slug of the post]/ The problem appears. After creating the post both url addresses work. It is not a surprise, because I include the urls from posts app in urls.py in groups app. What I want to do is to make the url addresses optional regarding to the group parameter (whether it is passed or not). It can work as something like: if groups parameter is not None choose the url from groups.urls if groups parameter is not None exclude url from posts.urls Basically I want to choose just one url, not two. Is it possible in Django to do it in a simple way? … -
how to setup supervisor for django
I have a problem with my configurations from the supervisor, well this is happening. my app is a server web socket when a run with de gunicorn like this #>gunicorn --bind 0.0.0.0:8001 colonybit.asgi:application this command run perfectly, but web sockets not working, when I run with the command traditional from django like this: #>python manage.py runserver 0.0.0.0.0:8001 working well, but the server is down if don't an activity, and decide install supervisor, I run this command $ sudo supervisorctl reread, not working and send me this message error like this error: <class 'socket.error'>, [Errno 2] No such file or directory: file: /usr/lib/python2.7/socket.py line: 228 I followed these tutorials 1: http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ and this 2: https://github.com/rfk/django-supervisor#configuration the first tutorial uses it gunicorn, but I not use it the second user django-supervisor but is discontinued my configurations is: root@ip-172-31-28-226:/etc/supervisor/conf.d# realtimecolonybit.conf [program:realtimecolonybit] command = /home/ubuntu/realtimecolonybit/colonybit/manage.py runserver host=0.0.0.0 port=8001 ; Command to start app user = root ; User to run as stdout_logfile = /home/ubuntu/realtimecolonybit/logs/realtime.log ; Where to write log messages redirect_stderr = true ; Save stderr in the same log environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ; Set UTF-8 as default encoding please help me, how to config my server using python manage.py etc I work with web sockets … -
unable to get display value of choice field using object.get_FOO_display in template
This is how my model looks like: class FacilityHoursOfOperation(models.Model): DAYS_OF_WEEK = ( (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday'), ) day = models.CharField(max_length=1, null=True, choices=DAYS_OF_WEEK, verbose_name="Day") This is how my view looks like: hoursofoperationslist = FacilityHoursOfOperation.objects.filter(some filter) return render(request, template_name="sometemplate.html",context={'hoursofoperation':hoursofoperationslist}) This is how my template looks like: {% for hop in hoursofoperation %} <tr> <td>{{ hop.get_day_display }}</td> </tr> {% endfor %} I was expecting it to display "Monday" or "Tuesday" etc. instead of 0 or 1. But it display 0 or 1. Looking at the documentation at https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display, it looks like it is supposed to but it is not. What am I missing here? -
How can I update a model on the Django admin page when the model is click to be viewed?
I have a function that updates my Orders model. In my admin.py, I register the model, and have a admin.ModelAdmin class associated with it. I want to call a function that runs when the registered model is clicked on the admin page, so that it updates before the users sees any information about the orders. I've tried just adding the function: class OrdersAdmin(admin.ModelAdmin): ... update_orders() But this just results in it being updated when I run the server, and not when the "Orders" model is clicked in the admin. I've looked into admin actions, but that is only related to making changes to various fields of the model after the page is populated with objects from Orders Model. How can I pass a function to be called when I click on the model in the admin page? Thanks. -
select_related on django 2.1 not working
I'm using Django 2.1 and Oracle 12C. From the django docs if we have something like: from django.db import models class City(models.Model): # ... pass class Person(models.Model): # ... hometown = models.ForeignKey( City, on_delete=models.SET_NULL, blank=True, null=True, ) class Book(models.Model): # ... author = models.ForeignKey(Person, on_delete=models.CASCADE) and then do either: Book.objects.select_related('author__hometown').all() Book.objects.select_related('author__hometown').filter(...) I get Unable to get repr for <class 'django.db.models.query.QuerySet'> Oddly, Book.objects.select_related('author_hometown').get(pk=123) works. Also, all the queries work if I use Django 2.0 as opposed to 2.1. Can anybody help? Thanks. -
Is it possible to remove field from Django admin in certain condition?
I don't want the picture to be editable if it's != 'clear.png' I would like in admin.py to say ## if image != 'clear.png' show only the image tag else show the Picture object class SeeSightsPic(models.Model): class Meta: verbose_name = "Снимка" verbose_name_plural = "Снимки" ordering = ['id' , 'Picture'] SeeSight = models.ForeignKey(SeeSights, blank=False, null=False, verbose_name="Обект", on_delete=models.CASCADE) Picture = models.ImageField(default='clear.png',upload_to='seesights/',verbose_name="Снимка", blank=True, null=True) def image_tag(self): return mark_safe('<img src="{}" width="auto" height="150" />'.format('/media/'+str(self.Picture))) image_tag.short_description = 'Image' and admin.py class SeeSightsPicInline(admin.TabularInline): model = SeeSightsPic ## if image != 'clear.png' show only the image tag else show the Picture object fields = ('image_tag', 'Picture',) readonly_fields = ('image_tag',) -
Avoiding multiple inclusions of javascript in django templates
I am trying to work out the best way to include custom javascript functions in my django project in a DRY manner. I started off including the javascript in a element at the base of my django templates. This resulted in multiple duplication and very un-DRY code. Next, I placed a 'js' folder in my template directory and placed library_name.js files in it to be {% include %} -ed in my django templates as needed. However, as some of my django templates include other html templates (I have a template specifically for modals for example), on occasion a javascript library is loaded multiple times (when a page has multiple modals populated on rendering or populated on opening via an ajax call). This has proved to be problematic as some of these identical javascripts fire simultaneously when I click on a page element, as the element's ID matches the criteria for all of their .click functions. What is the best way to avoid javascript repeatedly loading? One option I considered was having the django template engine track whether a library has previously been loaded. This approach would have involved having the template engine set a variable named after each library to …