Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django serializer requiring a dict instead of a model instance
I'm trying to make a really simple serialization in a viewset in django, but my serializer, which should require the instance to be serialized, is requiring a dict. This is my custom serializer: class JSONAPIModelSerializer(serializers.ModelSerializer): def __init__(cls, *args, **kwargs): if kwargs.get('many', False) is True: context = kwargs.get('context', {}) context.update({'is_many': True}) kwargs.update({'context': context}) return super().__init__(cls, *args, **kwargs) def format_object(self, instance, attributes: dict, meta = None, relationships = None, links = None, is_many: bool = False) -> dict: jsonapi_data = { 'type': instance.__class__.__name__.lower() if not getattr(self.Meta, 'resource_type', None) else None, 'id': str(instance.id), 'attributes': attributes, } jsonapi_data.update({'relationships': relationships}) if relationships else None if is_many: jsonapi_data = { 'data': jsonapi_data } jsonapi_data.update({'meta': meta}) if meta else None jsonapi_data.update({'links': links}) if links else None return jsonapi_data def get_attrs(self, instance): return {} def get_meta(self, instance): return None def get_links(self, instance): return None def get_relationships(self, instance): return None def to_representation(self, instance): return self.format_object( instance=instance, is_many=self.context.get('is_many', False), attributes=self.get_attrs(instance), meta=self.get_meta(instance), relationships=self.get_relationships(instance), links=self.get_links(instance) ) class AnimeSerializer(JSONAPIModelSerializer): class Meta: model = Anime fields = '__all__' resource_name = 'anime' def get_attrs(self, instance): return { 'titles': { 'en': instance.title_en, 'es': instance.title_es, 'en_jp': instance.title_ro, 'ja_jp': instance.title_jp }, 'titleCanonical': instance.title_canonical, 'abbreviatedTitles': [i.value for i in instance.titles_abbreviated.all()], 'otherTitles': [i.value for i in instance.titles_others.all()], 'description': instance.description, 'coverImage': … -
Google removed less secure option and facing SMTP problem
Less secure apps & your Google Account To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password. Important: This deadline does not apply to Google Workspace or Google Cloud Identity customers. The enforcement date for these customers will be announced on the Workspace blog at a later date. -
Django: make a list of column elements of selected rows
I'm new on Django and SQL and I'm trying to solve same simple problems to start to understand them. I have 3 models: Client, Product and Order. I want to list the products ordered by a client. The models: class Client(models.Model): name = models.CharField(max_length=32) ..... class Product(models.Model): product_name = models.CharField(max_length=32) ..... class Order(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) ..... My solution was: client= Client.objects.get(id=1) # target client orders = client.order_set.all() # or alternatively orders = Order.objects.filter(client=client) list_of_orders=[order.product for order in orders] My question: is there a better solution that uses some features of Django the get the list instead of the for loop? Thanks for any help. -
How to store list in Django model field while using SQLite
Hii Everyone here i am stuck with the issue that i need to insert the list [ ] in the model field while using SQLite, Group_Model.py: class ClassificationGroup(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) classification_id = models. [what do i take here to make it capable to store list of ids that will be related to the classification table.] Hope i will get the answer for this problem, Thanks in advance. -
Django Rest Framework not showing updated field until server restart
I am using DFR. when I send patch request for updating Patient record it changes in database and I can see it in admin panel, yet the response api request doesn't change until I restart the server. Patient Model: class Patient(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) birthdate = models.DateField(auto_now_add=False, null=True, blank=True) nationalCode = models.CharField(max_length=10) address = models.TextField(blank=True) cellphone = models.CharField(max_length=15, blank=True) haveInsurance = models.BooleanField(default=False) insuranceNumber = models.CharField(max_length=20, blank=True) image = models.ImageField(null=True,blank=True, upload_to=patient_image_file_path) patientHistory = models.ForeignKey( 'PatientHistory', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.firstName + ' ' + self.lastName Patient Viewset: class PatientViewSet(viewsets.ModelViewSet): """viewset for listing and creating patients""" serializer_class = serializers.PatientSerializer queryset = Patient.objects.all().order_by('-lastName') authentication_classes = (TokenAuthentication,) permission_classes = (IsAdminUser | IsObjectOwner,) def get_queryset(self): firstName = self.request.query_params.get('first_name') lastName = self.request.query_params.get('last_name') insuranceNumber = self.request.query_params.get('insurance_number') cellphone = self.request.query_params.get('cellphone') queryset = self.queryset if firstName: queryset = queryset.filter(firstName=firstName) if lastName: queryset = queryset.filter(lastName=lastName) if insuranceNumber: queryset = queryset.filter(insuranceNumber=insuranceNumber) if cellphone: queryset = queryset.filter(cellphone=cellphone) return queryset def perform_create(self, serializer): if self.request.user.is_staff: email = self.request.data['email'] cellphone = self.request.data['cellphone'] name = self.request.data['firstName'] + " " + self.request.data['lastName'] if get_user_model().objects.filter(email=email).exists(): user = get_user_model().objects.get(email=email) else: user = get_user_model().objects.create_user( email=email, password=cellphone, name=name ) else: user = self.request.user haveInsurance = True if 'insuranceNumber' in … -
How to edit M2M field in Django in model?
I need to create a form that can edit. How to do it? If i just use {{ form.analog }} it oly shows form. But it doesnt work. With my wariant in only shows none view def editpart(request, id): added = '' error = '' PartAllView = Part.objects.order_by('-id') part = Part.objects.get(id=id) if request.method == 'POST': part.brand = request.POST.get("brand") part.favorite_fruits = request.POST.get("analog") part.save() added = 'Запчасть успешно отредактирована' form = PartForm() ... context_object_name = "part" return render(request, 'kross/editpart.html', data) form ... "analog": SelectMultiple(attrs={ 'multiple': 'multiple', 'name': 'favorite_fruits', 'id': 'fruit_select', }), ... -
django channel WebsocketCommunicator connect test
Returns a json message on successful connection I want to test this value, how do I do it? test.py communicator = WebsocketCommunicator(application, "/test/", ) connected, _ = await communicator.connect() consumer.py class ExchangeRateConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json({...}) -
Django is_active field is not changing
I'm using django 4.0 when i change the is_active to False from django admin, it doesn't make any changes to the object, I have override the save method in models models.py class Topic(CreatedModel, DatedModel): name = models.CharField( max_length=255, unique=True, null=False, ) slug = models.SlugField( max_length=255, unique=True, help_text="A unique field used for creating Topics in Kafka" ) category = models.CharField( max_length=255, blank=True, choices=CATEGORY, help_text="Default for constant value updates" ) selected_model = models.CharField( max_length=255, choices=ALERT_MODELS, unique=True, help_text="The Model for sending updates to Kafka" ) is_active = models.BooleanField( default=True ) def save(self, *args, **kwargs): if self.pk is None: print("New object topic") topic_name = self.slug invoke_kafka_topic_create.delay(topic_name) super().save(*args, **kwargs) def __str__(self): return self.slug admin.py class TopicManager(admin.ModelAdmin): def save_model(self, request, obj, form, change): if getattr(obj, 'created_by', None) is None: obj.created_by = request.user obj.save() else: obj.modified_by = request.user obj.save() Can anyone advise ? The problem started when i added the save() in models.py -
How to auto-populate django's admin.ModelAdmin.search_help_text with verbose field names of parameters defined in admin.ModelAdmin.search_fields
I understand that Django offers out-of-box customization of the django-admin's changelist search functionality via its admin.ModelAdmin.search_fields and admin.ModelAdmin.search_help_text parameters. I want to take this a bit further by having django auto-populate the admin.ModelAdmin.search_help_text parameter with the verbose_name of the fields specified in admin.ModelAdmin.search_fields. For example, consider the following code: class FinancialYearAdmin(admin.ModelAdmin): fields = ['financialYearEnding'] list_display = ('financialYearEnding', 'dbEntryCreationDateTime', 'dbLastModifiedDateTime') search_fields = ['financialYearEnding'] search_help_text = "Seach here using the following fields in the database:" for searchField in search_fields: search_help_text += FinancialYear._meta.get_field(searchField).verbose_name It outputs the following search experience: However, it has the following limitations: The search box's help text, completely ignores the newline escape character. The last 3 lines have to be repeated in every ModelAdmin class that I create, albeit with change in the Model class name. Is there a way whereby I could write those last 3 lines of code to either have the search_help_text auto-populated from the search_fields, or, have the search_help_text populated by making a function call without having to repeat the code across all child ModelAdmin classes? Maybe through inheritance from an base abstract ModelAdmin class? [Note:] financialYearEnding, dbEntryCreationDateTime and dbLastModifiedDateTime are all parameters in the FinancialYear Model class. -
Django AttributeError: 'tuple' object has no attribute 'backend'
I am trying to implement authentication by Simple JWT Authentication. I am using custom User models and I also want to change the authentication method because my password are encrypted using bcrypt and I have to follow that. my project name is backend and app name is custom_auth. setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'custom_auth', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } AUTH_USER_MODEL = 'custom_auth.User' AUTHENTICATION_BACKENDS = ('custom_auth.custom_authenticate.CustomAuthentication',) I also included SIMPLE_JWT in my setting given Here. custom_authenticate.py import bcrypt from .models import User from rest_framework import authentication class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self,request,mail=None,password=None): if mail is not None and password is not None: print(mail,password) user = User.objects.get(mail=mail) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8')) print(is_check) if is_check: return (user,None) else: return None else: return None def get_user(self,user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None When I am providing the mail and password and by printing the is_check, I found it to be True. Full error [17/Jun/2022 13:25:15] "GET /api/token/ HTTP/1.1" 405 7630 Internal Server Error: /api/token/ Traceback (most recent call last): File "C:\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
Sort Django queryset with custom order
Let's say I have the following Django model: class Todo(models.Model): class Priority(models.IntegerChoices): HIGH = 1, "High" LOW = 2, "Low" MEDIUM = 3, "Medium" title = models.CharField(max_length=255) priority = models.PositiveSmallIntegerField(choices=Priority.choices, db_index=True) And the following test data via factory-boy: import factory from factory.django import DjangoModelFactory class TodoFactory(DjangoModelFactory): class Meta: model = Todo title = factory.Sequence(lambda n: f"Todo {n}") def test_custom_db_sort(): todo1 = TodoFactory(priority=Todo.Priority.MEDIUM) todo2 = TodoFactory(priority=Todo.Priority.HIGH) todo3 = TodoFactory(priority=Todo.Priority.LOW) todo4 = TodoFactory(priority=Todo.Priority.MEDIUM) todo5 = TodoFactory(priority=Todo.Priority.HIGH) I want to fetch the Todo objects from the database and sort from HIGH -> LOW priority. Unfortunately Todo.Priority isn't ordered correctly so I can't sort on that. I've come up with the following solution: PREFERENCE = { Priority.HIGH: 1, Priority.MEDIUM: 2, Priority.LOW: 3, } result = sorted( Todo.objects.all(), key=lambda x: [PREFERENCE[x.priority], x.id] ) This works but I'd rather sort in the database for several reasons (e.g. faster, better to do work in the DB rather than Python). Is there anyway to perform this query in the database? -
Is this a reasonable project for a beginner web dev to take on solo?
I'm a fresh graduate with a BSc in Comp sci, and I am wondering how reasonable the project I'm considering taking on as a commission is. I'm a relatively experienced programmer, but newish to web development. The project is a simple ecommerce site: -A couple of static pages -A product listing, and the ability to add to a cart with various custom options/dropdowns -Ability to edit cart -Ability to place order for delivery or pickup -Process payment using stripe. No shipping, no need to worry about stock, as it is a food establishment. It seems pretty doable to me but Im worried about wasting the client's time, so I would like some input on how reasonable this would be for me to build in Django and React. I don't need perfection, both I and the client will be satisfied with something that loads fast, looks nice, and doesn't lose orders. Though I have also found it difficult to research common pitfalls building such a site, as all I get are results related to the marketing side of ecommerce. Thoughts? It greatly ease my anxiety to hear from some real full stack web devs. -
Deploy Django on Plotly Dash Enterprise
Good Evening, I am attempting to install a Django and run the development server and production WSGI on Dash Enterprise. I'll preface this with I am also fairly new to Python and Django but not programming. From what I can tell the Dash Enterprise Stack runs a Heroku like containerized web container setup. Each of these containerized apps have a web accessible IDE and are able to run the development web server and are served up at domain.com/Workspaces/view/app_name/ When the code is pushed via git, the live app is viewable at domain.com/app_name/ Gunicorn is employed with nginx to run the production web server and is configured via a ProcFile in the root of the app. web: gunicorn app_name.wsgi --log-file Other services at play appear to be Docker, Herokuish, and Dokku. My code runs fine when tested locally, but when employed on the server, the development server gives me errors such as System check identified no issues (0 silenced). June 16, 2022 - 23:35:45 Django version 4.0.5, using settings 'app_name.settings' Starting development server at http://0:8050/ Quit the server with CONTROL-C. Not Found: /Workspaces/view/app_name/ [16/Jun/2022 23:35:53] "GET /Workspaces/view/app_name/ HTTP/1.1" 404 2183 When I push via git, I'm able to see the unformatted … -
"Product" matching query does not exist, django
I encounter this error when testing the API to create order. The order gets created when I make the request still I get that error message. The order has relatinship with the orderItem and orderItem has relationship with the product model as shown in the models.py. How do i eliminate this error? The django code is valid because it is working on frontend but the issue seems to be in the way I structure the request body on postman as shown below: { "orderItems":[{ "product": 1, "qty":"2", "price":"200" }], "shippingAddress": { "address":"u-address", "city":"u-city", "postalCode":"12345", "country":"u-country" }, "paymentMethod":"p-method", "itemPrice":"2000" } Here is the models.py file class Product(models.Model): category = models.CharField(max_length=50, choices=Categories.choices, default=Categories.medications) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_product", null=True) name = models.CharField(max_length=150) brand = models.CharField(max_length=255, default="brand") productClass = models.CharField(max_length=50, null=True, blank=True) image = models.ImageField(upload_to="images/products/") label = models.CharField(max_length=254, default='', blank=True, null=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) stock = models.IntegerField(null=True, blank=True, default=0) dateCreated = models.DateTimeField(auto_now_add=True) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_order", null=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.dateCreated) models.py class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) image = models.CharField(max_length=200, null=True, blank=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) qty = models.IntegerField(null=True, blank=True, default=0) … -
Scheduled Tasks - Runs without Error but does not produce any output - Django PythonAnywhere
I have setup a scheduled task to run daily on PythonAnywhere. The task uses the Django Commands as I found this was the preferred method to use with PythonAnywhere. The tasks produces no errors but I don't get any output. 2022-06-16 22:56:13 -- Completed task, took 9.13 seconds, return code was 0. I have tried uses Print() to debug areas of the code but I cannot produce any output in either the error or server logs. Even after trying print(date_today, file=sys.stderr). I have set the path on the Scheduled Task as: (Not sure if this is correct but seems to be the only way I can get it to run without errors.) workon advancementvenv && python3.8 /home/vicinstofsport/advancement_series/manage.py shell < /home/vicinstofsport/advancement_series/advancement/management/commands/schedule_task.py I have tried setting the path as below but then it gets an error when I try to import from the models.py file (I know this is related to a relative import but cannot management to resolve it). Traceback (most recent call last): File "/home/vicinstofsport/advancement_series/advancement/management/commands/schedule_task.py", line 3, in <module> from advancement.models import Bookings ModuleNotFoundError: No module named 'advancement' 2022-06-17 03:41:22 -- Completed task, took 14.76 seconds, return code was 1. Any ideas on how I can get this working? It … -
Installing dependencies with requirements.txt by using Pip fails when deploying django app to elastic beanstalk
The app will not deploy because it fails to install Django after successfully installing other packages. Anyone know why this could be? requirements.txt: asgiref==3.5.2 attr==0.3.1 backports.zoneinfo==0.2.1 certifi==2022.6.15 charset-normalizer==2.0.12 Django==4.0.5 django-cors-headers==3.13.0 djangorestframework==3.13.1 idna==3.3 mysqlclient==2.1.0 numpy==1.22.4 python-dotenv==0.20.0 pytz==2022.1 requests==2.28.0 sqlparse==0.4.2 tzdata==2022.1 urllib3==1.26.9 Logs: 2022/06/17 02:47:39.485957 [INFO] Installing dependencies with requirements.txt by using Pip 2022/06/17 02:47:39.485969 [INFO] Running command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt 2022/06/17 02:47:41.833832 [INFO] Collecting asgiref==3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting attr==0.3.1 Using cached attr-0.3.1.tar.gz (1.7 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting backports.zoneinfo==0.2.1 Using cached backports.zoneinfo-0.2.1-cp37-cp37m-manylinux1_x86_64.whl (70 kB) Collecting certifi==2022.6.15 Using cached certifi-2022.6.15-py3-none-any.whl (160 kB) Collecting charset-normalizer==2.0.12 Using cached charset_normalizer-2.0.12-py3-none-any.whl (39 kB) 2022/06/17 02:47:41.833879 [INFO] ERROR: Could not find a version that satisfies the requirement Django==4.0.5 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, … -
How to add separate permission for a selected ModelAdmin in Django wagtail just like 'Page permissions'?
I am creating an application for teaching management in Wagtail. I create an AdminModal for 'Subjects'. I want to allow only selected user group to access a selected subject. Just like "Page permissions" in 'Add group'. Any idea how to do that? -
Splitting one field from model into two form input fields on django update view
I have this customer model with only one address field. class PullingCustomer(models.Model): code = models.CharField(verbose_name='Code', max_length=10, primary_key=True) name = models.CharField(verbose_name='Customer', max_length=255, blank=False, null=False) address = models.CharField(verbose_name='Address', max_length=255, blank=False, null=False) city = models.CharField(verbose_name='City', max_length=25, blank=True, null=True) def __str__(self): cust = "{0.name}" return cust.format(self) but on my form.py, I split it into two input, address 1 and address 2. class PullingCustomerForm(ModelForm): address1 = forms.CharField(max_length=155) address2 = forms.CharField(max_length=100) def __init__(self, *args, **kwargs): super(PullingCustomerForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( .... Row( Column('address1', css_class = 'col-md-12'), css_class = 'row' ), Row( Column('address2', css_class = 'col-md-8'), Column('city', css_class = 'col-md-4'), css_class = 'row' ), .... class Meta: model = PullingCustomer fields = '__all__' Then I combine them again on view.py so I can save it. class PullingCustomerCreateView(CreateView): form_class = PullingCustomerForm template_name = 'pulling_customer_input.html' def form_valid(self, form): address1 = form.cleaned_data['address1'] address2 = form.cleaned_data['address2'] temp_form = super(PullingCustomerCreateView, self).form_valid(form = form) form.instance.address = str(address1) + ', ' + str(address2) form.save() return temp_form Since I want to use the same form layout on my update view, I need to split the address into two again. What is the best method to do that? class PullingCustomerUpdateView(UpdateView): model = PullingCustomer form_class = PullingCustomerForm template_name = 'pulling_customer_update.html' -
Django like filter for SQL query filter
How can i implement same django type filtering using SQL query. In django if i need to filter based on multiple column value i can again filter the query sets using .filter. For Example in Django: Model is Employee data = Employee.objects.all() if employee_department!='': data = data.filter(empdept=employee_department) if employee_location!='' data = data.filter(emploc=employee_location) How can i achieve this in SQL like filtering the query results -
occasionally i get Server Error (500) Missing staticfiles manifest entry
Before you mark it as duplicate, i did search and go throw many questions https://stackoverflow.com/search?q=[django]+Missing+staticfiles+manifest+entry my site works, but sometimes i get Server Error (500), And in logs i get: ValueError: Missing staticfiles manifest entry for 'css/jquery-ui.css' it's the first file in base.html. i think when staticfiles is missing a file, the site should stop at once. in staticfiles.json there is "css/jquery-ui.css": "css/jquery-ui.koi84nfyrp.css", mysite: storage = s3 cdn = cloudflare django = 4.0.4 P.S: in AWS bill center, there is $0.03 total, but i never get a bill or bay them any. Error Traceback ERROR [django.request:241] Internal Server Error: / Traceback (most recent call last): File "/django-my-site/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/django-my-site/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/django-my-site/venv/lib/python3.8/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/django-my-site/venv/lib/python3.8/site-packages/django/template/response.py", line 92, in rendered_content return template.render(context, self._request) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 62, in render return self.template.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 958, in render_annotated return self.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line … -
How to make Django's ImageField app specific?
I've read through a few answers/articles at these links, but am still confused as all of them SEEM to be slightly different than what I'm after: here here here here here I am looking to make use of Django's ImageField function for uploading images from my admin page, to my portfolio/blog's app space. My folder structure looks like this: Portfolio_Blog_Website |---personal_portfolio_project |---projects_app |---migrations |---static |---img |---templates So I want to upload images to/display on the template from, the app > static > img folder. Currently, I have STATIC_URL = 'static/' set, and I'm manually drag and dropping image files into that folder, and using models.FilePathField(path="/img") in the model, and displaying them (in a for loop) with <img src="{% static project.image %}">, which works. I want to switch to be able to upload images from the admin page, and then display them on the app's page like they're supposed to. From what I've read, we have to define a MEDIA_ROOT and MEDIA_URL variable to use with models.ImageField(upload_to="img/"). The problem I see is that MEDIA_ROOT needs to be an ABSOLUTE path to the folder, which I COULD set as \\C:\Portfolio_Blog_Website\projects_app\static\img, however this isn't necessarily what I want because I'm specifically targeting the … -
Grouping ModelMultipleChoiceField in custom group and permissions form in django
I'm to implement a custom form for assigning permissions for groups in django. I have several apps in the project and every one defines its own set of permissions within its own 'AppPermissions' model. I'm currently using a ModelMultipleChoiceField with a CheckboxSelectMultiple widget. Like so: app_permissions = Permission.objects.filter(content_type__model='apppermissions') permissions = GroupedModelMultipleChoiceField( app_permissions, widget=forms.CheckboxSelectMultiple ) Now this already displays the checkboxes I need for displaying the permissions but a requirement is that they must be grouped by app. In a header/content fashion: App1_Name_Header [] App1_name_Permission1 [] App1_name_Permission2 [] App1_name_Permission3 App2_Name_Header [] App2_name_Permission1 [] App2_name_Permission2 etc... Is there a way to implement this? I'm very inexperienced with django so if there's a way of building a widget or a custom field that can accomplish this, any guidance will be appreciated. -
django.core.exceptions.ImproperlyConfigured: No default throttle rate set for 'jwt_token' scope
It was working fine two days ago. But now I am getting this above error. I am not sure what is the issue. When I call jwt/token/ for simple jwt authentication in django rest framework, I get this error. My base.py settings is as follows: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( # "rest_framework.authentication.SessionAuthentication", # "rest_framework.authentication.TokenAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", "DATETIME_FORMAT": "%B %d, %Y %H:%M:%S", "DEFAULT_THROTTLE_RATES": { "jwt_token": "5/minute", "user_registration": "5/day", "otp_email_verification": "5/day", "password_reset": "5/day", "google_registration": "5/day", "resend_email_verification": "5/day", "apple_registration": "5/day", "facebook_registration": "5/day", }, } The problem in the api is follows: {{local}}api/v1/users/jwt/token/ My traceback: Traceback (most recent call last): File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "E:\lvl9\merosiksha\merosiksha\users\api\v1\views.py", line 172, in dispatch return super().dispatch(*args, **kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "E:\lvl9\merosiksha\myvenv\lib\site-packages\rest_framework\views.py", line 497, in dispatch self.initial(request, *args, **kwargs) … -
django-s3direct 2.0.2 admin upload not displaying in Django 3.2
I am in the process of upgrading my versions after a period of neglect. Previously I was on Django==2.2.24 and django-s3direct==1.1.5. Downgrading django-s3direct to 1.1.5 but keeping Django 3.2 restored the functionality of django-s3direct, so the issue seems to lie within the newer version of django-s3direct itself. In the admin the S3 direct upload form is not showing up -- it should appear in the space to the right of "Local image:" in the screenshot below: However, all the markup for the element is in the source of the page. I discovered that the CSS from /static/s3direct/dist/index.css appears to be hiding it (what you see below is the CSS straight from the file; it was not modified by any JS that ran on the page). s3direct worked prior to this upgrade. I'm not attempting anything custom in the code. models.py: class Image(models.Model): local_image = S3DirectField(dest='misc', null=True, blank=True) admin.py: admin.site.register(Image) I also don't have anything custom running on my admin pages. All the other JS/CSS files pulled into this page are files included with the Django admin. I ensured that all I followed all set-up steps for the latest version (I added my access credentials directly to settings.py). I don't see … -
Adding a multiple file field to a Django ModelForm
I'm wanting to create a form that allows multiple image uploads. I've got a Listing model that looks like this: class Listing(models.Model): location = models.CharField("Address/Neighborhood", max_length=250) class ListingImage(models.Model): listing = models.ForeignKey( Listing, related_name="images", on_delete=models.SET_NULL, null=True, ) image = models.ImageField() I'm using django-crispy-forms to create the form on the page but I cannot figure out how to get the listing field onto the page. class ListingModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( "Location", Div("location", css_class="col-md-12 col-lg-6") ) ) class Meta: model = Listing fields = "__all__"