Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete model by filtering with pk
I am trying to delete an entire model using pk, but when I click on "delete" I am redirected to the given page but nothing happens model is still there and not being deleted, but when I write the 'room_name' instead of 'pk' it does work, (thanks in advance) *Views.py: def delete_room(request, pk): Room.objects.filter(name=pk).delete() return redirect('home') Urls.py: path("delete/<int:pk>/", views.delete_room, name="delete_room") Models.py: class Room(models.Model): name = models.CharField(max_length=100) about = models.TextField(max_length=500, null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator') members = models.ManyToManyField(User, through="RoomMember") class RoomMember(models.Model): approved = models.BooleanField(default=False, blank=False) room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE) class Messages(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) text = models.CharField(max_length=10000, blank=False, null=False) date = models.DateTimeField(default=datetime.now) room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE) Html: <a class="btn btn-danger" href="{% url 'delete_room' pk=room.pk %}">Delete Room</a>* -
Wrong decimal round to first 2 digits of amounts in python 3.7 and Django
Let there be 3 Django fields: INPUT = models.DecimalField(max_digits=20, decimal_places=3, default=0) RESULT = models.DecimalField(max_digits=20, decimal_places=3, default=0) RATE = models.DecimalField(max_digits=12, decimal_places=5, default=1) RATE is always Decimal('1.00000'). I want to have RESULT = INPUT * RATE and since the source is either from database, either from APIs, I use: RESULT = Decimal(INPUT) * Decimal(RATE) I do not know why, but in some cases (≈ 2%) I end with the numbers you see in the following table. There is a round to the first 2 digits. Do you know what could cause that? I do not see anything in the code that could do that and I am clueless. Both columns should be equal. RESULT INPUT 610.000 609.000 3700.000 3743.520 1200.000 1159.000 570.000 573.300 61.000 61.470 1300.000 1321.550 44.000 43.730 130.000 125.770 18.000 18.500 100.000 99.590 41.000 40.650 95.000 94.880 19.000 18.710 36.000 35.640 120.000 118.800 12.000 12.290 11.000 11.260 1.000 1.030 160.000 155.970 190.000 186.850 51.000 50.770 130.000 128.150 12.000 12.290 11.000 11.260 25.000 24.940 24.000 23.640 -
Makefile code-convention pylint set doen'st work
Im trying to configure code-convention at my project with pylint and flak8, I set configurations in the file and run 'make code-convention', but its return ModuleNotFoundError: No module named 'myproject'. The $PATH variable is correctly configured. My Makefile: code-convention: export DJANGO_SETTINGS_MODULE=myproject.config.settings ;\ flake8 myproject ;\ pylint myproject/ up_env: docker-compose up -d up_env_build: docker-compose up -d --build down_env: docker-compose rm --stop --force logs_env: docker-compose logs -f # Server run_server: python -m application all: clean create-venv setup-dev test-cov default_target: clean code-convention test-cov -
Django verbose logging for bad request
I am relatively new to django. I recently deployed my application on a web server, and I find it very hard to debug issue. I am getting 400 Http status code for some of my requests and not sure why. I am trying to increase the level of logs in order to find the root cause for it. However, the output of the logs in not very informative. I am using this configuration for logging (DEBUG is enabled): logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { 'format': '%(name)-12s %(levelname)-8s %(message)s' }, 'file': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'console' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'formatter': 'file', 'filename': '/var/log/django/debug.log' } }, 'loggers': { '': { 'level': 'DEBUG', 'handlers': ['console', 'file'] } } }) This is the output that I am getting in the logs: 2021-11-18 16:18:59,667 django.request WARNING Bad Request: /create How can increase the verbosity of the logs to be more informative? -
Django url kwargs in templates
Previously we have been accessing kwargs in Django templates with {{view.kwargs.kwarh_name}}. However, it has been to my surprise that this is not working in my django 3.2.4+ Has it been removed, is there any issue with the line above? Note: Kwargs here I mean something like below: Given a function as below: def GetSomething(request, code): return render(request, "some template here") Now, the urlpatterns would be something like, import GetSomething from .views app_name = "some_app_name_here" urlpattern = [ path("link/<int:code>/", GetSomething, name="some_cool_name") #http:localhost/link/12345/ ] Now in HTML/Django templates or Jinja2(whichever you use), accessing this code would be via {{ view.kwargs.code }} But it so happens that this is not working for me in Django 3.2, any reasons?? Hope I was very clear! -
Django DurationField just for HH:MM never needing seconds?
I have a DurationField in my DB and trying to use this in ModelForm` with the purpose of keeping track of days if any, and only hours and minutes. I do not need seconds at all. I have tried to build out custom functionality to do this, as follows... def duration_string(duration): days = duration.days seconds = duration.seconds minutes = seconds // 60 hours = minutes // 60 minutes = minutes % 60 dur_string = f'{hours}:{minutes}:00' if days: dur_string = 'f{days} + dur_string' return dur_string class CustomDurationField(forms.DurationField): def prepare_value(self, value): if isinstance(value, datetime.timedelta): return duration_string(value) return value class TimeForm(ModelForm): setup_duration = CustomDurationField() now in my form field, when a user enters 1:45 I want this to register as 1 hour and 45 minutes, yet when I check my database, 00:01:45 is returned, which is 1 minute and 45 seconds. In my shell, I am getting a timdelta object such as datetime.timedelta(seconds=105) If anybody has any guidance as to how to accomplish this would be greatly appreciated! -
django path to view
hey i have a url path that i want to lead me to an application url file but it says page not found here is my core url: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls', namespace='store')), path('basket/', include('basket.urls', namespace='basket')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here is my basket.url file: from django.urls import path from . import views app_name = 'basket' urlpatterns = [ path('', views.basket_summary, name='basket_summary'), ] and this is the view: from django.shortcuts import render # Create your views here. def basket_summary(request): return render(request, 'store/basket/summary.html') my app name is basket , and i might add all of the files are defined. whats the problem ? -
Django - Invalid template name in 'extends' tag: ''. Got this from the 'current_module.base_template' variable
In my project I wanted to apply django-material frontend according to this tutorial http://docs.viewflow.io/frontend_crud.html I just wanted to add one more application to an existing and working project. Unfortunately, I ran into a problem with urls.py configuration Here are some code snippets that may be relevant INSTALLED_APPS ... INSTALLED_APPS = [ 'epm.apps.EpmConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'organize', 'crispy_forms', 'compressor', 'bootstrap_modal_forms', 'django_filters', 'fontawesome-free', 'material', 'material.frontend', 'viewflow', 'viewflow.frontend', 'ordercard', 'general.apps.GeneralConfig' ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #'DIRS': [], 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'APP_DIRS': True, ... ... ... My global urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls import url from material.frontend import urls as frontend_urls from pprint import pprint #from . import views urlpatterns = [ path('', include('epm.urls')), path('card/', include('ordercard.urls')), path('admin/', admin.site.urls), path('auth/', include('django.contrib.auth.urls')), path('viewflow/', include(frontend_urls)), path('organize/', include('organize.urls')), url(r'general/', include('general.urls')), path('', include(frontend_urls)), ] and my urls.py from general app from django.conf.urls import url, include from django.views import generic from material.frontend import urls as frontend_urls from . import views app_name='general' urlpatterns = [ url('^$', generic.RedirectView.as_view(url='./customer/'), name="index"), url('^customer/', include(views.MyModelViewSet().urls)), #url(r'', include(frontend_urls)), #url('', generic.TemplateView.as_view(template_name="sales/index.html"), name="index"), ] With this configuration of files, he gets an error message: TemplateSyntaxError at /general/customer/ Invalid template name in 'extends' tag: … -
Apply a migration to Django Flatpage model
I would like to use the modeltranslation package in a Django application that uses the flatpages app. I installed both, followed the model translation docs, and created a translation.py file, which I put in the main app (where all the global stuff lies), as I can't put it directly in the flat pages app (Django code is a requirement and is not committed to VCS). # django/main/translation.py from modeltranslation.translator import translator, TranslationOptions from django.contrib.flatpages.models import FlatPage class FlatPageTranslationOptions(TranslationOptions): fields = ('title', 'content') translator.register(FlatPage, FlatPageTranslationOptions) Then I ran python manage.py makemigrations, and it created a migration file in the flatpages app /usr/local/lib/python3.8/site-packages/django/contrib/flatpages/migrations/0002_auto_20211118_1558.py. It would be again in the Django code, so I tried to simply move it to the main app at django/main/migrations/0002_flatpages_translations.py (there is already an unrelated 0001_initial.py migration, which has no dependencies): from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('flatpages', '0001_initial'), ] operations = [ migrations.AddField( model_name='flatpage', name='content_en', field=models.TextField(blank=True, null=True, verbose_name='content'), ), migrations.AddField( model_name='flatpage', name='content_fr', field=models.TextField(blank=True, null=True, verbose_name='content'), ), migrations.AddField( model_name='flatpage', name='title_en', field=models.CharField(max_length=200, null=True, verbose_name='title'), ), migrations.AddField( model_name='flatpage', name='title_fr', field=models.CharField(max_length=200, null=True, verbose_name='title'), ), ] And... when I finally try to run the migration (python manage.py migrate), I got this error: CommandError: Conflicting migrations detected; multiple leaf … -
How to get a list of existing student names in Django?
I am new to Django rest framework, I want to get a list of the student first names(only) when it is existed. can anyone help me? In my model.py class School(models.Model): name = models.CharField(max_length=100, null=False, blank=False) city = models.CharField(max_length=100, null=False, blank=False) street = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return f"{self.city}->{self.street}->{self.name}" class Student(models.Model): school_id = models.ForeignKey(School, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, null=False, blank=False) last_name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return f"{self.first_name} {self.last_name}" In my serializers.py: class StudentSerializer(serializers.Serializer): class Meta: model = Student fields = ['first_name'] class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True, read_only=True) class Meta: model = School fields = ['is_existing_student','student'] In my views: class schoolViewSet(viewsets.ModelViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() In this picture you can see how it should look like [1]: https://i.stack.imgur.com/bR8cN.png -
/etc/nginx/conf.d/default.conf is not a file or does not exist
I am trying to route both Django and React with NGINX via docker-compose. The error I get is /etc/nginx/conf.d/default.conf is not a file or does not exist Here is my docker file version: "3.9" services: web: container_name: web build: context: ./backend dockerfile: Dockerfile command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 volumes: - django_static_volume/:/usr/src/app/static expose: - 8000 env_file: - ./backend/.env depends_on: - db react: container_name: react build: context: ./frontend dockerfile: Dockerfile volumes: - react_static_volume:/usr/src/app/build/static expose: - 3000 env_file: - ./.env.dev command: serve -s build -l 3000 depends_on: - web db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./backend/.env nginx: container_name: nginx restart: always build: ./nginx volumes: - django_static_volume:/usr/src/app/django_files/static - react_static_volume:/usr/src/app/web_frontend/static ports: - 80:80 depends_on: - react - db - web volumes: postgres_data: react_static_volume: django_static_volume: here is my nginx.conf upstream django_backend { server django:8000; } upstream react_frontend { server react:3000; } server { listen 80; ########### # URL ROUTING # ########### location /admin { proxy_pass http://django_backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /api { proxy_pass http://django_backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } ########### # STATIC FOLDER ROUTING # ########### location /static/admin/ { alias /usr/src/app/django_files/static/admin/; } location /static/rest_framework/ { alias /usr/src/app/django_files/static/rest_framework/; } location /static/ { alias /usr/src/app/react_files/static/; } … -
Change available options in select but don't change selected one
I wan't to create Django/JavaScript mechanism that will enable me to change form select data based on other selected fields. For example let's say I have two select fields, I change the first one, then the function is triggered in Django and new template is loaded to html select element (I am using Ajax for that). This works fine, but the problem is when I will choose element 1 and then I want element 2 to also be able to change element1, the first option is reseted. I was trying to solve this by remembering the selected field and then loading it in but it then triggers element 2 and it, won't work. Any help will be appreciated :) -
Django DRF foreignkey serializer - how to return only the latest object?
I currently have to models where a Node can have many Benchmark's, but when displaying it to the end users, I only want the serializer to return the latest benchmark for the node, instead of all of them which it currently does. How can I do this? Models.py class Node(models.Model): node_id = models.CharField(max_length=42, unique=True) wallet = models.CharField(max_length=42, null=True, blank=True) earnings_total = models.FloatField(null=True, blank=True) data = models.JSONField(null=True) online = models.BooleanField(default=False) version = models.CharField(max_length=5) updated_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Benchmark(models.Model): benchmark_score = models.IntegerField() benchmarked_at = models.DateTimeField(default=timezone.now) provider = models.ForeignKey(Node, on_delete=models.CASCADE) serializers.py class BenchmarkSerializer(serializers.ModelSerializer): class Meta: model = Benchmark fields = ['benchmark_score', 'benchmarked_at'] class NodeSerializer(serializers.ModelSerializer): benchmark_set = BenchmarkSerializer(many=True) class Meta: model = Node fields = ['earnings_total', 'node_id', 'data', 'online', 'version', 'updated_at', 'created_at', 'benchmark_set'] -
why at django framework vscode extension pylance giving me reed line at path
please click here for resolving error please someone resolve this problem why vs code giving me red line on path on django framework -
is it safe to compare owner_id to request.user.id for authentication in django?
in my app I have the model: class Meal(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=500) carbohydrates = models.FloatField() protein = models.FloatField() fat = models.FloatField() fiber = models.FloatField() owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) the following serializer: class MealSerializer(serializers.ModelSerializer): class Meta: model = Meal fields = "__all__" and this viewset: class MealViewSet(viewsets.ModelViewSet): queryset = Meal.objects.all() serializer_class = MealSerializer def get_queryset(self): return Meal.objects.filter(owner_id=self.request.user.id) And now I have a question, is it safe to compare owner_id=self.request.user.id in get_queryset method for authentication? or is it possible somehow to specify user.id in request e.g. using postman and pull all Meal objects? for example: Is that possible in postman or somewhere else? I am a beginner in django and rarely used postman. Sorry if I wrote something wrong, English is not my native language. -
How to change browse button to look like modern drag&drop?
I have created a django site, django site is working in this way. You go to the site, upload document with data and you get some results. You upload excel file, and you download excel file. In background I used pandas for calculations. In the end you can see code. I have left one thing to finish. I want to create drag&drop for upload document. Chech picture 1, as I understand this is already drag&drop, just doesn't look as I would like to. I want to look like in picture 2. Picture 1: Current Picture 2: I would like to look like this. Can I change the look that you seen on first image without using js? This is html that I have and output is shown in picture 1... {% extends "base.html" %} {% load static %} {% block content %} <form action="{% url "cal" %}" method="post" enctype="multipart/form-data" class="dropzone"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload and Download!"/></p> </form> {% endblock content %} This is function in views def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): … -
ERROR: Failed building wheel for PyNaCl trying to install pymssql on M1 silicon with Monterey OS with pip install
Tried installing pymssql on an M1 device with Monterey 12.0 on pycharm using pip install and failed with the below error tried installing freetds, force linking it, and installing OpenSSL nothing helped. Versions: Python - 3.8.9 Pip-21.3.1 freetds- 1.3.3 mysql-connector>=2.2.9 tried both pymssql<3.0 && pymssql==2.2.2 tried both Cython==0.29.24 && Cython>=0.29.24 Building wheel for PyNaCl (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users//code//venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-install-3t__09es/pynacl_f3395a623f074763b680641bfc68bebd/setup.py'"'"'; file='"'"'/private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-install-3t__09es/pynacl_f3395a623f074763b680641bfc68bebd/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-wheel-ys2kjl3_ cwd: /private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-install-3t__09es/pynacl_f3395a623f074763b680641bfc68bebd/ Complete output (29 lines): /Users//code//venv/lib/python3.8/site-packages/setuptools/installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer. warnings.warn( Traceback (most recent call last): File "", line 1, in File "/private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-install-3t__09es/pynacl_f3395a623f074763b680641bfc68bebd/setup.py", line 203, in setup( File "/Users//code//venv/lib/python3.8/site-packages/setuptools/init.py", line 152, in setup _install_setup_requires(attrs) File "/Users//code//venv/lib/python3.8/site-packages/setuptools/init.py", line 147, in _install_setup_requires dist.fetch_build_eggs(dist.setup_requires) File "/Users//code//venv/lib/python3.8/site-packages/setuptools/dist.py", line 806, in fetch_build_eggs resolved_dists = pkg_resources.working_set.resolve( File "/Users//code//venv/lib/python3.8/site-packages/pkg_resources/init.py", line 771, in resolve dist = best[req.key] = env.best_match( File "/Users//code//venv/lib/python3.8/site-packages/pkg_resources/init.py", line 1056, in best_match return self.obtain(req, installer) File "/Users//code//venv/lib/python3.8/site-packages/pkg_resources/init.py", line 1068, in obtain return installer(requirement) File "/Users//code//venv/lib/python3.8/site-packages/setuptools/dist.py", line 877, in fetch_build_egg return fetch_build_egg(self, req) File "/Users//code//venv/lib/python3.8/site-packages/setuptools/installer.py", line 87, … -
How to resolve user into the field?
I'm creating a simple To Do app using Django 3.2, and I have stuck in a error which is: FieldError: Cannot resolve keyword 'user' into field. Choices are: content, created, email, id, name, user1, user1_id This is models.py: from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields import CharField from django.contrib.auth.models import User # Create your models here. class User(models.Model): content = models.CharField(max_length=200, null=True) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) user1 = models.ForeignKey(User, on_delete=CASCADE) def __str__(self): return self.content forms.py from django import forms from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] views.py from django.shortcuts import render, redirect from django.http.response import HttpResponse from django.utils import timezone from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from demo.forms import CreateUserForm from .models import * from .models import __str__ # Create your views here. @login_required(login_url='/login') def home(request): user = request.user all_items = User.objects.filter(user=user).order_by("created") context = {'all_items': all_items} return render(request, 'html/home.html', context) @login_required(login_url='/login') def add_content(request): current_date = timezone.now() newItem = User(content=request.POST.get('content')) newItem.save() return redirect('/') @login_required(login_url='/login') def login_user(request): if request.method == 'POST': username = … -
Django server won't run: This site can’t be reached127.0.0.1 refused to connect
I am trying to make an auction website for my CS50W project2: Commerce .When I try to run python3 manage.py runserver. There are 6 errors. I get that the system identified 6 errors: System check identified 6 issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 259, in build_graph self.graph.validate_consistency() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auctions.0003_auto_20201114_0509 dependencies reference nonexistent parent node ('auctions', '0002_listing') please help -
Django admin and MTM relationships
I'm working with following scheme: class Session (models.Model): uuid = # uuid status = # charfield class Document (models.Model): session = models.ForeignKey(Session) signers = models.ManyToManyField(Signer, through='Signature', related_name='documents') class Signer(models.Model): uuid = # uuid class Signature(models.Model): signer = models.ForeignKey(Signer) document = models.ForeignKey(Document) I'm now trying to create a detail admin view where I can display: Session information List of documents in session Nested list per document for all signers in document Nested list per signer with all signatures for signer So far I came up with: @admin.register(Session) class SessionAdmin(nested_admin.NestedModelAdmin): search_fields = ("status", ) list_display = ("uuid", ) inlines = [DocumentInline] can_delete = False class InSignDocumentInline(nested_admin.NestedTabularInline): model = Document inlines = [ InSignSignerInLine, ] exclude = ['signers', ] class SignerInLine(nested_admin.NestedTabularInline): model = Document.signers.through But all that is showing is: Session with information List of documents in session Nested list of signatures in document (I would like to display the signers between the documents and the signatures) What am I missing? -
How to aceess list item in jinja
I have 2 list in my Django site. my views.py: def index(request): totalDBElement = [169, 2166, 5413, 635, 635] elementOrder = ['Rules', 'Questions', 'ParentChild', 'ChildList'] return render(request,'diagnosis/index.html', {'totalDBElement': totalDBElement, 'elementOrder' : elementOrder}) I wish to get something like this in my template: Rules: 169 Questions: 2166 ParentChild: 5413 ChildList: 635 my template: {% for i in len(totalDBElement) %} <h2> {{ totalDBElement[i] }} </h2> <h2> {{ elementOrder[i] }} </h2> {% endfor %} But it gives errors like: Could not parse the remainder: '(totalDBElement)' from 'len(totalDBElement)' Please suggest how can I fix this? I also wish to print -
django deployment on heroku issue (djongo not found)
remote: django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend. remote: Try using 'django.db.backends.XXX', where XXX is one of: remote: 'mysql', 'oracle', 'postgresql', 'sqlite3' remote: -
Django - How to get value from related model
I have my user model like this class User(AbstractUser): USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] last_name = models.CharField(max_length=48, blank=True) email = models.EmailField(unique=True) #Private=True Public=False account_type = models.BooleanField(default=False) And a preferences model for user class UserPreferences(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) leader_board_exclusion = models.BooleanField(default=False) reaction_count_visibility = models.BooleanField(default=True) How do I get the value leader_board_exclusion? Currently I'm doing this (Does this hit the database?) user_preference = UserPreferences.objects.get(user=user) print(user_preference.leader_board_exclusion) I was reading about selected_related and get_related and was thinking of a better way to do this -
Django chunked upload in IIS
I uploaded a program on which a django application is used for file uploading and used the chunk file uploads for it (with the blueimp fileupload on JS side). When I tested my application locally, it works. When I do it on the IIS production, I always get this error: POST http://URL/api/chunked_upload/ 500 (Internal Server Error) The logs in the IIS were not helpful either. JS Code: $('#fileUpload').fileupload({ url: window.location.href + 'api/chunked_upload/', dataType: "json", maxChunkSize: 100000, // Chunks of 100 kB formData: form_data, type: 'POST', add: function (e, data) { form_data.splice(1); calculate_md5(data.files[0], 100000); $("#submitButton").off('click').on("click", function () { showLoading() data.submit(); }); }, chunkdone: function (e, data) { // Called after uploading each chunk if (form_data.length < 2) { form_data.push( {"name": "upload_id", "value": data.result.upload_id} ); } }, done: function (e, data) { // Called when the file has completely uploaded let formInput; $.ajax({ type: "POST", url: window.location.href + 'api/chunked_upload_complete/', data: { csrfmiddlewaretoken: csrf, upload_id: data.result.upload_id, md5: md5 }, dataType: "json", success: function(data) { inputForm = document.getElementById('ddGraderForm') document.getElementById('id_formFile').value = data['file'] inputForm.submit() } }); }, }); Django urls urlpatterns = [ path('', views.webinterfaceViews, name='main'), path('api/chunked_upload_complete/', FastaFileUploadCompleteView.as_view(), name='api_chunked_upload_complete'), path('api/chunked_upload/', FastaFileUploadView.as_view(), name='api_chunked_upload'), ] Django view class FastaFileUploadView(ChunkedUploadView): model = fileUpload def check_permissions(self, request): # Allow non … -
accessing context variables that contain spaces
I have python dictionary, and I am passing its values to a html page to display them. i am able to access the values of the dictionary by using {{ value.xxx }} where the xxx is the element of the dictionary. the values appear on the screen no problem for name, age & height below. However the skill set component doesn't appear because of the space in the text. How can i set it so that i can access the elements that contain a space, like the skillset value below. I have tried adding an underscore such as {{ value.skill_set }} but that doesn't seem to work. Dictionary: dict = {1: {'name': 'John', 'age': '27', 'height': '160', 'skill set': 'running'}, 2: {'name': 'Marie', 'age': '22', 'height': '170', 'skill set': 'swimming'}} Html: <table class="u-full-width" id="table2"> <thead > <tr> </tr> </thead> <tbody> {% for key,value in dict_items.items %} <tr> <th scope="row" style="text-align:center">{{ key }}</th> <td style="text-align:center">{{ value.name }}</td> <td style="text-align:center">{{ value.age }}</td> <td style="text-align:center">{{ value.height }}</td> <td style="text-align:center">{{ value.skill set }}</td> </tr> {% endfor %} </tbody> </table>