Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MongoDB with Django
I have a mongoDB which contains scraped data. I want to import that data in my django project and display it accordingly. How do I access that data? I used djongo package and changed my settings and then ran the migrations. But it has resulted in the creation of a new database. How can I approach this issue? -
Prefetch querysets cannot use values
i want to make the follow query for get a queryset with this characteristic: pre-filtered grouped by name sum the inner data in my code i have: q = DatiBanca.objects\ .filter(is_negativo=False)\ .values("istituto_credito__name")\ .order_by("istituto_credito__name") anagrafiche = anagrafiche.prefetch_related( Prefetch('dati__banche', queryset=q) ) dataset JSON: "dataset": { "id": 40, "banche": [ { "id": 18396, "name": "Pippo", "importo": "10", "istituto_credito": 3, "is_negativo": false }, { "id": 18397, "name": "Pippo", "importo": "20", "istituto_credito": 3, "is_negativo": false }, { "id": 18398, "name": "Pippo", "importo": "999999999999", "istituto_credito": 3, "is_negativo": true }, { "id": 16519, "name": "Pluto", "importo": "40", "istituto_credito": 5, "is_negativo": false }, { "id": 13967, "name": "Paperino", "importo": "50", "istituto_credito": 4, "is_negativo": false } ] } this query give me belows error: "Prefetch querysets cannot use values()." how can i get following result from dataset? "dataset": { "id": 40, "banche": [ { "name": "Pippo", "importo": "30", "istituto_credito": 3, "is_negativo": false } { "name": "Pluto", "importo": "40", "istituto_credito": 5, "is_negativo": false }, { "name": "Paperino", "importo": "50", "istituto_credito": 4, "is_negativo": false } ] } I use django 2.1.5 -
Adding item into database without inputting in the text box
I am trying to figure out how to insert a default item which is "Item Code" into my 'List' database instantaneously after clicking the add button. I only managed to do is insert the string/char that I have entered in the text box. Though, when I click the 'add' button without typing in anything inside the text box, I get this error: ValueError at / The view home.views.index didn't return an HttpResponse object. It returned None instead. Here are my codes so far: models.py from django.db import models from django.utils import timezone class List(models.Model): item = models.CharField(max_length=200) date = models.DateTimeField(default = timezone.now) def __str__(self): return self.item views.py from django.shortcuts import render from .models import List from .forms import ListForm from django.contrib import messages def index(request): context = { 'items': List.objects.all() } if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, ('Item has been added to the list.')) return render(request, 'home/index.html', context) else: return render(request, 'home/index.html', context) forms.py from django import forms from .models import List class ListForm(forms.ModelForm): class Meta: model = List fields = [ 'item', 'date' ] index.html <h1>To do list</h1> {% if messages %} {% for message in messages %} <p> {{ message }} … -
Django login in iFame not saving login info
I have a django app that is embedded in another django app using iframe it works fine for most pages but when trying to enter a @login_required view sends me to log in (which is normal) but when login sends me back to login as is the POST info doesn't save the login request. any ideas? Thanks. in order to even work with no login required view, I disabled the 'django.middleware.clickjacking.XFrameOptionsMiddleware' not sure if it has to do, from reading maybe something with cookies even tho I can see it in the host app maybe is not sending it or the iframe cant access cookies from the parent or host app. -
How can I use django-session-security in my project
What are the steps that I need to follow to run the 'django-session-security' for show warning to the user before session expire. I check on its official documentation but not able to understand exactly how to setup the things. -
Filtering on one in a many-to-many relationship in django
I've two objects teams and tournaments, class Tournament(Base): name = models.CharField(db_index=True, max_length=255) tournament = Tournament.objects.get(id=kwargs.get('tournament_id')) class Team(Base): name = models.CharField(db_index=True, max_length=255) tournaments = models.ManyToManyField(Tournament) Now I want to filter teams in one specific tournament tournament = Tournament.objects.get(id=kwargs.get('tournament_id')) teams = Team.objects.filter(tournament=tournament) // This doesn't work. How do I do this. Any help appreciated -
Testing legacy database in Django 2.1
I'm writing an app which uses a legacy database (with managed=False) for some of the models, and have been trying to find a way to test them (as the usual testing won't work since it won't allow table creation). I have tried all of the workarounds I could find but the most recent was from 2017 and referred to a much older version of Django. Does anyone know a way to perform tests on legacy databases with unmanaged models in the current version of Django (2.1)? -
How to add a value to a field in the same model when the model is saved - django admin
I have a django model that looks like this... class Account(models.Model): account_name = models.CharField(max_length=100) deposited_amount = models.PositiveIntegerField(default=0) opening_balance = models.IntegerField(default=0) current_balance = models.CharField(max_length=9) Inside my admin.py file, I have the current_balance field set to readonly. I would like the current balance to be the sum of deposited_amount and opening_balance hence I have implemented a signal to try and handle that... @receiver(post_save, sender=Account, dispatch_uid="update_current_balance") def update_current_balance(sender, **kwargs): created = kwargs['created'] instance = kwargs['instance'] if created: instance.current_balance = F('deposited_amount') + F('opening_balance') Creating new accounts works fine but the current_balance doesn't get updated. What am I missing here? Also, I'm thinking that in the event that either the deposited amount or opening_balance is updated, I will need the current balance updated too so should I maybe remove the if created check, or do I create another signal? -
How can I call model method from template by passing parameters
Whenever i need a full collection of info I can pass through context data to template but when I need to collect data from a loop running in template by passing any id to other table and make query to get specific info of that each individual id how to do it in Django. In php we can run query from template by passing parameters that thing how to do it in django. -
Django form is not bounded when submitted
I have a form for user to search based on grade, subject and year. The grade fields prepopulated at initialization while subject and year are populated based on the grade selection for subject and subject selection for year. Index view process the form and if valid send to another view. However, it seems the form cannot be bound for some reason. Thanks in advance in form.py class SearchForm(forms.Form): grade = forms.ModelChoiceField( queryset =Grade.objects.all(),to_field_name="grade",required=False) subject = forms.ModelChoiceField(queryset=Subject.objects.none(), required=True ) year = forms.ModelChoiceField( queryset=Exam.objects.none(), required=True ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) index.html <form id="searchForm" action="" method="POST" data-url-types="{% url 'exam:subjects_choices' %}" data-url-years="{% url 'exam:years_choices' %}" novalidate> {% csrf_token %} <div class="row"> <div class="col-xs-6"> {{ form.grade}} </div> <div class="col-xs-12"> {{ form.subject}} </div> <div class="col-xs-6"> {{ form.year }} </div> </div> <button class=" type="submit">Search</button> </form> JS follows views.py def index(request): if request.method == "POST": form = SearchForm(request.POST) # A form bound to the POST data if form.is_valid():# All validation rules pass grade=form.cleaned_data['grade'] subject=form.cleaned_data['subject'] year=form.cleaned_data['year'] return redirect('taketest','grade':grade,'subject':subject, 'year':year}) # Redirect after POST else: form = SearchForm() return render(request, 'index.html', { 'form': form}) ExamTake(Formview) def dispatch(self, request, *args, **kwargs): subject=request.POST.get('subject') grade=request.POST.get('grade') year=request.POST.get('year') slugfield='-.join(subject,grade,year)' # eg. history-10-2012 self.exam = get_object_or_404(Exam,slug=slugfield) urls.py re_path(r'taketest/(?:grade=(?P<grade>\d{2})).*?(?:subject=(?P<subject> [\w]+)).*?(?:year=(?P<year>\d{4}))',ExamTake.as_view(), name='taketest'), The exam model has … -
circular import caused error when i start django server
So I try to run the this project I've been working on it's a simple Django blog but when i try to start the server i get the following error: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001A861F736A8> Traceback (most recent call last): File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 535, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 542, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from 'E:\\Projects\\Python\\web applications\\Django Simple Blog\\simple_blog\\blog\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. this … -
How do I make a POST request from within a django function to rest api?
I have xyz.py file. In this file I have a function @api_view(['POST']) def abc(request): which can be accessible at a url, say /algorithms/abc. I have another function def pkr(): I want to make POST request from this function to abc(request). I tried requests.request('POST', "/algorithms/abc", data=data_input) but the request.data at abc(request) is received as QueryDict (& not dict) & looses some texts that existed in data_input inside pkr() function. -
How to fix 'XXXSerializer is not defined' in Django although it is defined
I am learning Serialization with the Django Rest Framework. But when I defined the serializers, I got the "XXXSerializer is not defined" as error. So, in my project, I have 2 models: a CustomUser and a Clique. The relationships should be: A CustomUser can be the founder of many Clique objects but each Clique object has only one CustomUser as its founder. A CustomUser can a member of many Clique objects and each Clique can have more than one CustomUser as members. My models.py: class CustomUser(AbstractUser): created = models.DateTimeField(auto_now_add=True) job = models.CharField(max_length=100, blank=False) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Meta: ordering = ('created', ) class Clique(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) founder = models.ForeignKey(CustomUser, on_delete=models.CASCADE) members = models.ManyToManyField(CustomUser) def __str__(self): return self.name class Meta: ordering = ('created', ) My serializers.py: class CustomUserSerializer(serializers.HyperlinkedModelSerializer): # this line causes the error. I know that CliqueSerializer is defined below. owned_cliques = CliqueSerializer(many=True, read_only=True) class Meta: model = CustomUser fields = ('url', 'id','username', 'first_name', 'last_name', 'job','owned_cliques', 'clique_set') class CliqueSerializer(serializers.HyperlinkedModelSerializer): members = CustomUserSerializer(read_only=True, many=True) class Meta: model = Clique fields= ('id', 'name', 'members',) As result, I get "NameError: name 'CliqueSerializer' is not defined" error. There seems to be a dependency problem. … -
Avoid success_url in Class based View DJango
I don't want to call my success_url after saving of object. Actually, i am calling this class for saving data in a popup. It has a seperate page (addLocation). Naturally, i don't want to recall my base page (addDevice) which makes the form empty and the user has to refill the form again. views.py class AddLocationV(PassRequestMixin, SuccessMessageMixin, generic.CreateView): template_name = 'devices/addLocation.html' form_class = AddLocation success_message = 'New location has been added' success_url = reverse_lazy('addDevice') def form_valid(self, form): form.instance.created_by = self.request.user.id return super().form_valid(form) -
Django-Helpdesk change order of public ticket
In the django-helpdesk package I am trying to change the order of the public facing ticket entry and basically just use a custom form. I added a custom field but it keeps adding to the very bottom of the ticket. A ticket made of entirely custom fields would be fine, I know it is not searchable but I just need a quick way to spin up a customized ticket. What file(s) in django-helpdesk would I need to edit, modify or override to make a custom ticket? -
DJANGO Serializer Validation Never Called
I am trying to run custom validation on a serializer in Django. The serializer is as simple as: class PostsSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, required=False, allow_null=True) def validate(self, data): print('Validating') print(data) return data class Meta: model = Post fields = ["id", "user", "type", "title", "content", "created_ts"] read_only_fields = ["id", "user", "created_ts"] And the serializer is called as such: def create_post(self, request): serializer = PostsSerializer(data=request.data) if serializer.is_valid(raise_exception=True): #echo something else: fail And the model is this: from django.apps import apps from django.db import models from ..enums import PostTypes class Post(models.Model): user = models.ForeignKey("auth.User", on_delete=models.DO_NOTHING) type = models.IntegerField(choices=[(tag.name, tag.value) for tag in PostTypes]) title = models.TextField() content = models.TextField() class Meta: db_table = "post" ordering = ["-created_ts"] verbose_name = "Post" verbose_name_plural = "posts" Any idea what would be causing the validate function not to execute? -
ImportError: cannot import name 'safe_join'
I want to upload my static files to AWS CloudFront through s3. I have this error : ImportError: cannot import name 'safe_join' when running python manage.py collectstatic I am using Python 3.6 and Django 2x. django-storage-redux is installed, boto3 and botocore too. here is my settings.py : import os from django.utils.translation import ugettext_lazy as _ import boto3 ... # AWS CloudFront AWS_S3_REGION_NAME = 'us-east-2' # e.g. us-east-2 AWS_ACCESS_KEY_ID = '****' AWS_SECRET_ACCESS_KEY = '***' AWS_S3_HOST = 's3-us-east-2.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=1209600, no-transform' } # static BUCKET_STATIC_NAME = '***' CLOUDFRONT_STATIC_DOMAIN = '***' # media BUCKET_MEDIA_NAME = '***' CLOUDFRONT_MEDIA_DOMAIN = '***' # storage DEFAULT_FILE_STORAGE = 'elef.custom_storage.CachedStaticS3BotoStorage' STATICFILES_STORAGE = 'elef.custom_storage.MediaS3BotoStorage' MEDIA_URL = 'https://%s/' % CLOUDFRONT_MEDIA_DOMAIN ... here is my custom_storage.py : from storages.backends.s3boto3 import S3Boto3Storage import boto3 from django.conf import settings from django.contrib.staticfiles.storage import CachedFilesMixin class CachedStaticS3BotoStorage(CachedFilesMixin, S3Boto3Storage): """ S3BotoStorage backend which also saves a hashed copies of the files it saves. """ bucket_name = settings.BUCKET_STATIC_NAME custom_domain = settings.CLOUDFRONT_STATIC_DOMAIN class MediaS3BotoStorage(S3Boto3Storage): """ S3BotoStorage backend for media files. """ bucket_name = settings.BUCKET_MEDIA_NAME custom_domain = settings.CLOUDFRONT_MEDIA_DOMAIN i can also give you the full traceback: /Users/justine_dev/zapelef/lib/python3.6/site-packages/storages/__init__.py:9: UserWarning: This library has been designated as the official successor of django-storages and releases under that namespace. Please update your … -
How to add Django Language mode in CodeMirror Plugin of CKEditor?
I'm using CKEditor wysiwyg for creating django templating. Therefore, I come across using codemirror plugin for CKEditor as here. By following installation instruction, the following options available for config as refered here: config.codemirror = { // Set this to the theme you wish to use (codemirror themes) theme: 'default', [.......................] // Define the language specific mode 'htmlmixed' for html including (css, xml, javascript), 'application/x-httpd-php' for php mode including html, or 'text/javascript' for using java script only mode: 'htmlmixed', [.......................] // Whether or not to show the showAutoCompleteButton button on the toolbar showAutoCompleteButton: true }; However, as above mode options, the languages are limited to html, javascript, and php, that I could not use another language, for my case Django. I tried to modify the default code mirror plugin of CKEditor at <path to CKEditor>/Plugins/codemirror/plugin.js to add somewhere possible for django language, yet it resulted only in code error. So, how can I do to add Django language in codemirror plugin of CKEditor? Thanks. -
Edit inlinechangelink in admin.TabularInline
I am struggling to access and edit the inlinechangelink in a specific inline: Any idea how I can access/edit this via the admin.TabularInline or template? Thank you very much! -
Django: GenericForeignKey or ForeignKey
I currently have to make the following decision for my model Order: Either I use GenericForeignKey which refers either to the models DiscountModel or AnotherDiscountModel. There can only be one of those, so from the idea GenericForeignKey could make sense. However, I am implementing it somewhere, where performance matters. The alternative approach would be to have to ForeignKey fields in my model: discount_model and another_discount_model. One of them will always be empty. I now wonder which path you would go before I add the "other discount model". Do you have any insights you can share with me? Currently, GenericForeignKey seems a bit more complex to me and I would have to change several parts in my code. -
django.db.utils.DatabaseError: ORA-00904: invalid identifier
I'm running an application on django 1.11 and as an Oracle Database 11G XE database engine. I have 3 tables producto, catalogo and catalogo_producto. The catalogo_producto table is an intermediate table between producto and catalogo. When making the migration of the tables, no problem arises, but when wanting to create an object the following error arises django.db.utils.DatabaseError: ORA-00904: "CATALOGO_PRODUCTO". "ID": invalid identifier. I know that this error refers to the fact that I have not assigned any primary key in the model, but following the django documentation Extra fields on many-to-many relationships for these cases a primary key is not assigned to a specific field. I also understand that django in these cases creates a PK "ID" that is not shown in the models. So I do not know if the correct solution is simply to create an id field in the catalogo_producto table or is there some other solution? models.py class Producto(models.Model): codigo = models.IntegerField(primary_key=True) precio = models.IntegerField() nombre = models.CharField(max_length=100) tipo = models.CharField(max_length=25) cantidad = models.IntegerField() class Meta: db_table = 'producto' def __str__(self): return str(self.codigo) class Catalogo(models.Model): codigo = models.AutoField(primary_key=True) descripcion = models.CharField(max_length=250) fecha = models.DateField() productos = models.ManyToManyField(Producto, through='CatalogoProducto') class Meta: db_table = 'catalogo' def __str__(self): return … -
Creating random URLs in Django
I'm working on a project, I want to code the following steps => The user in page A wants to access to page B, so the user in page A will redirect to page B after validating the form, then : 1) Creating a random url 2) The user is redirected to that random URL 3) the user cant access to page B if he doesn't validate the form on page A I use django 2.1 Thanks for your help :) -
Django translation into custom language works in development but not in production
For the Django project I am working on I created a translation named en-ORGNAME that reflects the specific English jargon at use at the target organization. I use multiple instances of this application for multiple organizations and want to be able to customize the jargon according to the client organization. It started of pretty nice, after running django makemessages -l en_ORGNAME I ended up with a .po file that I could translate. Running compilemessages made sure I have to .mo file as well. The application only uses the LANGUAGE_CODE setting to determine language (no context processor or URLs). The locale path is set to LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'),) When I run the application (using docker-compose and the development server) all works well and my translations show up as expected. However, when I deploy the application (using the same docker image) using Rancher the custom translation stops working. I have used an environment variable to set the language at container level and all other languages work fine. I have tested the same stack in development (NGINX, Gunicorn, Django) and my custom translation works. I have tried adding the custom translation to the django.conf.locale dictionary (as per Add custom language for … -
Django annotate with nested foreign key set filter
Model C has a foreign key link to model B. Model B has a foreign key link to model A. This is, model A instance may have many model B instances, and Model B may have many model C instances. Pseudo-code: class A: ... class B: a = models.ForeignKey(A, ...) class C: b = models.ForeignKey(B, ...) I would like to retrieve the entire list of elements of model A from the database, annotating it with the count of B elements it has, where their respective count of C elements is not none (or any random number, for that matter). I tried this: A.objects.annotate( at_least_one_count=Count('b', filter=Q(b__c__isnull=False)) ) To the best of my knowledge, this should be working. However, numbers returned are not correct (in a practical case). It returns a higher number than without the filter, which is obviously not possible: A.objects.annotate( at_least_one_count=Count('b') ) Note: I would like to perform this query without SQL. If I have to utilise some more advance Pythonic tools that Django provides, I am happy to do it, as long as I stay Object-Oriented. I am trying to move away from using raw SQL for all database operations, and re-write them all with Django ORM. However, … -
How to retrieve and save value from custom star element
I have an HTML star element that records an integer value when clicked; for example, 2 stars clicked = value of 2. I am trying to save that value to my database, but am having trouble doing so. I believe it requires AJAX and have tried utilizing it, but have found no success thus far. Any help would be greatly appreciated. HTML <div class="text-center"> <h2>Rating</h2> </div> <!-- Form --> <form action="{% url 'student:rating' %}" method="POST" autocomplete="off" novalidate> {% csrf_token %} <!-- Review --> <div class="form-group"> <label>Review</label> {{ form.review }} </div> <!-- Stars --> <div class="form-group"> <x-star-rating value="5" number="5" id="stars"></x-star-rating> </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button" onclick="getRating()">Save</button> </div> </form> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <link rel="stylesheet" href="//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link rel="stylesheet" href="{% static 'student/css/rating.css' %}" type="text/css" /> <script src="{% static 'student/javascript/star_rating.js' %}"> . </script> <script> function getRating() { var stars = document.getElementById('stars').value; $.ajax({ method: 'POST', url: '/student/rating/', dataType: 'json', contentType: 'application/json', async: true, data: { stars: $('#stars').val(), }, success: function(data){ results = $(data).find('#stars').html(); }, error: function(){ alert("Error"); }, }); }; Javascript class StarRating extends HTMLElement { get value () { return this.getAttribute('value') || 0; } set value (val) { this.setAttribute('value', val); this.highlight(this.value - 1); } get number () { return this.getAttribute('number') || …