Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to use User ModelForm for log in?
I'm trying to use a modelForm for a login rather than a Form (to avoid repetition): class LoginForm(forms.ModelForm): class Meta: model = get_user_model() widgets = { "password": forms.PasswordInput(), } fields = ("email", "password") However, since the email field has a unique=True, and since forms can be used to create objects, when running is_valid() method on the form, I get an error: User with this E-mail already exists. What is the right way to handle this? Thanks. -
Docker on windows Vmmem grows with each rebuild of container
I have a Django + Gunicorn + Nginx website running in a docker container on windows 10 that's been working wonderfully. Every time that I update my source code I run the following command to rebuild the container: docker-compose up -d --build [servicename] This runs as expected, builds the container detached and then swaps them out when complete, Nginx stays running and looses connection for a second then boom, back up and running. Ill do this maybe 5-20 times a week depending on what I'm adding/fixing and pushing to production. the issue that I just came across was that the Vmmem process is growing by a factor of 1 each time, so when I run docker-compose up for the first time, memory usage will be about 3,000MB. When I run my rebuild, it will grow to 6,000 MB. and on and on.... Since the system I'm running on has 32GB of RAM, I didn't notice the mass amount of buildup until a few months in of running. Is this normal behavior from docker? and if so is there anything I can do to to alleviate the build up other than restarting the computer? -restarting docker does not solve the issue … -
django filter by fields that can change
I have this model : class Project(models.Model): state = models.CharField(max_length=7, default='#FFFF00') name = models.CharField(max_length=200, default="") price = models.FloatField(default=0) decision = models.TextField(blank=True, null=True) For example, if I want to filter all the projects named 'hello_project' with a price of 10, I can do this : projects = Project.objects.filter(Q(name='hello_project') & Q(price=10)) What I want to do is filter by lists that can change : fields = ["name", "price"] filters = ["hello_project", 10] Is there a way to do something like this that works ? (lists size can change) : projects = Project.objects.filter(Q({fields[0]}={filters[0]}) & Q({fields[1]}={filters[1]}) I've done this: def filter_projects(fields, filters): all_projects = Project.objects.all() filtered_projects = [] for i in range(len(fields)): for project in all_projects: if str(functions[fields[i]](project)) == str(filters[i])): filtered_projects.append(project) all_projects = filtered_projects filtered_projects = [] return all_projects It works but it's very long with a lot of projects so I want to know if I can do this in one line -
Annotating frequency of many to many objects in a query (Django)
I'm trying to annotate a product reports with the frequency at which a product appears on the report. I have the below so far which works, but it's counting the frequency products appear across all users reports, rather than the specific user. BarcodeScanProduct's are linked via m2m to barcodescanproduct and Products are linked by foreign key to BarcodeScanProduct's. user = request.user report, created = BarcodeScanReport.objects.get_or_create(user=user, complete=False) report_products = report.barcodescanproduct_set.all( ).annotate(instance_count=Count('product__barcodescanproduct__id') ).order_by('-product__status') Any ideas? -
Why do I get this TypeError in Django Cloudinary when running Debug=False?
So I have this Django project using django-cloudinary-storage for media files, deployed with Heroku. I know it's silly but I've been running the app with Debug=True. Everything was fine, all static and media files were served perfectly. But then I realized doing so is critical to the security of my app, so I re-deployed it with Debug=False. This is when I got this error message saying TypeError: expected str, bytes or os.PathLike object, not NoneType (Full traceback at the bottom) Let me show you my settings.py. I don't see what I've done wrong, but I keep getting the error. What do you think is the problem? (...) STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CLOUDINARY_STORAGE = { 'CLOUD_NAME' : '', # some string 'API_KEY' : config("CLOUDINARY_API_KEY"), 'API_SECRET' : config("CLOUDINARY_API_SECRET"), } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' And I also have this in my urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Full traceback. Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) … -
Django models - inherit from two classes: each with a custom Manager?
I've got an issue where I have a Model that is inheriting from two other AbstractModel classes. Both of the AbstractModel use a custom Manager to to point all queries to a particular database. Here is the first Model: # appA / models.py class AbstractA(models.Model): objects = managers.AManager() class Meta: abstract = True # appA / managers.py class AManager(models.Manager): def get_queryset(self): return super(AManager, self).get_queryset().using("database_a") This is the secondary Model that I utilize in order to do 'soft deletions' (from this article) # appA / models.py class ASoftDeletionModel(models.Model): deleted_at = models.DateTimeField(blank=True, null=True) objects = SoftDeletionManager() all_objects = SoftDeletionManager(alive_only=False) class Meta: abstract = True def delete(self): self.deleted_at = timezone.now() self.save() def hard_delete(self): super(ASoftDeletionModel, self).delete() # appA / managers.py class SoftDeletionManager(models.Manager): def __init__(self, *args, **kwargs): self.alive_only = kwargs.pop("alive_only", True) super(SoftDeletionManager, self).__init__(*args, **kwargs) def get_queryset(self): if self.alive_only: return ( SoftDeletionQuerySet(self.model) .using("database_a") .filter(deleted_at=None) ) return SoftDeletionQuerySet(self.model).using("database_a") def hard_delete(self): return self.get_queryset().using("database_a").hard_delete() class SoftDeletionQuerySet(models.QuerySet): def delete(self): return super(SoftDeletionQuerySet, self).update( deleted_at=timezone.now(), using="database_a", ) def hard_delete(self): return super(SoftDeletionQuerySet, self).delete(using="database_a") def alive(self): return self.using("database_a").filter(deleted_at=None) def dead(self): return self.using("database_a").exclude(deleted_at=None) I've created another simple model for making comments on a thing that inherits from both of those models like so: class Comment( ASoftDeletionModel, AbstractA ): thing = models.ForeignKey( Thing, on_delete=models.PROTECT, related_name="%(class)ss" ) … -
How can I get count of pages in LimitOffsetPagination django rest framework?
If my code looks like this: class SimpleLimitOffsetPagination(LimitOffsetPagination): offset_query_param = 'page' max_limit = 100 default_limit = 5 def get_paginated_response(self, data): return Response({ 'count': self.count, 'max_page': 'needs count of pages', 'results': data }) Is that possible to get count of pages? or do we have another solution? It's important to have an opportunity using limit filed. -
Problem with add and change instanse in django admin
I try from admin to add or change instance of model - CompletedWork. Error is: TypeError at /admin/ReportingTool/completedwork/68/change/ init() missing 1 required positional argument: 'user' my model: class CompletedWork(models.Model): period = models.ForeignKey(directory.Period, on_delete=models.SET('deleted date'), ) worker = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted worker'), related_name='worker_do', default=settings.AUTH_USER_MODEL ) work_done = models.ForeignKey(directory.WorksType, on_delete=models.SET('deleted works type')) work_scope = models.FloatField(blank=True, null=True) work_notes = models.CharField(_("Comments"), max_length=70, blank=True, null=True, ) record_author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted user'), related_name='record_author', auto_created=True, ) record_date = models.DateTimeField(auto_now=True) checked_by_head = models.BooleanField(default=False) active = models.BooleanField(default=True) def __repr__(self): return f'{self.period}, {self.worker}, {self.work_done}' def __str__(self): return self.__repr__() def is_active(self): if self.active: return True return False my form: class CompletedWorkForm(forms.ModelForm): class Meta: model = CompletedWork fields = ( 'period', 'worker', 'work_done', 'work_scope', 'work_notes', ) def __init__(self, user, *args, **kwargs): if kwargs.get('record_author'): self.user = kwargs.pop('record_author') super(CompletedWorkForm, self).__init__(*args, **kwargs) if user.struct_division: if user == user.struct_division.head: self.fields['worker'] = forms.ModelChoiceField( queryset= CustomUser.objects.filter(struct_division= user.struct_division).order_by('last_name') | CustomUser.objects.filter(struct_division__management_unit= user.struct_division).order_by('last_name') ) elif StructuralDivisions.objects.filter(curator=user): sd_user_curator = StructuralDivisions.objects.filter(curator=user) self.fields['worker'] = forms.ModelChoiceField( queryset= CustomUser.objects.filter(struct_division__in=sd_user_curator) | CustomUser.objects.filter(id=user.pk) ) else: self.fields['worker'] = forms.ModelChoiceField( queryset=CustomUser.objects.filter(id=user.pk) ) self.fields['work_done'] = forms.ModelChoiceField( queryset=WorksType.objects.filter(available_to=user.struct_division) ) def save(self, commit=True): obj = super(CompletedWorkForm, self).save(commit=False) if commit: obj.user = self.instance.record_author obj.save() return obj my view: class EditCompletedWorkView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = CompletedWork form_class = CompletedWorkForm template_name = 'completed_work_edit.html' context_object_name = … -
Using the URLconf defined in , Django tried these URL patterns, in this order:
I have a django app. And some upload functionaliteit. The page with the upload function is loading correct. But after I do a submit. I get this errror: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/main/ Using the URLconf defined in schoolfruitnvwa.urls, Django tried these URL patterns, in this order: admin/ The current path, main/, didn’t match any of these. so this is the views.py from .forms import ProfileForm from .models import UploadFile # Create your views here. """ def store_file(file): with open("temp/hello.png", "wb+") as dest: for chunk in file.chunks(): dest.write(chunk) """ class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() return HttpResponseRedirect("/") return render(request, "main/create_profile.html", { "form": submitted_form }) urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.CreateProfileView.as_view()) ] forms.py: class ProfileForm(forms.Form): upload_file = forms.FileField() So my question is: what I have to change? -
Django to Postgres connection issues on AWS server
I'm setting up an Amazon AWS test server with Django on which I use Postgres as a database. This was my way here: $ sudo apt update $ sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib I downloaded my files from Github and created a virtual environment for it and inside I installed psycopg2. $ pip install psycopg2 How I configured Postgres: $ sudo -i -u postgres $ psql $ createuser --interactive (super user); $ createdb Filme; Some other information that may be useful about Postgres: $ service postgresql status > postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset:> Active: active (exited) since Wed 2022-10-05 17:08:25 UTC; 20h ago Main PID: 977 (code=exited, status=0/SUCCESS) CPU: 1ms Oct 05 17:08:25 ip-172-31-29-151 systemd[1]: Starting PostgreSQL RDBMS... Oct 05 17:08:25 ip-172-31-29-151 systemd[1]: Finished PostgreSQL RDBMS. $ pg_lsclusters > Ver Cluster Port Status Owner Data directory Log file 14 main 5432 online postgres /var/lib/postgresql/14/main /var/log/postgresql/postgresql-14-main.log In my settings.py file of my project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'Filme', } } O erro ocorre quando eu tento rodar a migração para o novo banco de dados: $ (env) $ python3 manage.py migrate > Traceback (most recent call last): File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", … -
Is it possible to use ImageFields from other models via inheritance? (django)
I have two models with imageFields, and want to have the same images there, to display them at the admin-page... My two models: class Produkt(models.Model): STATUS_CHOICES = ( ('draft', 'offline'), ('published', 'online'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') image = models.ImageField(upload_to='images', height_field=None, width_field=None, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') class Meta: ordering = ('-publish',) def __str__(self): return self.title objects = models.Manager() published = PublishedManager() def get_absolute_url(self): return reverse('app:produkt_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) tags = TaggableManager() class Bestellung(models.Model): def two_week_hence(): return timezone.now() + timezone.timedelta(weeks=2) produkt = models.ForeignKey(Produkt, on_delete=models.CASCADE, related_name='bestellung') def get_image(self): return self.produkt.image versand_bis = models.DateTimeField(default=two_week_hence) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'hat Produkt {self.produkt} bestellt' and my admin.py looks like this: @admin.register(Produkt) class ProduktAdmin(admin.ModelAdmin): def image_tag(self, obj): return format_html('<img height="100" src="{}" />'.format(obj.image.url)) image_tag.short_description = 'Image' list_display = ('title', 'image_tag', 'image', 'kategorie', 'price', 'publish', 'status') list_filter = ('created', 'publish', 'status', 'price',) search_fields = ('title',) prepopulated_fields = {'slug': ('title',)} date_hierarchy = 'publish' @admin.register(Bestellung) class BestellungAdmin(admin.ModelAdmin): def image_tag(self, obj): return format_html('<img height="100" src="{}" />'.format(obj.get_image.url)) image_tag.short_description = 'Image' list_display = ('produkt', 'image_tag', 'versand_bis', 'created', 'active') list_filter = … -
how can I import one model from one app to another?, been doing it the standard way but its not working [closed]
This is the directory layout/related files and settings: When I run migrations I get this error message : I just want to import the group class from the models.py in group directory to my post models.py. I have tried many changes to the structure of the import code with no success. I tried : from simplescoial.groups.models import Groups This seems to have no issue with Pycharm (no red underlines and picks up autocomplete at all stages) but on the terminal I get a NoModuleFoundError it cant find simplesocial.groups. -
Creating a single-column dataframe in Pandas from a Django queryset
I'm trying to create a dataframe containing the values from field_1 and field_2 in a single column. I haven't used pandas a whole lot before, so I'm sure this is naive. # Create a dataset in CSV format field_names = ["work_description", "comments"] writer = csv.writer(open("dataset.csv", "w"), quoting=csv.QUOTE_ALL, delimiter=",") writer.writerow(field_names) for instance in WorkOrder.objects.all(): writer.writerow([str(getattr(instance, f)) for f in field_names]) # Read CSV data_frame = pd.read_csv("dataset.csv", index_col=0) # Combine columns df2 = data_frame.apply(lambda x: ", ".join(x[x.notnull()]), axis=1) If I'm working with a fairly large dataset, is there a way I can make this more efficient? I would like to eliminate the step that creates the CSV entirely, if possible. If anybody can point me in the right direction, that'd be fantastic. -
Django Error: __init__() takes 1 positional argument but 2 were given
I am new to Django and I'm trying to create my first project following a tutorial from Udemy, but I encounter this error. My project has the following folder structure: -demo __ init__.py admin.py apps.py models.py tests.py urls.py -views.py -first __ init__.py asgi.py settings.py urls.py wsgi.py views.py: from django.shortcuts import render from django.http import HttpRequest def first(request): return HttpRequest('1st message from views') demo/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.first), ] first/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('demo/', include('demo.urls')), path('admin/', admin.site.urls), ] Both __ init__.py files are empty error: TypeError at /demo/ __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/demo/ Django Version: 3.2.16 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: D:\Python\DJANGO\first-project\demo\views.py, line 6, in first Python Executable: D:\Python\DJANGO\first-project\venv\Scripts\python.exe Python Version: 3.7.6 Python Path: ['D:\\Python\\DJANGO\\first-project', 'D:\\Python\\DJANGO\\first-project', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37', 'D:\\Python\\DJANGO\\first-project\\venv', 'D:\\Python\\DJANGO\\first-project\\venv\\lib\\site-packages'] Server time: Thu, 06 Oct 2022 12:34:45 +0000 -
Im getting error 'str' object has no attribute 'status_code' [closed]
I've seen every thread i could find for that problem and there a acutally quite a lot but i cant figure out the problem. Im trying some unit testing on one of my django views. It used to pass the test but now it breaks and prints: AttributeError: 'str' object has no attribute 'status_code' unit test: def test_delete_flight(self): self.client.force_login(self.user) response = self.client.get('/agriculture/delete_flight/' + str(self.flight)) self.assertEqual(response.status_code, 302) self.assertRedirects(response.url, '/agriculture/flights') The error occurs on assertEqual for some reason. I tried printing out response.status_code, 302 and everything seems normal, its basically (302, 302) so i cant figure out where it is breaking. error ERROR: test_delete_field Traceback (most recent call last): File "/home/dukis/Documents/agrominds/src/agriculture/tests/test_views.py", line 329, in test_delete_flight self.assertRedirects(response.url, '/agriculture/flights') File "/home/dukis/Documents/venv-agrominds/lib/python3.10/site-packages/django/test/testcases.py", line 358, in assertRedirects response.status_code, status_code, AttributeError: 'str' object has no attribute 'status_code' -
Heroku : (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)"
I am trying to deploy my django app on heroku. While deploying I am getting this error. I am not sure if there is something wrong with my settings file or heroku setup. Python 3.10, Django 4.1.2 Here is the database settings I am using import dj_database_url DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } This is the database url from heroku config DATABASE_URL: postgres://ewdtekjzxnzuuo:b16a983b5c9cfb7fe1f9aaab58f1ac21bea073fdb059c0fa7356600c4a19030b@ec2-34-200-205-45.compute-1.amazonaws.com:5432/da0ttf53ppludi Error message -> MySQLdb.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 97, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/model_checks.py", line 36, in check_all_models errors.extend(model.check(**kwargs)) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1533, in check *cls._check_indexes(databases), File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1952, in _check_indexes connection.features.supports_expression_indexes File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line … -
How to delete virtual environment completely on Docker?
I am trying to make a Django and Postgre container using docker-compose. I followed this tutorial: https://docs.docker.com/samples/django/. I am using Windows and executed the following command: docker-compose run web django-admin startproject composeexample . After that, I modified my Dockerfile to include some apt-get update # syntax=docker/dockerfile:1 FROM python:3 RUN apt-get update RUN apt-get install -y libgdal-dev ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt /usr/src/app/ RUN pip install -r requirements.txt COPY . /usr/src/app/ I deleted the created composeexample folder and data folder, and run the command again. docker-compose run web django-admin startproject composeexample . This time. I get the following error: CommandError: /usr/src/app/manage.py already exists. Overlaying a project into an existing directory won't replace conflicting files. ERROR: 1 Somehow Docker thinks the files still exist from the 1st execution. Even if I change the name of the parent directory to change the container name, I still get the error. How can I remove the environment completely from my 1st execution? -
Django RetrieveAPIView where is the rights place to do some small db update
I'm using Django REST framework, and still quite new to it.. I Want to retrieve a message from db with generics.RetrieveAPIView method, which I did.. But I want to also set the read field to true at the database. Where is the place to do it (maybe in the serializer)? This is the idea: class MessageDetail(generics.RetrieveAPIView): serializer_class = MessageSerializer permission_classes = [IsAuthenticated] queryset = AppUserMessage.objects.all() AfterTheRequst(self) # This is what I want to do obj.read_at = time.now() -
Django, no module named 'polls' - Django reusable apps
I am at the end of the getting started of the Django project, I built the package as described in the Advanced tutorial: How to write reusable apps. I got a tar.gz file that I installed not in a virtual environment using the command python.exe -m pip install --user C:\Users\[PRIVACY AMEND]\Documents\python\mysite\django-polls\dist\django-polls-0.1.tar.gz. The module is installed as shown in the output of python.exe -m pip list below. Package Version ------------ ------- asgiref 3.5.2 Django 4.1.1 django-polls 0.1 lxml 4.9.1 sqlparse 0.4.2 tzdata 2022.2 But when I migrate, I get the error no module named polls... I have done all steps of the tutorial on Windows and Debian (on WSL), using explicitly python.exe -m pip when interacting with pip, checked the logs for any other error, and checked the PYTHONPATH and where the package is installed given by python.exe -m pip show django-polls, the output is just below. Name: django-polls Version: 0.1 Summary: A Django app to conduct web-based polls. Home-page: https://www.example.com/ Author: Your Name Author-email: yourname@example.com License: BSD-3-Clause # Example license Location: c:\users\[PRIVACY AMEND]\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages Requires: Django Required-by: Does anyone have a hint ? -
encrypt and decrypt Django rest framework field as superuser?
I read the answers here: plaintext API secret and have read about encryption and decryption of API keys and secrets. In django Rest Framework, 1- store the API key and Secret in plain text in Django REST framework DB. 2- An endpoint, only accessible by superuser(I could limit this further to IP address), gives all users API keys and secrets to be used in another script. TLS communication. I am not sure if this is the best approach. -
Django how to create a dynamic field
I don’t understand the principle of a dynamic field. In my case I have 3 classes on my models: 1- Product : name, ref, description and availability (availability should not be coded in the database and be define dynamicly. It should return available or out of stock). 2- Location : name of the location. 3- Stock : foreign key for Product and foreign key for Location and number a product(INT). The idea is : if in Stock there is 1 or more of a product, the products endpoint shows available. If 0 it shows out of stock. Is that even possible ? How ? Thank you for all the help. -
CKEditor 5 open image in full screen
I am using CKEditor 5 in a Django project, where I display the created content on a front end page. My content wrapper is quite narrow, and therefore any images that I add via the CKEditor are small. I need a way to make them clickable and either open the image URL in a new tab or have a full screen Bootstrap Modal that shows the 100% width image. Would this be achievable without altering the CKeditor JS files? Can I create a JS script that replaces CKEditor image tags with my own HTML code on every page load in the front end? Or can it be done so that the needed HTML code is directly saved to the database? (then can the CKEditor understand that new code when I edit the content?). I hope you can help with some tips. No code needed. Thank you! -
Getting error when using custom manytomany field when save in django admin
i have a problem in django admin. When i submit my forms in django admin i'm getting Cannot assign "<QuerySet [<ProductAttributeValue: color : red>, <ProductAttributeValue: size : L>]>": "StockJoinProductAttributeValue.prod_att_value" must be a "ProductAttributeValue" instance. I know the problem. Here i have to pass object not queryset. But i don't know how to do it. models.py class Stock(models.Model): #Implement dynamic select options sku = models.ForeignKey(SubProduct, on_delete=models.PROTECT, related_name="sub_product", default=1) product_attribute_value_id = models.ManyToManyField(ProductAttributeValue, blank=True, related_name="product_attribute_value", through="StockJoinProductAttributeValue" ) is_default = models.BooleanField(default=False, verbose_name=_("Default selection"), help_text=_("format: true=stock visible") ) units = models.IntegerField( default=1, unique=False, null=False, blank=False, verbose_name=_("units/ qty of stock"), help_text=_("format: required, default=0") ) units_sold = models.IntegerField( default=0, unique=False, null=False, blank=False, verbose_name=_("units/ qty of sold products"), help_text=_("format: required, default=0") ) def __str__(self): return '{}'.format(self.sku) class ProductAttributeValue(models.Model): product_attribute = models.ForeignKey( ProductAttribute, on_delete=models.PROTECT, related_name="product_attribute") attribute_value = models.CharField( max_length=255, unique=True, null=False, blank=False, verbose_name=_("attribute value"), help_text=_("format: required, max-255") ) class Meta: ordering = ['product_attribute'] def save(self, *args, **kwargs): self.attribute_value = self.attribute_value.lower() return super().save(*args, **kwargs) def __str__(self): return '{} : {}'.format(self.product_attribute.name, self.attribute_value) class StockJoinProductAttributeValue(models.Model): stock_id = models.ForeignKey(Stock, models.PROTECT) prod_att_value = models.ForeignKey(ProductAttributeValue, on_delete=models.PROTECT) class Meta: unique_together = ['prod_att_value', 'stock_id'] admin.py class StockJoinProductAttributeValueForm(forms.ModelForm): class Meta: model = StockJoinProductAttributeValue fields = ['stock_id','prod_att_value'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['prod_att_value'] = forms.ModelMultipleChoiceField( queryset=ProductAttributeValue.objects.all(), ) class … -
how to convert tree query set into dictionary?
book_category_list=[] for book_category in BookCategory.objects.filter(parent__isnull = True): book_category_list.append(book_category.get_family())** now the book_category_list in tree query set format. I need to list categories in a tree structure.so I need to convert this book_category_list into dictionary format. BookCategory is a MPTT Model? -
Django ORM: possible to annotate a QuerySet with a field across a normal AND a reverse foreign key relation?
Assume the following model classes: class Person(models.Model): # ...irrelevant fields... class PersonEmailLogin(AbstractBaseUser): email = models.EmailField() person = models.ForeignKey(Person) # ...more irrelevant fields... class SomeModel(models.Model): person = models.ForeignKey(Person) # ...more irrelevant fields... Note: these are all unmanaged models—we're developing against an existing database that is not managed by us. While not expressed in the code above, it's guaranteed outside Django that for each Person, 0–1 PersonEmailLogins will point to it. I want to retrieve SomeModel objects, but annotate each row with the email field from PersonEmailLogin. This has to be done with an outer join, since not all Persons have PersonEmailLogins. SomeModel doesn't have a direct foreign key to PersonEmailLogin, but as they both point to Person, it is possible to associate a SomeModel instance to a single PersonEmailLogin instance, or NULL where a given Person doesn't have any PersonEmailLogins pointing to it. When using SomeModel.objects.raw(), the currently functioning query looks like this: SELECT sm.*, pel.email FROM somemodel sm LEFT OUTER JOIN personemaillogin pel ON sm.person_id = pel.person_id; I would prefer to use normal QuerySets instead of RawQuerySets, since it would be more convenient to do more filtering operations down the line, but I haven't found a way to express this …