Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass the value from v-for to a simple django filter
I have the following component in a django template <div class="trow" v-for="(item, idx) in data"> </div> Now if I try to write the following inside the div {{ item.co.name }} I won't get the value, I will have to write the following to get the value {% verbatim %} {{ item.co.name }} {% endverbatim %} Now my problem is that I have to do something with this value so I wrote a simple filter like this from django import template from django.templatetags.static import static register = template.Library() @register.filter def define(val=None): return static(f"images/{val.lower()}.svg") but I can't do the following <div class="trow" v-for="(item, idx) in data"> {% verbatim %} {{ item.co.name | define }} {% endverbatim %} </div> I've also tried a lot of combinations with no luck, how can I solve this? -
convert mongoose schema to django model
I have below javascript schema const mongoose = require('mongoose'); const pointSchema = new mongoose.Schema({ timestamp: Number, coords: { latitude: Number, longitude: Number, altitude: Number, accuracy: Number, heading: Number, speed: Number } }); const trackSchema = new mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, name: { type: String, default: '' }, locations: [pointSchema] }); mongoose.model('Track', trackSchema); I'm trying to convert above file to Django models. wondering how to write that locations: [pointSchema] and const pointSchema in my models.py. Is it possible to convert that ? -
Understanding Django to put python web app into a site
I'm trying to create a portfolio to show my python web apps. I've created a github with a main portfolio page that uses an HTML template with my own edits. What I'm trying to do is place each individual project, that I'm working on, into that main site. I understand how to clone github to my VSCode etc. and I understand how to make the front-end side of the website with Django BUT what I am not understanding is how to format the web apps to be used on the site like I hope for. For example, I created a thesaurus project specifically on python (from a course), but I don't understand where or what I code in Django that the user can actually use it. In other words, I'm not finding the answer to create a Charfield (for the user to input) and then it prints into a separate box below it, while using the same python script. What I also can't figure out, is where would my database JSON file (with all the definitions) be stored in order for the user input to print. Or is that already done within the python script that I don't need to … -
How can I update a Django QuerySet, so that it doesn't return cached data?
The QuerySet in my Django ListView view doesn't automatically update when I create a new record in the model. The Django admin updates and the database updates, but the view does not update. I've come to realise that this is happening because the QuerySet is using cached data. To re-execute the QuerySet on a get request, I have unsuccessfully tried various versions of the code below... def get_queryset(self): self.user = self.request.user queryset = Strategy.objects.filter(user=self.user) updated_queryset = queryset.update() return updated_queryset Instead of updating my QuerySet each time the webpage is refreshed, this is returning an empty QuerySet. What do I need to do to update the QuerySet on a GET request? -
ImportError: Couldn't import Django. PYTHONPATH
there was an error 'account.User' that has not been installed But I solved this problem. After that, there was an error 'The SECRET_KEY setting must not be empty.' I don't know whether my method to solve this problem is correct or not, I applied some solutions with Google. But now, there is an error ' ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?' But i already installed django and virtualenv. I don't know how to do it. I spent lots of days recent error Traceback (most recent call last): File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 10, in main from django.core.management import execute_from_command_line File "/Users/leejunseo/PycharmProjects/ITM coding/venv/lib/python3.9/site-packages/django/core/management/init.py", line 12, in from django.conf import settings File "/Users/leejunseo/PycharmProjects/ITM coding/venv/lib/python3.9/site-packages/django/conf/init.py", line 21, in from .base import * ModuleNotFoundError: No module named 'django.conf.base' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 21, in main() File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? MY code manage.py … -
Serialize and Deserialize nested and foreign key with Django Rest Framework
I am creating an Ecommerce website and I am stuck in the backend trying to serialize and deserialize data using Django Rest Framework. Here's my model file from django.db import models # Create your models here. class Company(models.Model): company_name = models.CharField(max_length=200, null=True) def __str__(self): return self.company_name class Category(models.Model): category_name = models.CharField(max_length=100, null=True) def __str__(self): return self.category_name class Tags(models.Model): tag_name = models.CharField(max_length=100, null=True) def __str__(self): return self.tag_name class Product(models.Model): product_name = models.CharField(max_length=999, null=True) product_description = models.TextField(max_length=999, null=True) product_price = models.IntegerField(null=True) product_company = models.ForeignKey(Company,null=True, on_delete=models.SET_NULL) tag = models.ManyToManyField(Tags) category = models.ManyToManyField(Category) product_availability = models.BooleanField(default=True) stocks_count = models.DecimalField(null=True, decimal_places=1, max_digits=3) def __str__(self): return self.product_name Here I have nested Many to Many relationships and Foreign Key relationship which I want to be able to read and write with DRF My Serializers file is as below: from rest_framework import serializers from .models import * class CategorySerializer(serializers.ModelSerializer): def to_representation(self, value): return value.category_name class Meta: model = Category fields = ('category_name',) class TagsSerializer(serializers.ModelSerializer): def to_representation(self, value): return value.tag_name class Meta: model = Tags fields = ('tag_name',) class CompanySerializer(serializers.ModelSerializer): def to_representation(self, value): return value.company_name class Meta: model = Company fields = ('company_name',) class ProductSerializer(serializers.ModelSerializer): tag = TagsSerializer(many=True) category = CategorySerializer(many=True) product_company = CompanySerializer() class Meta: model = Product … -
OAuth server using django-oauth-server
I'm developing a system where I have a central authentication server (using django-oauth-toolkit) for multiple web apps (clients, uses DRF to provide api endpoints to front-end SPA). The auth server will only be for authenticating users, while the api calls from the front-end side will be to the client apps not the auth server. This brings me to the question, If I'm getting access-token from auth server, how can I secure my api endpoints of the app server? In cases where authorization and api calls are on the same server, I would use DRF authentication that handles the creation of access token, but since the token is created by auth server, I was wondering how to handle the access token and api calls to the client. Hope anybody can clarify this. -
Django-React authentication: limit users who can obtain simpleJWT tokens
I have two React frontends for my backend: first one is used by all users, second one is an admin panel which can only be used by is_staff users. What is the best way to limit access using simplejwt tokens? I have overriden TokenObtainPairSerializer to include additional fields like 'is_staff'. So I have two questions: is just checking the is_staff field on the frontend safe enough? Doesn't seem to me like a good idea. if I want to create second API url entry for admin authentication and override authentication logic on backend side to only issue tokens to staff users. What method/class exactly should I override to change this? Is this a good idea? -
fields do not recognise django
I have been having a problem working with formsets in my project and I've been trying to get to the bottom of this. While doing so, a couple of different errors have been appearing. Generally, what I want to do is create an object of entity A (workout) and get redirected to a template/url that lets me "fill" it with objects of entity B, which I will be making at that point dynamically using model formsets. The problem seems to be revolving around the form, more specifically: if I write the fields one by one, as in : CycleFormSet = modelformset_factory( Cycle, fields=('reps', 'place_in_workout', 'exercise', 'number_of_times', 'break_inbetween'), extra=1 ) Then, I get the error: Unknown field(s) (place_in_workout, break_inbetween, reps, number_of_times) when I attempt to run the server. If I use exclude for some field, or do fields = 'all' , then I don't get an error at this point. However, I get the error : ['ManagementForm data is missing or has been tampered with'] when I try to post the data of the workout object. Me code: models.py class Exercise(models.Model): name = models.CharField(max_length=150) description = models.TextField(max_length=500) def __str__(self): return self.name class Workout(models.Model): name = models.CharField(max_length=150, null=True) created_by_user = models.ForeignKey(User, null=True, … -
How to access GreenPlum from Django?
I am doing a Django application that gets data from a Postgres DB. Is there a way to make it use GreenPlum instead? I am using these settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testDB', 'USER': 'postgresUser', 'PASSWORD': 'postgresPasswd', 'HOST': 'localhost', 'PORT': '5432', } } Thanks -
i am trying to import " django.shortcuts import get_objects_or_404" in my django views file but is giving an error
I am getting the folllowing error: from django.shortcuts import render,get_objects_or_404,redirect ImportError: cannot import name 'get_objects_or_404' from 'django.shortcuts' this is the error I am getting in my django project can anyone help me in fixing this -
module 'jwt' has no attribute 'ExpiredSignature'
I have been developing a Django application using graphene/graphql running over AWS using Docker alpine image. I have been using django-grapql-jwt module for calling jwt authentication in my application. Where it is calling ExpiredSignature from PyJWT instead of ExpiredSignatureError. And graphQL is returning "module 'jwt' has no attribute 'ExpiredSignature'" error. How to resolve the issue? -
Embedding Data Tables and Plots in a Local/Private webpage using Dash
This one is a generic question. I know that I can create a dash app from my csv file to the local server ( 127.0.0), but instead of hosting it to that webpage, is it possible to host it to a shared page inside my company which anyone can access whenever they want it to. I may run the code on my machine and in one scheduled run (say per day) the data will be populated and whenever within that day anyone else will access the webpage/dashboard will be able to get that data and see plots/tables etc depending on the application and interactivity. Next day when someone else looks at the data ( that will be new data assuming the code on my machine has run and populated new data). I am finding dash useful but not sure how it can be hosted/embedded into a separate webpage. Any help or ideas or suggestions will be immensely appreciated. -
not able to make entries in mapping table - Python Django
I am trying to create a form with the help of that I can make entries in the table, but I couldn't able to understand the logic what should I do here, the mapping table stores the foreign key references. My code is as shown below: models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size = models.CharField("Product Size", max_length=20, null=False) def __str__(self): return "{size_id}-->{prod_size}".format(size_id=self.size_id, prod_size=self.prod_size) class SizeProductMapping(models.Model): size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True) size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") def __str__(self): return ".`. {}_____{}".format(self.size_id, self.prod_id) here is the function to add data in the table. views.py def sizeProductMap(request): if request.method == 'POST': size_id = request.POST['size_id'] size_id = int(size_id) print(size_id) product_id = request.POST['product_id'] product_id = int(product_id) print(product_id) sizeProductMap_update = SizeProductMapping(size_id=size_id, prod_id=product_id) sizeProductMap_update.save() return redirect('/admin1/productSize') else: sizeProductMap_show = SizeProductMapping.objects.all() # start paginator logic paginator = Paginator(sizeProductMap_show, 3) page = request.GET.get('page') try: sizeProductMap_show = paginator.page(page) except PageNotAnInteger: size_show = paginator.page(1) except EmptyPage: sizeProductMap_show = paginator.page(paginator.num_pages) # end … -
Creating Static Htmpl pages containing Tables and Plots from csv files in Python
I have a generic question here. Not a related code or trouble shooting issue. I will have csv files which I will have as data tables with multiple columns. I am looking to generate different group statistics (from different columns) and plots among the data columns. What I want is to create html files for the plots and the tables ( all in a static format) and host them to a private website ( which is of my choice ). What is the best platform to do that in python? I am seeing many different options when I search ( flask/django/react in python ) and shiny in R etc but not understanding what to do. The object is to have html files and put it to a website with tabs etc ( for multiple html files) How to do that? -
Changing attributes in Django Login Form
I am following a tutorial for Login in Django and after finishing I found that the Login Form requires the USername and Password but I want to replace the username with the user's Email instead. Here is the views.py @login_required def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) Here is the forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] Here is the template <form style="padding: 30px 38px 27px 38px;" class="login100-form validate-form" method="POST"> <span class="login100-form-title p-b-34"> Account Login </span> <fieldset class="input100 m-b-20"> {% csrf_token %} {{ form|crispy }} … -
ValueError -- Django search form: Multiple select field with foreign key
I would like a search form for a model which results in a table with filtered view. Started out using django-tables2 and django-filter to achieve this. It all works fine. However, when I try to change a select field for a foreign key into a multiple select field, then I start running into issues. E.g., ValueError: Cannot assign "<QuerySet []>": "Test.library" must be a "Library" instance. ValueError: Cannot assign "<QuerySet [<Library: my lib!>, <Library: hmm>, <Library: a's lib>]>": "Test.library" must be a "Library" instance. Any tips? With the form, table, and filter, it's all a little confusing. # models.py class Library(models.Model): some_title = models.charField() class AbstractTest(models.Model): some_value = models.charField() library = models.ForeignKey( 'Library', on_delete=models.CASCADE) class Test(AbstractTest): another_value = models.charField() # forms.py class TestSearchForm(forms.ModelForm): # library should display as a muliple select field # do it here? library = forms.ModelMultipleChoiceField( queryset = Library.objects.all(), to_field_name = "title", required = False ) class Meta: model = Test widgets = { # library should display as a muliple select field # do it here? 'library': forms.SelectMultiple(), } # filters.py class SpectraFilter(django_filters.FilterSet): # library should be a multiple select filter library = django_filters.ModelMultipleChoiceFilter( queryset = Library.objects.all(), to_field_name = "some_title", required = False ) class Meta: … -
Any good folder structure for Component?
Scenario Most of projects nowadays using component to avoid duplicate code over the frontend. Because of this, normally in a project, there a tons of components. It was super confusing. Question How to properly manage all these components? Using naming convention or divide into different folder? Any clue? Is there any standard solution for these? -
Django form only sending GET requests
I have this add page which uses a django form to get information which i am trying to store within "tasks" list and display in the todo html page. i believe all my syntax is correct but it is not displaying the list of tasks when I submit the form. on cmd it detects a GET request every time i submit the form, shouldnt it be saying post? views: from django.shortcuts import render from django import forms tasks = [] class newTaskForm(forms.Form): task = forms.CharField(label="new task") # Create your views here. def index(request): return render(request, "tasks/todo.html", { "tasks": tasks }) def add(request): if request.method == "POST": form = newTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["task"] tasks.append(task) else: return render(request, "tasks/add.html", { "form": form }) return render(request, "tasks/add.html", { "form": newTaskForm }) add: {% extends "tasks/layout.html" %} {% block body %} <form action="{% url 'tasks:add' %}"> {% csrf_token %} {{ form }} <input type="submit"> </form> <a href="{% url 'tasks:home' %}">Veiw list</a> {% endblock %} todo: {% extends "tasks/layout.html" %} {% block body %} <h1> To Do List</h1> <ul> {% for task in tasks %} <li> {{ task }}</li> {% endfor %} </ul> <a href="{% url 'tasks:add' %}">Add items</a> {% endblock %} -
Figuring out JSON memory leaks in Django
I am using Python 3 and Django 3.1.4 for a web application hosted on Heroku. I started experiencing R14 and R15 errors related to memory quota exceeding. The application involves a lot of API calls with large JSON data being sent to the client side via JSONResponse I followed some online resources to run tracemalloc for some of the views. tracemalloc.start() # ... run your application ... snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('lineno') print("[ Top 10 ]") for stat in top_stats[:10]: print(stat) I refreshed the page and I found this pattern. Iteration 3: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/json/decoder.py:353: size=290 MiB, count=3399976, average=89 B Iteration 4: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/json/decoder.py:353: size=406 MiB, count=4759963, average=89 B Iteration 5: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/json/decoder.py:353: size=522 MiB, count=6119933, average=89 B Iteration 6: /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/json/decoder.py:353: size=638 MiB, count=7479913, average=89 B With each iteration, the size increases. It even goes beyond 1000 MiB. Can it be concluded that there is a memory leak with the way JSON data is being handled? How can I fix this problem? -
Python check multiple Unique columns when using POST method(RestAPI)
Pretend that I have multiple unique columns in my database. username = models.CharField(max_length=64, unique=True) email = models.CharField(max_length=64, unique=True) phone_number = models.CharField(max_length=64, unique=True) serial_number = models.CharField(max_length=64, unique=True) When I use POST method, I will use 4 queries to check each of these field exist in database.(If not then I will POST them in database) I am wondering is there a smarter way to check all multiple unique in the database? -
nginx throws bad request 400 when accessed through ddns domain
Working perfect when accessed through local web server IP but throws 400 error when accessed through NOIP hostname. For context, router is configured to forward requests to the web server on that port. This is the nginx config file: server { listen 80; server_name 192.168.1.64; #server_name example.ddns.net; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/projectdir; } location / { include proxy_params; # proxy_pass http://example.ddns.net; proxy_pass http://unix:/run/gunicorn.sock; } } I tried adding the lines where the hashtags are but to no avail. -
Django best practices
I am wondering if I am doing the right thing on my project organisation: For now each app has its template folder containing html files. Also each app has its own static file containing JS files and CSS files (one per html), is it what we do, "in best practices" 1html=1css? Then I also have common stuff, for example navbar, or footer html in a main folder located at the root of my project. I have seen several practices, but I am not able to tell which one is better. Thank you -
Django round in subquery
hi i am getting the progress percentage of each project in a ListView with subquery with the following code class projects(LoginRequiredMixin, ListView): model = Project template_name = 'project_list.html' ordering = ['project_title'] paginate_by = 10 queryset = Project.objects.annotate( todo_done=Count('todo', filter=Q(todo__state=True)) * 100 / Count('todo'), todo_left=Count('todo', filter=Q(todo__state=False)) * 100 / Count('todo'), ) in a project I have 12 tasks, 8 finished and 4 in progress. The system returns 66% completed and 33% in progress, whose sum is 99% and not 100% {{ project.todo_done }} {{ project.todo_left }} part of the bar is blank because the 1% is missing. I try to use round as follows but it is not possible todo_done=round(Count('todo', filter=Q(todo__state=True)) * 100 / Count('todo')), TypeError: type CombinedExpression doesn't define __round__ method -
Running Django app with docker-compose - applying migrations causes db to stop responding to queries but no errors are raised
I searched for this, and it seems like every post has some sort of related error message, but I get no error messages for this problem. It took me a while to even realize what was going on, but I still don't understand why. Essentially, I am trying to containerize my Django app with Docker. I am able to interact with the app on localhost:8000, and if I try my app's search function (the only functionality I've built out so far) before I apply migrations, I get an error as expected because certain tables don't exist. I can see in the logs the database is trying to search for the input from the web app. Once I apply migrations with docker-compose exec web python manage.py migrate --noinput, and I search for any term, I get no results back at all and no errors, and there's nothing in the database logs to suggest it's handling the query. I do see in the logs for the web container that it's noticing I am typing in search terms and pressing enter. On the frontend, I just see "0 results for [search term]", which is what should be returned if the db can't find …