Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF, modelSerializer related nested tables
I am trying to serialize related tables but can't manage the include nested table's nest. Let's say. I have a Project model. class Project(models.Model): project_name = models.CharField(max_length=255) path = models.CharField(max_length=50) def __str__(self): return self.project_name and this project model has many relationship with the Plan model. class Plan(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="plans") ... ... def __str__(self): return self.type everything is fine. 'till here I am serializing the project table with the nested Plan BUT Plan model has hasMany relationship too (with the PlanImage model) class PlanImage(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE, related_name="plan_images") ... ... So in my serializers.py if I do: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ["id", "project_name", "path", "plans"] depth = 1 Project has coming with the nested Plan table but. in the Plan table, of course there is no PlanImage table. I checked the DRF docs but couldn't find the way. How can I include PlanImage into Plan? -
Why error 500 raise when I use domain.com instead of domain.com/en/ in Django i18n?
I added a second language to my Django project and when in Debug=False mode I enter domain.com I get ERROR 500 but domain.com/en/ works perfectly. In Debug=True there is no error. My i18n settings: LANGUAGE_CODE = 'fa' LANGUAGES = ( ('fa', _('Persian')), ('en', _('English')), ) My template: {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <div class="languages"> <ul class="languages"> {% for language in languages %} <li class="languages"> <a href="/{{ language.code }}/" {% if language.code == LANGUAGE_CODE %} class='selected'{% endif %}>{{ language.name_local }}</a> </li> {% endfor %} </ul> </div> -
tensorflow.python.util.tf_export.symbolalreadyexposederror: symbol name_scope_v1 is already exposed as ()
Iam trying to set up theano backend for keras in my django server.And i got this error.I have no idea about this error please help me. here is link for full error i got in my server [error log][1].iam using pythonanywhere hosting. [1]: https://pastebin.com/DUjgKpL6 -
Django: how to set up the site name and show it at the end of all pages title
For example, there are 3 html templates with different titles: <title>Page1</title> <title>Page2</title> <title>Page3</title> How to append all the titles with the site name at the end using variable (or other ways)?: <title>Page1 - {{Here is the configurable Site Name}}</title> <title>Page2 - {{Here is the configurable Site Name}}</title> <title>Page3 - {{Here is the configurable Site Name}}</title> -
Django: Got an unexpected keyword argument 'filtered_relation'
I got an issue when trying to union 2 custom Queryset with join_to in Django. Here the syntax I used when union 2 Querysets: output_qs = output_qs | exclude_qs Then the error by executing the code above: TypeError: init() got an unexpected keyword argument 'filtered_relation' Info: 2 Querysets are selecting on the same model and the same custom join_to -
I closed the tag but i get TemplateSyntaxError: Unclosed tag on line 9: 'if'. Looking for one of: elif, else, endif
keep getting this error: TemplateSyntaxError: Unclosed tag on line 9: 'if'. Looking for one of: elif, else, endif. line 9 is: {% if users %} and I believe I close it on line 20 with: {$ endif %} here's the html code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Users</title> </head> <body> <<h1>Here are your users for AppTwo:</h1> {% if users %} <<ol> {% for person in users %} <<li>User Infor</li> <<ul> <<li>First Name: {{ person.first_name}}</li> <<li>Last Name: {{ person.last_name}}</li> <<li>Email: {{ person.email }}</li> </ul> {% endfor %} </ol> {$ endif %} </body> </html> the error message highlighted when running python manage.py runserver is: "GET /users/ HTTP/1.1" 500 126895 thus i believe perhaps its having problems when accessing the script in another file.. here is the views.py file: from django.shortcuts import render from appTwo.models import User # Create your views here. def index(request): return render(request, 'appTwo/index.html') def users(request): user_list = User.objects.order_by('first_name') user_dict = {'users':user_list} return render(request,'appTwo/users.html',context=user_dict) here is models.py file: from django.db import models # Create your models here. class User(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email = models.EmailField(max_length=264,unique=True) here is my urls.py file: from django.conf.urls import url from appTwo import views urlpatterns = [ url(r'^$',views.users,name='users') ] any help would … -
I want to find that user using email data sent to django
My current code is like this. class testAPI(generics.GenericAPIView): serializer_class = testSerualizer def post(self, request, *args, **kwargs): email2 = request.data.getlist('email') test = User.objects.filter(email=email2) print('test : ', test) return Response( { "email": test, "gogogo": "gogogo", } ) python terminal ( test = User.objects.filter(email=email2) ) System check identified no issues (0 silenced). September 17, 2020 - 12:24:16 Django version 3.1, using settings 'web.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. test : <QuerySet []> [17/Sep/2020 12:24:32] "POST /api/auth/test/ HTTP/1.1" 200 38 python terminal ( test = User.objects.filter(email='emailtest@email.com') ) System check identified no issues (0 silenced). September 17, 2020 - 12:11:28 Django version 3.1, using settings 'web.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. test : <QuerySet [<User: test1>]> [17/Sep/2020 12:11:28] "POST /api/auth/test/ HTTP/1.1" 200 4 It appears like test : <QuerySet []> despite passing the correct data. I want to solve this phenomenon. Thanks to those who helped. If the data type is different, can you please tell me how to fix it? -
Any alternative of django_braces?
I want to used SuperuserRequiredMixin fron django braces which is one of the clean way to perform the task but there are multiple dependency issue with this package for Django3.0. I found these two, there might be other as well. from django.utils.functional import curry, Promise ImportError: cannot import name 'curry' from 'django.utils.functional' (C:\Users\vivek\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py) File "C:\Users\vivek\AppData\Local\Programs\Python\Python37-32\lib\site-packages\braces\views_ajax.py", line 8, in from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (C:\Users\vivek\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils_init_.py) I know that there are alternative such as package 'Six' and functools.partial for curry but if there are any other package or any other clean way to perform django braces then it will be very helpful thanks in advance -
data-role= tagsinput is not changing tag when click enter in Django forms
i am trying to get a tag input in django form. I have create a input type text and set data-role as tagsinput. But when i click enter it is not giving me any tags. May i know what is the problem? This is how i add input in form. These are the links. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter- bootstrap/2.3.2/css/bootstrap.min.css"> <link rel="stylesheet" href="bootstrap-tagsinput.css"> These are scripts. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="bootstrap-tagsinput.min.js"></script> <script> $("#write-form").submit(function(e){ e.preventDefault(); }) # i add this because when i click enter it refresh page. $('input').tagsinput({ confirmKeys: [13, 32, 44] maxTags: 8 }); </script> -
Django view - switch login_required on and off
I have a Django application, some view functions have a @login_required mixin and permissions to access. In some site installations, admin want to switch off the login required and permissions for some functions, to make it public. What is the best way, from site configuration? -
Python : import csv ignoring single comma
i have a csv file below which works fine: Test Case ID,summary TC-16610,“verify that user is able to u_pdate 'active' attribute 'false ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'true'” TC-16609,“verify that user is able to u_pdate 'active' attribute 'true ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'false'” But if i add single comma it fails to parse: Test Case ID,summary , TC-16610,“verify that user is able to u_pdate 'active' attribute 'false ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'true'” TC-16609,“verify that user is able to u_pdate 'active' attribute 'true ' on adding “new category records” using 'v3/definition/categories' PUT API on specifying the 'active' attribute 'false'” i want to parse csv file even while having single comma in it. either it should skip and parse or validate to parse. can anyone help me with this. My code... i am using this in django : class CsvUpload(forms.Form): csv_file = forms.FileField() def clean_csv_file(self): # Probably worth doing this check first anyway value = self.cleaned_data['csv_file'] if not value.name.endswith('.csv'): raise forms.ValidationError('Invalid file type') try: data = pd.read_csv(value.file, encoding = 'ISO-8859-1', … -
Django Admin With Docker Error Incorrect padding
When I try to access to my Django admin site With Docker I got the following error: but With out Docker , it can work How to fix this? docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" Dockerfile FROM python:3 ENV PYTHONUNBUFFERED l RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ requirements.txt Django==2.2 Does anyone have some ideas or same issue? Thanks! -
Creating a model ChoiceField that relies on another model in Django
I'm new to Django but I'm trying to replace the categories constant with the types of videos from the other model, VideoTypes. How would I do this? from django.db import models # from django.contrib.auth import get_user_model # User = get_user_model() CATEGORIES = ( ('Executive Speaker Series', 'Executive Speaker Series'), ('College 101', 'College 101'), ('Fireside Chat', 'Fireside Chat'), ('Other', 'Other') ) # Create your models here. class VideoType(models.Model): type = models.CharField(max_length=255) def __str__(self): return self.type class Video(models.Model): title = models.CharField(max_length=255) link = models.CharField(max_length=1000) category = models.CharField(choices=CATEGORIES, max_length=255) timestamp = models.DateTimeField(auto_now_add=True) # owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title -
ImportError: cannot import name 'Bio' from partially initialized module 'bios.models' (most likely due to a circular import )
First app models.py file from django.db import models from projects.models import Project class Bio(models.Model): name = models.CharField(max_length=200,null=True,blank=True) project = models.ManyToManyField(Project,blank=True) number = models.CharField(max_length=11,default=None,null=True) text = models.TextField(max_length=280) def __str__(self): return self.name 2nd app model.py file from django.db import models from django.contrib.auth.models import User from bios.models import Bio from django.conf import settings class Project(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(User, on_delete=models.CASCADE,null=True) bio = models.ManyToManyField(Bio) desc = models.TextField(max_length=200) def __str__(self): return self.name I am getting a circular import error. How to resolve this ???? My Aim is to create a project that has many to many relations with bio and I want bio to show project Thanks in Advance -
I want to do user finder using python django
class ForgotidAPI(generics.GenericAPIView): serializer_class = ForgotidSerualizer def post(self, request, *args, **kwargs): Email = request.data.getlist('email') First_name = request.data.getlist('first_name') test = User.objects.get(email=Email) print('e-mail : ', Email); print('your name' : , First_name); print('test : ', test) return Response( { "email": "test", "first_name": "test", } ) I would like to compare the saved emails to the emails I sent and print the user accordingly. Only the statement'test = User.objects.get (email = Email)' is not executed. How do you run it? -
unable to remove white space from HTML view with Bootstrap
I'm having an issue with the template view below. I've added a scrollbar to the "Used in" table at the bottom, however I am getting a lot of whitespace underneath it. When I try removing each div/element one by one the issue seems to come from that table alone. view.html {% extends "includes/base.html" %} {% load crispy_forms_tags %} {% block body %} <div class="container-fluid"> <div class="row"> <div class="col"> <form method="POST"> <br> {% csrf_token %} {% crispy partform %} </form> <br> <table class="table table-hover"> <tbody> {% for comment in partcomments %} <tr> <td>{{ comment }}</td> </tr> {% endfor %} </tbody> </table> <form method="POST"> <br> {% csrf_token %} {% crispy commentForm %} </form> <div> {% for image in images %} <img class="center img-responsive" src="{{ image.image.url }}" style="height: 25%"/> {% endfor %} <br> <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ imageform.as_p }} <button type="submit">Upload</button> </form> </div> </div> <div class="col"> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table class="table table-hover mb-0"> <thead> <tr> <th>Supplier</th> </tr> </thead> <tbody> {% for supplier in partsuppliers %} <tr data-href="{% url 'info_supplier' supplier.supplier.id %}"> <td>{{ supplier }}</td> </tr> {% endfor %} </tbody> </table> </div> <a class="btn btn-secondary btn-sm btn-pad" href="{% url 'addpartsupplier' part_id=part_id %}" role="button">Add Supplier</a> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table class="table table-hover mb-0"> … -
Chartjs not appearing when sending data to PostgreSQL
My program is supposed to get the system performance data from psutils through flask and display it on a Django webpage using Chartjs. The data is intended to be stored in postgreSQL. However only one of it works. If I return insert_call(), the webpage does not load but data will be sent to the database. If I remove the return, no data sent as expected but the webpage appears. I have tried to place insert_call outside the "def cpu_monitor" but does not work too. views.py # imports import datetime import schedule from django.shortcuts import render import requests from django.http import HttpResponse from .models import Usage import numpy as np # load html page to display Chartjs def cpu_monitor(request): # execute the call function upon loading chart.html insert_call() return render(request, "chart.html") # gather data from Flask for cpu, memory and network usage def monitor(request): # request data from Flask url1 = "http://127.0.0.1:5000/cpu" url2 = "http://127.0.0.1:5000/memory" url3 = "http://127.0.0.1:5000/inb" url4 = "http://127.0.0.1:5000/oub" # storing received data cpu_data = requests.get(url1) memory_data = requests.get(url2) ib_data = requests.get(url3) ob_data = requests.get(url4) # converting stored data to json format cpu_data2 = cpu_data.json() memory_data2 = memory_data.json() ib_data2 = ib_data.json() ob_data2 = ob_data.json() # extracting only the value … -
After update data with ajax i lose a property in a bootstrap button and a modal doesn't work
I'm working on a project with django and for ajax calls take as an example the project of: https://pypi.org/project/django-bootstrap-modal-forms/ I have a table where with the button Ver Tratamiento I can show the information of a treatment through a modal. Likewise, if a treatment does not have an end date, the Cerrar Tratamiento button is disabled. This is what I see when I click the Ver Tratamiento button: And here you can see the buttons to Cerrar Tratamiento button disabled: The problem is that when I close a treatment, the information is saved correctly in the base, and it returns to the template, but if I want to see the treatment again when I click the button to see treatment the modal does not appear, and if I see the closing buttons, those that were previously disabled are now enabled. This is what happens after saving the treatment lock: This is the function I use to close the treatment: function cerrarTratamientoModalForm() { $(".cerrar-tratamiento").each(function () { $(this).modalForm({ formURL: $(this).data("form-url"), asyncUpdate: true, asyncSettings: { closeOnSubmit: true, successMessage: asyncSuccessMessage, dataUrl: "/tratamientos/{{paciente.id}}", dataElementId: "#tablaTratamiento", dataKey: "table", addModalFormFunction: cerrarTratamientoModalForm } }); }); } cerrarTratamientoModalForm(); And this is the function with which I handle the content … -
Adding deep learning model at django
enter image description here ml: django app folder test: pytorch python code folder --predict.py(model) And I wanted to use procees function that i made at predcit.py at views.py process function def process(): for img_file in os.listdir('C:\\Users\\user\\Desktop\\model\\project\\ml\\test\\images'): img_path = os.path.join('images', img_file) predition = predict_breed_transfer(model, img_path) print(predition) print("image_file_name: {0}, \t predition breed: {1}\n\n".format(img_path, predition)) return (predition) views.py at ml folder from django.shortcuts import render from .test.predict import * def predict(request): pred=process() return render(request, "predict.html",{'pred':pred}) When i run the server at my local computer, it gets pred as none. I don't understand why views.py doesn't run 'predict_breed_transfer'function... -
How we patched Django to keep users logged in between sessions
We had a problem with a website which uses Django. Each time we upgrade Django, if a user is logged in with two or more different browsers, and then they login again from one browser - they are automatically logged out from all other sessions (browsers). Since we upgraded Django to new major versions about 5 times in the last year, this caused us a headache. We don't want to force users to have to login again and again between sessions. How can we solve this problem? -
React JS Frontend with DRF backend authentication
Have developed a pretty decent API utilizing Django and Django Rest Framework to make my data available for consumption. Decided to build a React JS front end to be a little more dynamic than the standard Django templates. I have numerous views within DRF which work fine, I'm able to make calls against them and get or post to them no problem. Currently I'm working on implementing a login capability for the React frontend so that users will be given access to a couple protected views and will be presented with information relevant to them. Maybe I'm not understanding what is supposed to be happening, web development isn't exactly my area of expertise. Have referenced the Django documentation a bunch trying to understand sessions and session authentication. I have a 'login' view which is taking a username and password provided to it, searching for a related 'User' record based off of the username and attempting to leverage the django.contrib.auth login method; this all seems to be working, the user is getting authenticated. After this step, I'm pretty much completely lost as to what is supposed to happen. In my React component, I've attempted sending the username as a 'session' attribute … -
Django-Tenants Search Among All Schemas from a public Schema
I am using Django-tenants and was wondering how to access/search among all schemas ? Is it possible? Whats the best approach? Any hints or links to resources will be much appreciated. -
django file upload error The 'image' attribute has no file associated with it
I getting error after the file upload with dropzone. I guess due to file is not uploaded. ValueError at /ui/project_detail/4/ The 'image' attribute has no file associated with it. my view function snippet: @csrf_exempt def project_image_alternative_form_submit_ajax(request, object_id): project_image = ProjectImage.objects.filter(pk=object_id).first() if not project_image: response_json = { 'message': 'Image you provided pk for doesnt exist!', } return JsonResponse(response_json, status=status.HTTP_400_BAD_REQUEST) if request.method == 'POST': if request.is_ajax(): image_file = request.FILES.get('image_file') project_image_alternative = ProjectImageAlternative( project_image=project_image, image=image_file, ) project_image_alternative.save() response_json = { 'message': 'Alternative Image saved successfully!', 'image_alternative_pk': project_image_alternative.pk } return JsonResponse(response_json, status=status.HTTP_200_OK) else: response_json = { 'message': 'Please send a POST request', } return JsonResponse(response_json, status=status.HTTP_400_BAD_REQUEST) return JsonResponse(response_json, status=status.HTTP_200_OK) my dropzone function snippet: $('.alternative_image_upload').dropzone({ maxFiles: 1, autoProcessQueue: true, parallelUploads: 1, headers: { 'Cache-Control': null, 'X-Requested-With': null, }, error: function(file, response, xhr) { if (typeof xhr !== 'undefined') { this.defaultOptions.error(file, xhr.statusText);// use xhr err (from server) } else { this.defaultOptions.error(file, response);// use default (from dropzone) } }, sending: function(file, xhr, formData) { var pk = this.element.dataset['pk']; formData.append('pk', pk); }, init: function() { this.on("success", function(file, response) { console.log(response); }); }, uploadMultiple: false, acceptedFiles: '.jpg, .jpeg, .png, .svg' }) -
Django - Temporary midi file
Sorry if I'm not getting something right, I am new to web application development, I've been working on a project with Django and I wish I could do the following: When the user clicks on a button an Ajax request is generated (I am using plain Javascript). This request sends some notes to the server (Django) that generates a melody. The server saves the melody in a midi file that I want the user to be able to listen to in the front-end like this: <midi-player src = "url/path/to/temporaryfile" sound-font visualizer = "#myVisualizer"> </midi-player> <midi-visualizer type = "staff" id = "myVisualizer"> </midi-visualizer> I want this file to be temporary so that it does not take up space, that is, that the user can listen to the melody, have the option to download it, etc, but that when they leave the page, the file is deleted and thus does not take up more space . Is this the best way to do what I think? -
Fetch all Django objects that have a M2M relationship
I have the following two Django models: class Parent(models.Model): name = models.CharField(max_length=50) children = models.ManyToManyField("Child", through="ParentChild") def __str__(self): return self.name class Child(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name Let's say I have four Parent objects in my database, only two of which have children: for parent in Parent.objects.all(): print(parent, parent.children.count()) # Parent1 3 # Parent2 0 # Parent3 0 # Parent4 1 My goal is to write an efficient database query to fetch all parents that have at least one child. In reality, I have millions of objects so I need this to be as efficient as possible. So far, I've come up with the following solutions: Using prefetch_related for parent in Parent.objects.prefetch_related("children"): if parent.children.exists(): print(parent) # Parent1 # Parent4 Using filter: for parent in Parent.objects.filter(children__isnull=False).distinct(): print(parent) # Parent1 # Parent4 Using exclude: for parent in Parent.objects.exclude(children__isnull=True): print(parent) # Parent1 # Parent4 Using annotate and exclude: for parent in Parent.objects.annotate(children_count=Count("children")).exclude(children_count=0): print(parent) # Parent1 # Parent4 Which of these solutions is the fastest? Is there another approach that's even faster / more readable? I'm seeing a django Exists function but it doesn't appear to be applicable for this use case.