Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display results of query in user admin section - django
Newbie question: I have my "users" app in the django admin but is there a way to implement a section that only shows users with criteria is_staff = False or any other criteria that I define? I'm a bit lost because I don't think it's necessary to create an app, because I don't need to create a new table, just query and display. For example: My query should I implement it in users / admin.py? But how do I render the result of the query? Thanks! -
django doesn't render a first <form> tag in the template
I have a base template to extend: {% load static %} {% load i18n %} <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <meta name="viewport" content="width=device-width,initial-scale=1"> {% block title %} <title>taskmanager</title> {% endblock title %} <link rel="stylesheet" type="text/css" href="{% static 'common_static/base/styles/base.css' %}"> {% block extrahead %}{% endblock extrahead %} </head> <body> <header> <div class="header-main-area center-area"> <div id="switch-lang" class="header-element"> {% include 'svgpaths/language_icon.html' %} {% get_current_language as LANGUAGE_CODE %} {% get_language_info for LANGUAGE_CODE as current_language %} <div class="header-element-caption"> {{ current_language.name_local }}</div> <form action="{% url 'set_language' %}" method="post" class="lang-dropdown dropdown-content">{% csrf_token %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <button type="submit" name="language" value={{ language.code }} class="dropdown-item">{{ language.name_local }}</button> {% endfor %} </div> <div id="account" class="header-element"> {% include 'svgpaths/account_icon.html' %} {% if username %} <div class="header-element-caption">{{ username }}</div> {% else %} <div class="header-element-caption">{% translate "account" %}</div> {% endif %} <div class="acconunt-dropdown dropdown-content"> <a href="{% url 'logout' %}" class="dropdown-item">{% translate "log out" %}</a> <a href={% url 'user_settings' %}><div class="dropdown-item">{% translate "settings" %}</div></a> </div> </div> </div> </header> <main> {% block maincontent %} <h1>This is the base templated for extending</h1> {% endblock maincontent %} </main> {% block bodybottom %}{% endblock bodybottom %} … -
Uploading and Downloading Files with Django and Nginx
I'm currently trying to upload some files using Django and it seems to be working for the most part. I'm at least able to see that the file is added to the specific model in the Django admin panel but I'm unable to open it. Additionally, whenever I try to get the URL of the file, I get forwarded to the Django error page with a nice error that says, [Errno 2] No such file or directory: 'media/some_file.csv' Here is my file model : class File(models.Model): challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE, default="") file = models.FileField(default="", upload_to="media/") def __str__(self): return self.challenge.challenge_id Settings.py : STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'server', 'static'), os.path.join(BASE_DIR, '..', 'media'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' Upload Function : def uploadChallengeFile(request): latestChallenge = Challenge.objects.last() for file in request.FILES.items(): file_model = File(challenge=latestChallenge, file=file[0]) file_model.save() data = {"data": [True]} return JsonResponse(data, safe=False) Download Function : def downloadFile(request, challenge_id): challenge = Challenge.objects.filter(challenge_id=challenge_id) filename = File.objects.filter(challenge=challenge).values("file")[0]["file"] content = open(File.objects.get(challenge=challenge).file.url).read() response = HttpResponse(content, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response urls.py : url(r'^api/start/download/(?P<challenge_id>[\w.@+-]+)/$', views.backendServices.downloadFile, name="download") It seems like Django is saving the instance of the file but not actually storing it. Do I need to configure the nginx.conf to serve the … -
Is it possible to execute javascript through Wagtail's richtext field?
I was building a website with django and wagtail as cms, I was wondering if it's possible to execute javascript through wagtail's richtext field with wagtail's default richtext filter. For example, add a onclick attribute to a link. My goal is to prevent such thing from happening, for security reasons. -
What data is this?
I am using Django and I am getting a pdf file stored in BinaryField and trying to send it in a response as data-type (Preferably, I want to send it in as many data-types as I can as requested by a client). class CVPdf(generics.UpdateAPIView): permission_classes = [IsAuthenticated] parser_classes = [FileUploadParser] def get(self, *args): """ * ``:param request:`` GET request sent with ``Authorization: Bearer token_id``. * ``:return:`` Authenticated Seeker CV file """ pdf_file= CV.objects.get(id=1).pdf_file return HttpResponse(pdf_file) Doing a GET request with python requests library, I am getting the following data: '...0000000123 65535 f\r\n0000000124 65535 f\r\n0000000125 65535 f\r\n0000000126 65535 f\r\n0000000127 65535 f\r\n0000000128 65535 f\r\n0000000129 65535 f\r\n0000000130 65535 f\r\n0000000131 65535 f\r\n0000000132 65535 f\r\n0000000133 65535 f\r\n0000000134 65535 f\r\n0000000135 65535 f\r\n0000000136 65535 f\r\n0000000137 65535 f\r\n0000000138 65535 f\r\n0000000139 65535 f\r\n0000000140 65535 f\r\n0000000141 65535 f\r\n0000000142 65535 f\r\n0000000143 65535 f\r\n0000000144 65535 f\r\n0000000145 65535 f\r\n0000000146 65535 f\r\n0000000147 65535 f\r\n0000000148 65535 f\r\n0000000149 65535 f\r\n0000000000 65535 f\r\n0000032441 00000 n\r\n0000032871 00000 n\r\n0000235049 00000 n\r\n0000235493 00000 n\r\n0000236007 00000 n\r\n0000236479 00000 n\r\n0000432257 00000 n\r\n0000432285 00000 n\r\n0000432726 00000 n\r\n0000647350 00000 n\r\n0000647920 00000 n\r\n0000648462 00000 n\r\n0000648763 00000 n\r\n0000661917 00000 n\r\n0000661961 00000 n\r\n0000662439 00000 n\r\n0000778958 00000 n\r\n0000778986 00000 n\r\n0000798973 00000 n\r\ntrailer\r\n<</Size 169/Root 1 0 R/Info 36 0 R/ID[<B3EBF57233FC8C4C9A30C5ED4E046BAA><B3EBF57233FC8C4C9A30C5ED4E046BAA>] >>\r\nstartxref\r\n799587\r\n%%EOF\r\nxref\r\n0 0\r\ntrailer\r\n<</Size 169/Root 1 0 R/Info 36 0 R/ID[<B3EBF57233FC8C4C9A30C5ED4E046BAA><B3EBF57233FC8C4C9A30C5ED4E046BAA>] … -
How is throttling disabled for testing in Django Rest Framework?
Upon implementing a throttle for a REST API, I'm encountering an issue when running my tests all at once. Upon isolating the subject TestCase and running the test runner, the TestCase passes its assertions. However when all the tests are ran I get the following error: AssertionError: 429 != 400. Which that type of error of course is due to the requests exceeding a rate limit. How can I disable throttling for the tests so the assertion error is not raised. I decorated the TestCase with @override_settings but that doesn't have any effect. from copy import deepcopy from django.conf import settings from django.test import TestCase, override_settings from django.contrib.auth.models import User from rest_framework.test import APITestCase, APIClient from django.urls import reverse from ..models import QuestionVote, Question from users.models import UserAccount from tags.models import Tag from .model_test_data import mock_questions_submitted REST_FRAMEWORK = deepcopy(settings.REST_FRAMEWORK) del REST_FRAMEWORK['DEFAULT_THROTTLE_RATES'] @override_settings(REST_FRAMEWORK=REST_FRAMEWORK) class TestUserVoteOnOwnQuestion(APITestCase): '''Verify that a User cannot vote on their own Question''' @classmethod def setUpTestData(cls): cls.user1 = User.objects.create_user("Me", password="topsecretcode") cls.user1_account = UserAccount.objects.create(user=cls.user1) cls.tag = Tag.objects.create(name="Tag") cls.q = mock_questions_submitted[2] cls.q.update({'user_account': cls.user1_account}) cls.question = Question(**cls.q) cls.question.save() cls.question.tags.add(cls.tag) def test_vote_on_own_posted_question(self): self.client.login(username="Me", password="topsecretcode") response = self.client.put( reverse("questions_api:vote", kwargs={'id': 1}), data={"vote": "upvote"} ) self.assertEqual(response.status_code, 400) self.assertEquals( response.data['vote'], "Cannot vote on your own question" … -
Add custom button near Save button Django-admin
I have added a custom button in django admin, however its below the Save and Save and Close buttons, how can I make this custom button on the same line with the 2 buttons above, below is the image : then, how I overridden the button with the templates : {% extends 'admin/custominlines/change_form.html' %} {% load i18n %} {% block submit_buttons_bottom %} {{ block.super }} {% if request.GET.edit %} <div class="submit-row"> {% for obj in transitions %} <input type="submit" value="{{ obj }}" name="{{ obj }}"> {% endfor %} </div> {% endif %} {% endblock %} -
Django / Rest Framework, AttributeError: 'list' object has no attribute id
I'm working with Django / Rest Framework, i would like to get the inserted record id i did : formSerializer = self.serializer_class(data = request.data, many=True, context={'request': request}) if formSerializer.is_valid(): newContact = formSerializer.save() print(newContact.id) but i'm getting an error : print(newContact.id) AttributeError: 'list' object has no attribute 'id' -
I can’t reproduce videos on Safari (Django App)
I have a Django app, when a reproduce videos on my desktop (Chrome) I can reproduce the video but when I reproduce the video on my mobile (iPhone - safari ) the video doesn’t work, the same problem with Safari on my Mac. In Chrome I can’t advance or rewind the video (the videos are in my computer), but when I change the source and I use a video of youtube (for example) I can advance or rewind the videos. I have this error when I try to reproduce videos on my phone: ------- Exception occurred during processing of request from ('192.168.1.7', 63287) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 720, in __init__ self.handle() File "/Users/edison/Documents/Python/Proyecto_10/venv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/edison/Documents/Python/Proyecto_10/venv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py", line 714, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer My HTML code for the video: <div class="col-md-12"> <div class="d-flex justify-content-center"> <video width="960" height="540" poster="{{ scene.profile_pic.url }}" controls preload="none" controlsList="nodownload" playsinline> <source src="{{ scene.video_trailer.url }}" type="video/mp4"> </video> </div> </div> Thanks in advance. -
Tracking User Model Changes in Django's Default User Model with pghistory
I implemented your django-pghistory package in my college project. However, I am having trouble with tracking Django's default user model. I tried your "Tracking Third-Party Model Changes" suggested code in your documentation, as shown below in apps.py corresponding to "usuarios" app: user app.py However, I am not getting migrations done, so I think I am missing something that I am not aware of from the documentation. Would you mind helping me around with this? -
How do I filter a foreign key in models.py based on Groups
I'm new here. I just stared a project using Python/Django it is an idea that I want to show at my job. I have a django project and app already working Since I just started with it. I'm relying heavily on the default Django Admin Panel. My Problem is: I have this class in models.py class Sales(models.Model): order_number = models.CharField(max_length=50) order_date = models.DateField('digitado em', default=date.today) Sales_User = models.ForeignKey(User, on_delete=models.SET_DEFAULT) Now in my User db I have 50 Users. But only 15 of those are Sales People (all in the Group "Sales") When I go to create an order and have to select the sales user The dropdown shows all 50 Users. Is the a way to either filter those user by the group they are in? Or to replace the dropdown with on of those pop-up then search and select. I'm open to try different approaches as long as I can actually accomplish them. :-) Thank you all for the time. -
ImportError: Module "rest_framework.permissions" does not define a "isAuthenticated" attribute/class
Currently trying to add authentication to my app. Not sure if this has to do with my current problem, but I made an authentication application, and then had to change the name because it didn't play well with django.contrib.auth. Anyway, I just renamed the folder and the name in INSTALLED_APPS, since I didn't do any migrations yet. When I had finished up with that and tried to do ./manage.py makemigrations for the first time, I get this: ImportError: Could not import 'rest_framework.permissions.isAuthenticated' for API setting 'DEFAULT_PERMISSION_CLASSES'. ImportError: Module "rest_framework.permissions" does not define a "isAuthenticated" attribute/class. I also didn't install any new dependencies to my virtualenv since renaming my authentication app, so I don't think I missed anything in terms of renaming stuff in node_modules. Here's my settings.py: import os from datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'blah blah' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
how do I merge multiples datasources into one result?
lets say . I have the following models where I Have multiples store locations where it sends me all inventory to multiples tables its products e.g Collection1,Collection2,Collection3, n+1, so I need to merge the results to a centralized table or merge the results of all tables into a single response in the view. is there any way to perform .all() in a single result? class Collection1(models.Model): id = models.CharField(max_length=32, unique=True) products = models.ManyToManyField(Product, related_name='products') provider = models.ManyToManyField(Provider, related_name='provider') date = models.DateTimeField(default=timezone.now) class Collection2(models.Model): id = models.CharField(max_length=32, unique=True) products = models.ManyToManyField(Product, related_name='products') provider = models.ManyToManyField(Source, related_name='provider') date = models.DateTimeField(default=timezone.now) class Collection3(models.Model): id = models.CharField(max_length=32, unique=True) products = models.ManyToManyField(Product, related_name='products') provider = models.ManyToManyField(Provider, related_name='provider') date = models.DateTimeField(default=timezone.now) -
Django Runserver Error: "OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'"
The Problem Some friends and I were working on a project for class that we were never able to complete. We were using this tutorial by Dennis Ivy on YouTube to make a To-Do List using Django, but I was never able to finish my part thanks to an error I kept getting, listed below. I tried looking things up everywhere online, but none of it helped. I reinstalled Python, Django, VSCode, tried PyCharm, upgraded pip, tried VMs (OpenSUSE, Regolith, Ubuntu), and even a whole other Windows PC. but none if it seemed to help. The Error Tried to run the server: PS D:\Cloud\jvivar-nmsu\OneDrive - New Mexico State University\Documents\2021_Spring\ET458\ToDo_Project_Final\et458\todo> python manage.py runserver 8000 Error Output: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Program Files\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Program Files\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program … -
Problems with DjangoFilterView
I am trying to filter my models with the django-filter extension. The view wont work, and I am not sure why.. I currently have this code: models.py from django.db import models class defense_mechanism(models.Model): defense = models.CharField(max_length=100, blank=True) def __str__(self): return self.defense class attack(models.Model): actor = models.CharField(max_length=100, blank=True) action = models.CharField(max_length=100) asset = models.CharField(max_length=100) defense = models.ManyToManyField(defense_mechanism) def __str__(self): return self.action class security_incident(models.Model): security_inc = models.CharField(max_length=100, primary_key=True) def __str__(self): return self.security_inc class adtree(models.Model): goal = models.ForeignKey(security_incident, on_delete=models.CASCADE) attack = models.ManyToManyField(attack) defense_mechanism = models.ManyToManyField(defense_mechanism) filters.py import django_filters from django import forms from .models import adtree, security_incident, attack, defense_mechanism class ADTreeFilter(django_filters.FilterSet): goal = django_filters.CharFilter defense_mechanism = django_filters.CharFilter attack = django_filters.CharFilter class Meta: model = adtree fields = ['goal', 'defense_mechanism', 'attack'] views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.views.generic import View, FormView from django import forms from django_filters.views import FilterView from .models import adtree, security_incident, defense_mechanism, attack from .filters import ADTreeFilter class GenerateView(FilterView): model = adtree context_object_name = 'ad_tree' template_name = 'application/generate.html' filterset_class = ADTreeFilter def get_context_data(self, **kwargs): context = super(GenerateView, self).get_context_data(**kwargs) context['goals'] = adtree.objects.goal().order_by('pk') context['attacks'] = attack.objects.all().order_by('pk') context['defense_mechanisms'] = defense_mechanism.objects.all().order_by('pk') return context def get_form_kwargs(self): kwargs = super(GenerateView, self).get_form_kwargs() return kwargs generate.html <form method="get"> <div class="well"> <div class="row"> <div class="col-md-12"> … -
Detect Authentication Failure
I'm using the Django AllAuth package to authenticate my users. I used this tutorial to implement it. I am attempting to write a JS function that would change the display css property on the message element. The problem I'm having is detection the authentication failure event in order to place it into a function. Is it possible to do this? -
Django - File name '' includes path elements exception, isn't the name supposed to include the path relative to MEDIA_ROOT?
I am working through a Django/Vue tutorial. I have a url setup 'latest-products' that should show the serialized Products but I am getting an exception when the thumbnail doesn't exist and is created with the make_thumbnail function in the Product class of models.py. This is the exception: Exception Type: SuspiciousFileOperation at /api/v1/latest-products/ Exception Value: File name 'uploads/winter3.jpg' includes path elements This is the result I am expecting: screenshot From the Django File documentation , the name is supposed to be "The name of the file including the relative path from MEDIA_ROOT." So, my question is why am I getting a SuspiciousFileOperation exception? #models.py from io import BytesIO from PIL import Image from django.core.files import File from django.db import models class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.slug}/' class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.category.slug}/{self.slug}/' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def get_thumbnail(self): if … -
How do I change django's default sqlite3 database to a more advanced one like MySQL?
I want to use a better database with my Django like postgresql or mysql. what are the steps in doing that? -
Integrating postgres to django
im trying to install psycopg2 to use postgres on my django app. Seems like the first step is to run the sudo apt install python3-dev libpq-dev, but when i do it hits me with this funky error - Unable to locate an executable at "/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home/bin/apt" (-1). I'm confused as to why its showing me a java error when i'm installing python-dev. Any help would be greatly appreciated! -
Problem with django I get KeyError: 'carriage' when I restart the server
Estoy intentaldo hacer un proyecto pero no funciona y no me deja hacer nada me sale un error KeyError: 'carro' y estoy intentando pero no funciona esto se encuentra en un archivo llamado context_processor.py ya colo en settings esto def importe_total_carro(request): total = 0 if request.user.is_authenticated==True: for key,value in request.session['carro'].items(): total=total+(float(value["precio"])*value["cantidad"]) return {"importe_total_carro":total} y esto en views class Carro: def init(self, request): self.request=request self.session= request.session carro = self.session.get("carro") if not carro: carro=self.session["carro"]={} else: self.carro=carro def agregar(self, producto): if(str(producto.id) not in self.carro.keys()): self.carro[producto.id]={ "producto_id":producto.id, "nombre":producto.nombre, "precio":str(producto.precio), "cantidad":1, "imagen":producto.imagen.url } else: for key, value in self.carro.items(): if key == str(producto.id): value["cantidad"]=value["cantidad"]+1 break self.guardar_carro() def guardar_carro(self): self.session["carro"]=self.carro self.session.modified=True def eliminar(self, producto): producto.id= str(producto.id) if poducto.id in self.carro: del self.carro[producto.id] self.guardar_carro() def restar_producto(self,producto): for key, value in self.carro.items(): if key == str(producto.id): value["cantidad"]=value["cantidad"]-1 if value["cantidad"]<1: self.eliminar(producto) break self.guardar_carro() def limpiar_carro(self): self.session["carro"]={} self.session.modified=True -
How to view others profile just like instagram website
i am stuck in a situation while creating a social media website in django .the problem i face is .The website i am working is just like Instagram, a user can upload image and other user can view it.So i made a page where when a user is loged in he can view his profile and he can see all his uploaded images.Then the problem comes i want also a page in which the other user can see other peoples profile just like instagram ,clicking on the name we goes to the profile of the person who upload the post.i want this feature to be implimented in my website but i can filter the model and get all the upload pics of other user into the new page but i was not able to get the detial of the user such as their profile pic bio etc....... i tried looping but the profile card get into lot of card because of the modes the bellow link is my html page to show the logined person profil but i want to see the others profile also profile html page to show profile detial of loged in person this is my views … -
Error in Django project: (fields.E120) CharFields must define a 'max_length' attribute
I am currently changing the models in my Django App,and I am getting a new issue I am having problems with to solve. I am pretty sure I get the error due to my models.py file, but I cant solve the problem. I have not found a solution online and it is driving me crazy. models.py from django.db import models class defense_mechanism(models.Model): defense = models.CharField(max_length=100) def __str__(self): return self.defense class attack(models.Model): actor = models.CharField(max_length=100) action = models.CharField(max_length=100) asset = models.CharField(max_length=100) defense = models.CharField(defense_mechanism) def __str__(self): return self.action class security_incident(models.Model): security_inc = models.CharField(max_length=100, primary_key=True) def __str__(self): return self.security_inc class adtree(models.Model): goal = models.ForeignKey(security_incident, on_delete=models.CASCADE) defense_mechanism = models.ManyToManyField(defense_mechanism) attack = models.ManyToManyField(attack) def __str__(self): return self.goal here is the full output of the error message django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: application.attack.defense: (fields.E120) CharFields must define a 'max_length' attribute. System check identified 1 issue (0 silenced). C:\Users\Bruker\PycharmProjects\hri\attack_defense_tree_generator> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line … -
Field 'id' expected a number but got ' '
I'm trying to get my item's id so I can save it in the user's profile. However, when I make the post request I get the error: Field 'id' expected a number but got ''. So how can I solve this so I can get the item's id and why is it not working in my code? if request.method=='POST' and 'anime_pk' in request.POST : anime_id = request.POST.get("anime_pk") anime = Anime.objects.get(id = anime_id) request.user.profile.animes.add(anime) messages.success(request,(f'{anime} added to wishlist.')) return redirect ('/search') animes = Anime.objects.all() The html: <form method="post"> {% csrf_token %} <section> <div class=row> <div class="col-md-4 col-sm-6 col-lg-3"> <div class="card"> <div class="card-body text-center"> <p class="card-title"> <b>{{anime.Title}}</b></p> <hr> <p class="card-text">Episodes: <b>{{anime.Episodes}}</b></p> <img src = {{anime.Image}} /> </div> </div> </section> <input type="hidden" value="{{anime.pk}}" name="anime_pk"> <button type="submit" class="btn btn-outline-primary" style="font-size:18px; border-radius: 50%">★</button> </form> -
JQuery ломает CSS стили
всем привет, сразу извиняюсь за возможно довольно глупый вопрос который скорее всего напрямую связан с моими кривыми руками, но, тем не менее есть проблема с тем что при подключении файлов JQuery в мой Django проект ломаются все стили на странице к которой подключаю, до подключения всё работает корректно. Я новичок и скорее всего просто чего-то не понимаю, и не могу уже какой день решить эту проблему, сразу скажу что я знаю про collect static и все те вещи которые нужно делать со статическими файлами, ибо стили работают нормально и в файле settings.py все пути указаны верно. код скрипта довольно простой и служит по большей части чисто для адаптивного меню, и скрытия некоторых тегов html по нажатию. JQuery код скрипта довольно простой и служит по большей части чисто для адаптивного меню, и скрытия некоторых тегов html по нажатию. $(document).ready(function() { // Менюшка и появляющиеся категории $('.nav_show_btn').click(function() { let display = $('.nav_show_links').css('display') if (display == 'none') { $('.nav_show_links').slideDown('100') } else { $('.nav_show_links').slideUp('100') } }) $('.category_btn').click(function() { let display = $('.categorys_container').css('display') if (display == 'none') { $('.categorys_container').slideDown('100') $('.category_btn').addClass('active') } else { $('.categorys_container').slideUp('100') $('.category_btn').removeClass('active') } }) // Профиль и его меню { let active; $('#main_inf_user').click(function() { if (active != 'off' | active == undefined) … -
Django model design for Shopping List. how to use ManytoMany relationship?
I am working on making django app to handle multiple shopping list. which should have ManytoMany field? Item model or List model? is this model optimal ? A list can have many items, many sublists, many associated store. And, except for List vs Sublist all the relationships are many to many. An item can be in many list, a store can be associated to many list. sublist is just putting the item in categories so I can also remove this model and add a category attribute to items. Item has m2m fields for List but should it also have m2m field for Sublist? a List need not have sublist so the item can be part of list or sublist in a list (like a folder/file structure) models.py: class List(models.Model): name = models.Charfield(max_length=125) date = models.DateField(default=django.utils.timezone.now) class Store(models.Model) : name = models.CharField(max_length=128) store = models.ManyToManyField(List) class Item(models.Model): item = models.CharField(max_length=128) price = models.FloatField(default=0.0) category = models.CharField(max_length=128, default=None) checked = models.BooleanField(default=None) store = models.ManyToManyField(List) class SubList(models.Model): name = models.Charfield(max_length=256) parent_list = models.ForeignKey(List) items = models.ManyToManyField(Item)