Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using other models in Django Manager causes ImportError: partially initialized module (due to circular dependency)
I have the following function in my UserManager that I use with my CustomUser model in my django app. from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): ... def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user I needed to create a corresponding UserProfile object when a user is registered, so I updated the _create function as follows: from profiles.models import UserProfile class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() # Create the user profile UserProfile.objects.create(user=user) return user But this throws: ImportError: cannot import name 'CustomUser' from partially initialized module 'user s.models' (most likely due to a circular import) (../users/models.py) My CustomUser is defined as follows: class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] auth_provider = models.CharField( max_length=10, default=AUTH_PROVIDERS.get('email')) objects = UserManager() And the UserProfile model is defined as follows: class UserProfile(models.Model): user = models.OneToOneField( CustomUser, null=True, on_delete=models.CASCADE, related_name="profile") … -
How to solve 'ImproperlyConfigured at /admin/filebrowser/browse/ Error finding Upload-Folder (site.storage.location + site.directory). '
My project structure is main -temp project -settings.py I want to browse main/temp/ folder while navigating to the link: localhost:8000/admin/filebrowser/browse Please help me with the correct settings of the django file browser, since the settings are not clear in the official documentation. https://django-filebrowser.readthedocs.io/en/3.13.2/settings.html#settings in settings.py from filebrowser import settings FILEBROWSER_DIRECTORY = getattr (settings, "FILEBROWSER_DIRECTORY", "main/temp") -
How to rectify account activation error in django
I'm trying to click on an email activation link so as to activate a user account after submitting a registration form but I keep getting this error: The connection for this site is not secure; 127.0.0.1 sent an invalid response.. I ought to be redirected to the dashboard. Account is successfully created since the new user appears in the database but clicking on the activation link sent to the email throws back an error. I'm following a tutorial though, but I can't figure out why the problem occurs. url.py urlpatterns = [ path('activate/<slug:uidb64>/<slug:token>)/', views.account_activate, name='activate'), path('dashboard/', views.dashboard, name='dashboard') ] templates account-activation_email.html: {% autoescape off %} Great {{ user.user_name }}! Please click on the link below to activate your account https://{{ domain }}{% url 'account:activate' uidb64=uid token=token %} {% endautoescape %} register.html <form class="account-form p-4 rounded col-lg-10 mx-auto" method="post"> {% csrf_token %} <h3 class="mb-2 font-weight-bold">Create an account</h3> <p class="mb-4">Sign Up</p> <label>{{ form.user_name.label }}<span class="text-muted small"> (Required)</span></label> {{ form.user_name }} <label>{{ form.email.label}}<span class="text-muted small"> (Required)</span></label> {{ form.email }} <label>{{ form.company.label}}<span class="text-muted small"> (Required)</span></label> {{ form.company }} <label>{{ form.license_number.label}}<span class="text-muted small"> (Required)</span></label> {{ form.license_number }} <label>{{ form.state.label}}<span class="text-muted small"> (Required)</span></label> {{ form.state }} <label>{{ form.city.label}}<span class="text-muted small"> (Required)</span></label> {{ form.city }} <label>{{ form.address.label}}<span … -
How can I unit test a POST request with custom permissions in Django Framework?
everyone. I hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development. I only know Python, so Django REST framework my best fit for the moment. Right now I'm trying to implement Unit tests for my API. It's a simple model to implement CRUD on the names and heights of NBA players. In my models I added a class to describe this data and translated it to a view with ModelViewSets. I wanted to make this data editable only for a specific type of user (a read-write user), only readable for another (read-only user) as well as unaccesible to non-authenticated users. To do so, I created a custom User Model and translated it to my views with a custom permission. Now I want to write a few Unit tests to check that: r/w user can create a new player r/w user can get a list of players r/o user cannot create a new player r/o user can get a list of players unauthenticated user cannot create a new player unauthenticated user cannot get a list of players So far I've managed to run unit tests on my GET REQUEST with an OK output. But … -
Uploading image is not creating media file
Guys I'm new to django I tried uploading images in the imagefield but it's not creating media folder and the database image column is also blank. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py class Hotel(models.Model): name = models.CharField(max_length=50) hotel_Main_Img = models.ImageField(upload_to='images/') image.html <form method="POST" enctype="multipart/form-data> {% csrf_token %} <input type="file" class="form-control" id="customFile" name="image"/></div> </form> Even tried manually creating the media file Django. Still nothing!! Any help Will be appreciated -
Django Admin 403 - Forbidden: Access is denied IIS
first of all I apologize for my bad English. Did I upload the Django project to the windows server, but when I added data from the admin panel, the result I got is as follows. "403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied." Settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "home", 'django.contrib.sitemaps' ] MIDDLEWARE = [ 'htmlmin.middleware.HtmlMinifyMiddleware', 'htmlmin.middleware.MarkRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'umy.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'umy.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' #STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') web.config <?xml version="1.0" encoding="utf-8"?> … -
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!