Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Choice Dropdown Not Working on Cloned Form in Formset
I am cloning my an empty form in django following guidance I've found elsewhere in stack overflow. The JS will append a new form as intendended however the dropdowns from a choice widget are no longer working and I can't figure out why. I have already validated that all of my options are there using my browser's inspect feature. It appears to be that the javascript isn't working with the object. This is from the template: <form method="post"> {% csrf_token %} <div id="form_set"> {{ FightForms.management_form|materializecss }} {% for form in FightForms %} <div class="card white darken-1 col m12"> <table class='no_error'> {{ form.non_field_errors }} <row> <div class="col m3"> <div class="fieldWrapper"> {{ form.guild_member_id|materializecss }} </div> </div> </row> {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} </table> </div> {% endfor %} </div> <div class="col m12"> <div> <input class="btn light-blue lighten-1" type="button" value="Add More" id="add_more"> </div> <br> <button class="btn light-blue lighten-1" type="submit">Submit Guild Members</button> </div> <div id="empty_form" style="display:none"> <div class="card white darken-1 col m12"> <table class='no_error'> {{ FightForms.empty_form.non_field_errors }} <row> <div class="col m3"> <div class="fieldWrapper"> {{ FightForms.empty_form.guild_member_id|materializecss }} </div> </div> </row> {% for hidden in form.hidden_fields %} {{ hidden|materializecss }} {% endfor %} </table> </div> </div> </form> <script> $('#add_more').click(function() { … -
Do Django generic views automatically generate templates for Django models?
That’s all the Python code we need to write. We still need to write a template, however. We could explicitly tell the view which template to use by adding a template_name attribute to the view, but in the absence of an explicit template Django will infer one from the object’s name. In this case, the inferred template will be "books/publisher_list.html" – the “books” part comes from the name of the app that defines the model, while the “publisher” bit is the lowercased version of the model’s name. This comes from https://docs.djangoproject.com/en/5.1/topics/class-based-views/generic-display/ after the PublisherListView is displayed and the URL is configured. I have several questions: By changing the model equal to publisher, I understand that this view looks at a template books/publisher_list. Is this template already created by Django, with default code/logic to handle the display of multiple items of the given model? Or do we need to write it ourselves, with the context object_list? To be clear, if we create any generic view which inherits from ListView, and pass it a Django model as an attribute, will the template it's assigned to (if it already exists) look at all instances of that model, and display them in some pre-written … -
Django REST Framework cached view returning 2 different payloads
I'm experiencing a strange issue with my Django REST Framework paginated list view, which utilizes a 2 hour cache. If I repeatedly make requests to the view's endpoint, I am sometimes getting Response 1 (x bytes in size) and sometimes getting Response 2 (y bytes in size). The view code is as follows: class MyListView(generics.ListAPIView): model = MyListModel serializer_class = MyListSerializer pagination_class = PageNumberPagination pagination_class.page_size = 1000 def get_queryset(self): region = self.kwargs.get('region') sort_param = '-date_created' return MyListModel.objects.filter(region=region).order_by(sort_param) @method_decorator(cache_page(2*60*60)) def get(self, *args, **kwargs): return super().get(*args, **kwargs) I'm not sure if this is relevant, but once a day, I run a cronjob which clears all cached views using the following code: from django.core.cache import cache cache.clear() I have confirmed that the difference in response data from this endpoint is not due to the cache expiring and being replaced with new data. I have also confirmed that the data in the database for MyListModel is not being changed at all. I have also confirmed that the region parameter is consistent between requests. I'm at a loss for how I could be getting 2 different responses from this endpoint. Cache or no cache, the underlying data is not changing so the response should be … -
ModuleNotFoundError: No module named 'django.contrib.contenttyfrom datetime import timedelta'
I try to do a migration “python manage.py makemigrations ” but I get an error Traceback (most recent call last): File "/home/anton/Documents/project2/backend/my_backend/manage.py", line 22, in <module> main() File "/home/anton/Documents/project2/backend/my_backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.contenttyfrom datetime import timedelta' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttyfrom datetime import timedelta', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'auth_app', 'corsheaders' ] P.S. I already noticed the error in INSTALLED APS I can't find the file with this error, and I can't install this module either pip install timedelta i also did in .env file only SECRET_KEY=django-insecure-3+qcjvwgd8r95x++s85nwz7xa+#^v2hiv7-pbgdz)b1s5)gx&w DEBUG=TRUE -
How to update code for Django Stack on Google Cloud Platform
i have used Django Stack listed on Marketplace of GCP. When I visit the IP address I get an error DisallowedHost so I've changed settings.py to (for now) ALLOWED_HOSTS = ["*"]. Problem is I don't see any changes, still same error. How do I make it update? I run python manage.py collectstatic and sudo service apache2 restart but that did nothing. -
AttributeError: 'PosixPath' object has no attribute 'read'
I wanted to do a migration, but I got an error My python version in the virturalenv is Python 3.12.3 I haven't found a single appropriate response to stackoverflow yet. Traceback (most recent call last): File "/home/anton/Documents/project2/backend/my_backend/manage.py", line 22, in <module> main() File "/home/anton/Documents/project2/backend/my_backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 382, in execute settings.INSTALLED_APPS File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/conf/__init__.py", line 81, in __getattr__ self._setup(name) File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/conf/__init__.py", line 68, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/django/conf/__init__.py", line 166, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/home/anton/Documents/project2/backend/my_backend/my_backend/settings.py", line 12, in <module> environ.Env.read_env(BASE_DIR / '.env') File "/home/anton/Documents/project2/backend/pr2_venv/lib/python3.12/site-packages/environ/environ.py", line 646, in read_env content = f.read() ^^^^^^ AttributeError: 'PosixPath' object has no attribute 'read' I had the same error when I reconnected the postgres database and then sqlite3 again. -
Django Mock database not working properly
I was coding a unit test method for a post method, but for some reason, it keeps modifying the actual database instead of the mock database. This is my test method: def test_post_contest(self): mock_collection = self.mock_db.collection.return_value mock_document = mock_collection.document.return_value mock_document.set.return_value = None response = self.client.post( reverse('contest-list'), data={ 'ONI2024F2': { 'name': 'ONI2024F2', 'problems': ['problem1', 'problem2'], 'administratorId': '0987654321' } }, format='json' ) self.assertEqual(response.status_code, 201) self.assertEqual(response.json(), {'id': 'ONI2024F2'}) This is the setUp method: def setUp(self): self.client = APIClient() self.mock_db = patch('firebase_config.db').start() self.addCleanup(patch.stopall) And this is the firebase_config.py file import os import firebase_admin from firebase_admin import credentials, firestore #Path to Firebase credentials cred_path = os.path.join(os.path.dirname(__file__), 'credentials','firebase_credentials.json') #Initialize Firebase cred = credentials.Certificate(cred_path) firebase_admin.initialize_app(cred) #Firestore client db = firestore.client() I thought that it could be the firebase-config file, so I tried changing it but then all the tests raised exceptions. -
How i run python function without loading a page in django
i am working on a project which has a function which generate response automatically on loop using google gemini api and show it to the html page by saving it to the database, i want this function to run behind the scene without loading the page Currently what is happening is, if the function is generating 10 response in a loop then it is keep loading the page until all response get generated and then it is showing me home.html page. this is the function enter code here def home(request): print("Bot: Hello how can i help you?") # main code starts here i = 0 while i < 2: if len(history_global) == 0: user_input = input("You: ") chat_session = model.start_chat( history=history ) response = chat_session.send_message(user_input) #1 Taking input from user #generating output result....... model_response = response.text history.append({"role" : "user", "parts" : [user_input]}) #3 updating history - (user part) history.append({"role" : "model", "parts" : [model_response]}) #4 updating history - (response part) history_global = model_response #5 updating value of history_global with the response created # Save the data to the database saveit = Data1(question=user_input, answer=history_global) saveit.save() print(i) print("Question : ", user_input) print() print("Answer : ", model_response) print() print("...............................................................................................1") print() random_interval = random.randint(10, … -
Django Rest api json imput for m-m relation
I am trying to post json file and save the models into database. AttributeName and AttributeValue is generated correctly but Attribute is saved without "nazev_atributu_id" and "hodnota_atributu_id". [ { "AttributeName": { "id": 2, "nazev": "Barva" } }, { "AttributeValue": { "id": 2, "hodnota": "modrá" } }, { "Attribute": { "id": 1, "nazev_atributu_id": 2, "hodnota_atributu_id": 2 } } ] models.py from django.db import models class AttributeValue(models.Model): unique_id = models.AutoField(primary_key=True) id = models.IntegerField(unique=True) hodnota = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return f"AttributeValue with id: {self.id}" class AttributeName(models.Model): unique_id = models.AutoField(primary_key=True) id = models.IntegerField() nazev = models.CharField(max_length=255, null=True, blank=True) kod = models.CharField(max_length=255, null=True, blank=True) zobrazit = models.BooleanField(default=False) def __str__(self): return f"AttributeName with id: {self.id}" class Attribute(models.Model): unique_id = models.AutoField(primary_key=True) id = models.IntegerField(unique=True) nazev_atributu_id = models.ManyToManyField(AttributeName, through='AttributeAttributeNameMapping') hodnota_atributu_id = models.ManyToManyField(AttributeValue, through='AttributeAttributeValueMapping') def __str__(self): return f"Attribute with id: {self.id}" class AttributeAttributeNameMapping(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) attribute_name = models.ForeignKey(AttributeName, on_delete=models.CASCADE) class Meta: unique_together = ('attribute', 'attribute_name') class AttributeAttributeValueMapping(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) attribute_value = models.ForeignKey(AttributeValue, on_delete=models.CASCADE) class Meta: unique_together = ('attribute', 'attribute_value') serializer from rest_framework import serializers from .models import * class AttributeNameSerializer(serializers.ModelSerializer): class Meta: model = AttributeName fields = '__all__' class AttributeValueSerializer(serializers.ModelSerializer): class Meta: model = AttributeValue fields = '__all__' class AttributeSerializer(serializers.ModelSerializer): nazev_atributu_id = serializers.SlugRelatedField(queryset=AttributeName.objects.all(),slug_field='id') … -
How to pass a related objects parameters in the main objects serializer
I have a Room object, which will have some settings. I wanted to make Room and RoomSettings different objects but bound to each other. RoomSettings will be created whenever a Room is created, so I'm using signals. However, while creating the room, I need to pass RoomSettings arguments from Room to RoomSettings through signals, so I can set the settings in creation. models.py from django.db import models from users.models import AppUser as UserModel from django.core.validators import MaxValueValidator, MinValueValidator import random, string from datetime import datetime def generate_unique_key(): length = 10 while True: key = ''.join(random.choices(string.ascii_uppercase, k=length)) if Room.objects.filter(key=key).count() == 0: break return key class Room(models.Model): host = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='rooms') key = models.CharField(max_length=10, default=generate_unique_key, unique=True, editable=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return f'{self.key} - {self.host.username}' def get_chat(self): return self.chat class RoomSettings(models.Model): room = models.OneToOneField(Room, on_delete=models.CASCADE, related_name='settings') max_users = models.PositiveIntegerField(default=8, validators=[MaxValueValidator(8), MinValueValidator(1)]) is_public = models.BooleanField(default=True) users_can_send_message = models.BooleanField(default=True) serializers.py from rest_framework import serializers from .models import Room, RoomSettings from users.serializers import UserSerializer from chats.serializers import RoomChatSerializer class SettingSerializer(serializers.ModelSerializer): class Meta: model = RoomSettings exclude = ['room'] class CreateRoomSerializer(serializers.ModelSerializer): max_users = serializers.IntegerField() is_public = serializers.BooleanField() users_can_send_message = serializers.BooleanField() class Meta: model = Room fields = ['max_users', 'is_public', 'users_can_send_message'] signals.py from django.db.models.signals … -
Highlight Active Links are not working in Django Website
I fulfilled all requisite steps to highlight the active links in my Django Website Project. As I click on About Us, Contact Us, or Services options in the menu bar, No menu bar options are highlighted, for guide me. Thanks for your kind anticipation <!-- Main header start --> <header class="main-header sticky-header header-with-top"> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light"> <a class="navbar-brand company-logo" href="index.html"> <img src="{% static 'img/logos/black-logo.png'%}" alt="logo"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation"> <span class="fa fa-bars"></span> </button> <div class="navbar-collapse collapse w-100" id="navbar"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Home </a> </li> <li class="nav-item"> <a class="nav-link" href="cars.html"> Cars </a> </li> {% url 'about' as url %} <li class="nav-item"> <a class="nav-link {% if request.path == about %} active {% endif %}" href="{{url}}"> About </a> </li> {% url 'services' as url %} <li class="nav-item"> <a class="nav-link {% if request.path == services %} active {% endif %}" href="{{url}}"> Services </a> </li> {% url 'contact' as url %} <li class="nav-item dropdown"> <a class="nav-link {% if request.path == contact %} active {% endif %}" href="{{url}}">Contact</a> </li> <li class="nav-item dropdown m-hide"> <a href="#full-page-search" class="nav-link h-icon"> <i class="fa fa-search"></i> </a> </li> </ul> </div> </nav> </div> </header> … -
Model indexing on Choice field in django
i have a model which has a status field of choice field which are pending,approved,cancel,rejected. And i index the field status in my model and the makemigrations but the index only works for other values but not approved value. if i filter by other status like, pending,cancel it will shows that it get it from the index but if i filter by approved it won't work and it will load slowly. Though the dataset of the model is much which is around 7million. I get the details from a django debug tools this will show if i filter by other values if i filter by other values if i filter by approved value this is my view which i use to test the filter def testing(request): context['response'] = Task_Submitted.objects.filter(status='approved') return render(request, 'testing.html', context) is there any way to fixed this so approved too will be in index so if i filter by approved value too it will load faster -
How to prepare a Django web app for deployment?
I am a novice developer, I have recently started my journey with developing full web app projects with Django, and have just finished my first one. It's a simple full-stack web app written with Django, and I have come across an impasse. How can I prepare my Django Project for deployment? -In essence, the question is, how can I remove any personal local machine information from any files within my project directory, it seems that there are cases when the PATH of my local machine python files is mentioned within the venv and in other directories. Should I just remove the venv as a whole before deploying it and manually delete all local machine references? The second question is, how can I deploy my project via VPS? -Previously I have used shared hosting and it was fairly straightforward to have everything deployed, however now I am tasked with deploying it on a VPS with an Easy-Panel set up. This is less of a priority for a question, I believe I'll be able to figure it out on my own, but if you have any advice, I would be very grateful for it! I haven't attempted to resolve this as of … -
PyJWT installed but keey getting: ModuleNotFoundError: No module named 'jwt'
My Django project was working fine. Then followed the steps to implement Auth0 into my project, which I have setup on my frontend successfully. I followed all of these steps: https://auth0.com/docs/quickstart/backend/django/01-authorization Running in Python 3.9.6 ('.venv': Pipenv) ./.venv/bin/python Trying installing requirements in all environments as well I even updated requirements.txt to the most modern versions to see if it was a compatibility issue. When I run python manage.py runserver I get File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/chasesheaff/teachr-backend/teachr/urls.py", line 23, in <module> path('', include('auth0authorization.urls')), File "/Users/chasesheaff/Library/Python/3.9/lib/python/site-packages/django/urls/conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/chasesheaff/teachr-backend/auth0authorization/urls.py", line 3, in <module> from . import views File "/Users/chasesheaff/teachr-backend/auth0authorization/views.py", line 5, in <module> import jwt ModuleNotFoundError: No module named 'jwt' pip freeze … -
Gunicorn local port 8000 with Apache reverse proxy port 443
I am trying to deploy my django project on a linux ubuntu virtual machine (from linode) using an Apache2 server. I was following the tutorial by CoreySchafer on youtube, but my out put wasn't the same as him. His django project was directly hosted to port 80 of his vm. The only way I was able to make it work was by first running the django project locally using either the dev server (runserver) or gunicorn. Both were running on 127.0.0.1:8000 of the vm. Then in the apache site .conf file, I setup reverse proxy from local port 8000 to https 443. I have 2 issues now. A) The site works with runserver, but it is not a production level server. B) The site also works with gunicorn but doesn't serve static files (I did collect static). What am I doing wrong? Is it fine to reverse proxy to local? How to make gunicorn serve static. <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName (# hiding my website name) # Proxy settings ProxyPreserveHost On ProxyPass / http://127.0.0.1:8000/ ProxyPassReverse / http://127.0.0.1:8000/ DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLCertificateFile /etc/letsencrypt/live/www.website.co.in/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/www.website.co.in/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> This is how my apache site … -
Delete div and label for that div without label id
Using Crispy forms in Django app, I have a html code like this: <div id="div_id_pripadnost" class="form-group"> <label for="id_pripadnost_0" class=""> Pripadnost </label> <div class=""> <div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_1" value=""> <label for="id_pripadnost_1" class="form-check-label"> --------- </label> </div> <div class="form-check"> <input type="radio" class="form-check-input" checked="checked" name="pripadnost" id="id_pripadnost_2" value="CRS"> <label for="id_pripadnost_2" class="form-check-label"> CRS </label> </div> <div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_3" value="SCM"> <label for="id_pripadnost_3" class="form-check-label"> SCM </label> </div> </div> </div> I would like to remove div with id="id_pripadnost_1". I have removed radio button/div "form-check", but I can't remove label '---------', since it doesn't have id. How to remove that label? I have tried: const radioBtn = document.getElementById('id_pripadnost_1'); radioBtn.style.display = 'none'; radioBtn.previousElementSibling.style.display = 'none'; document.getElementById('id_pripadnost_1').remove(); -
How can I send a batch email using postmark in Anymail for Django?
I would like am trying to use the Anymail API for postmark in my django application. This is not the same as putting a list of emails in the cc, but I am trying to send a separate email to each individual email address (the email content is the same though). Right now, I have the following to send transactional (one-time) emails. from anymail.message import AnymailMessage email = AnymailMessage( subject=subject, body=body, from_email=from_email, # from email (uses DEFAULT_FROM_EMAIL if None) to=to, # recipient list ) email.esp_extra = { 'MessageStream': message_stream, # Specify the message stream } I initially tried using a for loop to send a separate email to each email address, but that consumed too much time and the page couldn't load long enough. How can I then achieve this batch email send in django using Anymail? Thank you, and please leave a comment if you have any questions. -
Many to many post request DRF
Currently I am trying to figure how the post request needs to be structured to create an object in watchlist. My models.py contains two models that are linked together via stock. class Stock(models.Model): model_number = models.CharField(max_length=100, unique=True, default="") model = models.CharField(max_length=100) brand = models.CharField(max_length=100) msrp = models.IntegerField(default=0) class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) stock = models.ManyToManyField(Stock) This created two tables in my database one called watchlist and another called watchlist_stock. The former contains an id and a user id. The later contains id, watchlist_id, and stock_id. Here is my serializer for the relevant view class WatchlistAddSerializer(serializers.ModelSerializer): class Meta: model = Watchlist fields = ['stock'] And here is the relevant view for the post method. @api_view(['POST']) def watchlist_create(request): serializer = WatchlistAddSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=request.user) return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) else: return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am using axios to post on the react frontend but I am currently at a loss for how the data needs to be structured to post. react api.post(`/api/watchlist-create/`, { // Some data goes here }) -
How to use logrotate cut uwsgi log files
My uwsgi.log path: /root/code/script/uWSGI.log My logrotate about uwsgi configuration: in /etc/logrotate.d/uwsgi /root/code/script/uWSGI.log { daily missingok rotate 7 compress delaycompress notifempty create 640 root root sharedscripts postrotate touch /root/code/script/.touchforlogrotate endscript } My uwsgi.ini [uwsgi] http = 0.0.0.0:8050 socket=/root/code/script/uwsgi.sock master=true chdir=/root/code/ wsgi-file=/root/code/data_analysis/wsgi.py home = /root/anaconda3/envs/data-analysis worker=6 threads=2 max-requests=5000 thunder-lock=true enable-threads=true pidfile=/root/code/script/uwsgi.pid touch-logreopen = /root/code/script/.touchforlogrotate when i use logrotate -d /etc/logrotate.d/uwsgi command, the following error occurs reading config file uwsgi error: uwsgi:2 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:3 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:4 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:5 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:6 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:7 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:8 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:9 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:10 lines must begin with a keyword or a filename (possibly in … -
How i save. Canvas in db. With background. Which comes from user uploaded in Django field img
I successfully save if static path How pass field image of customer to java There many trial but src for field from model i cant save both i f i add url in style background not saved your text type h window.onload = function(){ //var dataImage = localStorage.getItem('imgData'); //var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var imageObj = new Image(); var dataURL = canvas.toDataURL("image/png"); imageObj.onload = function(){ context.globalCompositeOperation="destination-over"; context.drawImage(imageObj,250, 50,700,400);// i edit it was context.drawImage(imageObj,50, 50); context.font = "40pt Comic Sans MS"; context.fillText("draw here",20,80); context.fill(); context.globalAlpha = 0.5; }; //function getBase64Image(img) { //var dataURL = canvas.toDataURL("image/png"); //return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); //} //here source imge for back ground if you want make it dynamic from upload by user use url of media <canvas style="background: url('{{ user.profile.profile_pic.url }}')" <canvas style="background: url({% static 'images/aes.png'%})" imageObj.src = dataURL;//"data:image/png;base64," + dataImage;//'/media/imggg/gggg.png';//"{{ img }}"//'/media/imggg/gggg.png'; //cnanvas.innerHTML = `<img src="${url}" width="50%">`;//`media/${object.img.url}`//("<img src="{{ MEDIA_URL}}{{field.img.url}}">"); //<img src="{{ MEDIA_URL}}{{ City.image.url }}">"url '(${field.img.url})' ";//=("<img src='${{field.img.url}}'>"); }; ere </main> </body> <script type="text/javascript"> </script> </html> Can pass variable from Django models and view to java Ok any other help i needs Edited code how make dynamic uploaded pic background drawing on it then save -
how to upload django project on hestiacp
how to upload django project on hestiacp I installed python in terminal and uploaded the project but don't know what I can do to run on my domain I asked shat GPT but it doesn't be useful. if some one face this problem before or has knowledge please help me -
Django i18n translations work locally but not when deployed in a CI/CD pipeline
I'm trying to add translations to my django project, and for some reason it never worked. When I deploy it in ci/cd pipeline not only does it not translate, but I get csrf errors, even though I got {% csrf token %} in my template and use render in my view. But all these problems disappear when I run it locally. Here's my code: views.py from django.shortcuts import render def test_page(request): return render(request, "translatetest.html") urls.py(app level) from . import views from django.urls import path urlpatterns = [ path('test_page/', views.test_page, name='test_page'), ] urls.py(project level) from django.contrib import admin from django.urls import include, path from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path("admin/", admin.site.urls), path("i18n/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns ( path("", include("help_pages.urls"), name="help_pages"), #test_page is here ) settings.py LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', ('English')), ('fr', ('French')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) I don't think it's a problem with my python bc it worked locally but I'll put it too just in case. Also, curious enough when I deploy it in the ci/cd pipeline, only one word is translated(in another view, not the test_page one), it's not … -
django instance.add() is not working on new m2m field added
Difference between Code 1 and Code 2 given below is that industry and dindustry fields are interchanged. While Code 1 works fine Code 2 doesn't update the database. Can someone please help..... Note: Table was altered and dindustry was newly created. No migration issues, I am able to add records to both industry and dindustry through django Admin Code 1: @receiver(m2m_changed, sender=Company.dindustry.through) def video_category_changed(sender, instance, action, pk_set, **kwargs): if action == "post_add": sectors = Sectors.objects.filter(id__in=pk_set) roots = set() for sector in sectors: root = sector.get_root() if not instance.industry.filter(id=root.id).exists(): instance.industry.add(root) print('data added') Code 2: @receiver(m2m_changed, sender=Company.industry.through) def video_category_changed(sender, instance, action, pk_set, **kwargs): if action == "post_add": sectors = Sectors.objects.filter(id__in=pk_set) roots = set() for sector in sectors: root = sector.get_root() if not instance.dindustry.filter(id=root.id).exists(): instance.dindustry.add(root) print('data added') My model is as below: class Company(MPTTModel): industry = models.ManyToManyField(Sectors, related_name='relatedname_industry', blank=True) dindustry = models.ManyToManyField(Sectors, related_name='relatedname_dindustry', blank=True) class Sectors(MPTTModel): sector = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') It works well on one m2m field but doesn't work on another m2m field in the same table -
html file have something wrong Registration Form not submitting in Django
My html file have some issues but I can't figure it out what the problem actually is. Can anyone Identify what really the problem is. Here is Html I'm using: signup.html {% include "user/layout.html" %} {% block content %} <h1>Sign Up</h1> <form method="POST"> {% csrf_token %} {{form}} <input class="btn login_btn" type="submit" value="Register Account"> </form> {% endblock %} **views.py ** from django.shortcuts import render, redirect from . forms import create_user # Create your views here. def sign_up(request): form = create_user() if request.method == "POST": if form.is_valid(): form.save() return redirect("test-home") context = {"form":form} return render(request, "user/signup.html", context) **urls.py ** from django.urls import path from . import views urlpatterns = [ path("create/", views.sign_up, name="sign_up"), ] I have tried some other html sign up templates from other videos. Only copying them works. I can't figure out where the real problem is. -
KeyError: 'pick-number' when accessing custom headers in Django Rest Framework view
I'm working on a Django Rest Framework API and encountered a KeyError when trying to access custom headers in my view. The error occurs when I try to access the "pick_number" header in my confirmingPick1View. The traceback is as follows: Internal Server Error: /api/wager/pick1/confirm/ Traceback (most recent call last): File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/gutsthakur/Projects/Betting App/wager/views.py", line 76, in post "pick_number": request.headers["pick_number"], File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/http/request.py", line 448, in __getitem__ return super().__getitem__(key.replace("_", "-")) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/utils/datastructures.py", line 308, in __getitem__ return self._store[key.lower()][1] KeyError: 'pick-number' In my view, I'm trying to access custom headers like "Draw", "pick_number", and "bet_amount" for processing a user's bet. I expected these headers to be accessed directly without any issues, but instead, I'm receiving a KeyError for "pick_number" …