Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
while using vs code, terminal no longer activates the virtual enviroment
whenever i open a new terminal window inside vs code, I get this pop-up massage. terminal works just fine, but I no longer can see the activation script that is like source/...../bin/activated. here is the actual massage: Python virtual environment was successfully activated, even though "venv" indicator may not be present in the terminal prompt. -
Django is automatically adding an ID field during unit tests even though I declared a primary key for my model
I have a django project with multiple tables and am in charge of writing unit tests for the api of said django project. One of the tables has a ForeignKey of a different table, however when I try to create the model object in a unit test I get the following IntegrityError after the model object the ForeignKey refers to is successfully queried, despite being able to post data to this table while the server is running: Traceback (most recent call last): File "C:\Python312\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.IntegrityError: NOT NULL constraint failed: app_examplemodel.location_id The above exception was the direct cause of the following exception: ... Traceback (most recent call last): File "~\tests\test_example_model.py", line 19, in test_post_example_model_valid response = self.client.post(reverse("examplemodelurl"), EXAMPLE_MODEL_DICT, content_type="application/json") django.db.utils.IntegrityError: NOT NULL constraint failed: app_examplemodel.location_id Here is the unit test (it throws the error before I get the chance to assert anything): class TestPostExampleModel(TestCase): def test_post_example_model_valid(self): self.client.post(reverse("locations"), {"name": "location name"}, content_type="application/json") response = self.client.post(reverse("examplemodelurl"), {"name": "example name", "location": "location name"}, content_type="application/json") The main confusing thing about this is that on the official django site, it says the following about model autofields: If you’d … -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "iranian_citi
I am a django developer, I want to use iranian cities library, but when I run this command py manage.py generate_city this error got: > (myenv) D:\myproject\math\maths>py manage.py generate_city Traceback (most recent call last): File "D:\myproject\math\myenv\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "iranian_cities_ostan_pkey" DETAIL: Key (id)=(1) already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\myproject\math\maths\manage.py", line 22, in <module> main() File "D:\myproject\math\maths\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\myproject\math\myenv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\myproject\math\myenv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\myproject\math\myenv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "D:\myproject\math\myenv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\iranian_cities\management\commands\generate_city.py", line 128, in handle self.generate_ostan(ostan_data_path) File "D:\myproject\math\myenv\Lib\site-packages\iranian_cities\management\commands\generate_city.py", line 37, in generate_ostan Ostan.objects.bulk_create(ostan_objs) File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\query.py", line 786, in bulk_create returned_columns = self._batched_insert( ^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\query.py", line 1831, in _batched_insert self._insert( File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\query.py", line 1805, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\sql\compiler.py", line 1822, in execute_sql cursor.execute(sql, params) File "D:\myproject\math\myenv\Lib\site-packages\django\db\backends\utils.py", line 102, in execute return super().execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\backends\utils.py", … -
Django Channels - Group
If in a group there are two channels, after group_send the event chat.message is handled by chat_message.. and its happening for both the channels because I'm printing the channel names and getting two different names... but UI gets updated for only on consumer and that too twice, whereas the other consumer shows no changes. In my client-side code, I have onmessage function, which is responsible for my UI getting updated. The ideal case is if I have two channels in the same group then the message should be broadcast to both and thus UI of both consumers should get updated. class MyWebsocketConsumer(WebsocketConsumer): def connect(self): print("Connected...",self.channel_name) self.group_name = self.scope['url_route']['kwargs']['group_name'] # print('Group Name...',self.group_name) async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): async_to_sync(self.channel_layer.group_send)(self.group_name,{ "type": "chat.message", "msg": text_data, },) def chat_message(self,event): self.send(text_data = event['msg']) print(self.channel_name) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)(self.group_name, self.channel_name) ws.onmessage = function(event){ console.log('Message recived from server...', event) document.getElementById('chat-log').value += (event.data + '\n') } -
Django - Autocomplete Search Throws Error For Logged Out Users?
I’m making some updates to the autocomplete portion of the search functionality in my application and for some reason i’m getting an error for logged out users that says TypeError: Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x1088a5e20>>. This is only happening for logged out users. When users are logged in the autocomplete works as built so I know I’m missing something but I just don’t know what. What needs to get changed to fix this issue? I’m building a gaming application where users have access to play certain games based on their rank in our application. So when a user is logged in I’d like the autocomplete functionality to reflect the games they have unlocked. So let’s say if a user has a rank of 100 then all the games with a game_rank of 100 and below will be displayed. For logged out users I would like all games to be shown. Made some notes in my views.py code from what I tested and added the JavaScript to the search functionality just in case. Screenshots below of what displays for users logged out and logged in. Logged Out Screenshot Logged In Screenshot Below is my … -
Django channels - groups
If in a group there are two channels, after group_send the event chat.message is handled by chat_message.. and its happening for both the channels because I'm printing the channel names and getting two different names... but UI gets updated for only one consumer and that too twice, whereas the other consumer shows no changes. ` from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class MyWebsocketConsumer(WebsocketConsumer): def connect(self): print("Connected...",self.channel_name) self.group_name = self.scope['url_route']['kwargs']['group_name'] # print('Group Name...',self.group_name) async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): async_to_sync(self.channel_layer.group_send)(self.group_name,{ "type": "chat.message", "msg": text_data, },) def chat_message(self,event): self.send(text_data = event['msg']) print(self.channel_name) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)(self.group_name, self.channel_name) ws.onmessage = function(event){ console.log('Message recived from server...', event) document.getElementById('chat-log').value += (event.data + '\n') } ` In my client-side code, I have onmessage function, which i responsible for my UI to get updated. An ideal case is if I have two channels in a group then the message should be broadcast to both and thus UI of both consumers should get updated. -
AssertionError in Django Unit Test: Unable to Retrieve Correct Count from Database
I'm encountering an AssertionError in my Django unit test when attempting to save a POST request to an existing list. Despite creating the list and sending the POST request successfully, the test fails with the following error: Failure Traceback (most recent call last): File "C:\ACode\TDD_Django\lists\tests.py", line 105, in test_can_save_a_POST_request_to_an_existing_list self.assertEqual(Item.objects.count(), 1) AssertionError: 0 != 1 Here's the relevant code: class NewListTest(TestCase): def test_can_save_a_POST_request_to_an_existing_list(self): # Arrange inputs and targets. correct_list = List.objects.create() # Act on the target behavior. self.client.post( f'/lists/{correct_list.id}/add_item', data={'item_text': 'A new item for an existing list'}, ) # Assert expected outcomes. self.assertEqual(Item.objects.count(), 1) new_item = Item.objects.get() self.assertEqual(new_item.text, 'A new item for an existing list') self.assertEqual(new_item.list, correct_list) URL: path('lists/<int:list_id>/add_item/', views.add_item, name='add_item') View: def add_item(request, list_id): our_list = List.objects.get(id=list_id) Item.objects.create(text=request.POST['item_text'], list=our_list) return redirect(f'/lists/{list_id}/') Model: def add_item(request, list_id): our_list = List.objects.get(id=list_id) Item.objects.create(text=request.POST['item_text'], list=our_list) return redirect(f'/lists/{list_id}/') I've tested the code manually using the requests library and verified that the view (add_item) works correctly. However, the unit test continues to fail. Any insights into why this test might be failing would be greatly appreciated. -
Create Raise error in model (clean method isn't working)
I want to raise some error like: if user create both bus_stop_1 and bus_stop_2 with same foreign key or if the count of an object exceed in a table more than 4 So my doubt is how can i raise the error when i use clean method it is not working properly class ConnectedRoute(models.Model): bus_stop_1 = models.ForeignKey( BusStop, on_delete=models.CASCADE, related_name='stop1') bus_stop_2 = models.ForeignKey( BusStop, on_delete=models.CASCADE, related_name='stop2') distance = models.FloatField(blank=True, null=True) time = models.TimeField(blank=True, null=True) def clean(self): if self.bus_stop_1 == self.bus_stop_2: raise ValidationError('Both stop cannot to the same') count_stop1 = ConnectedRoute.objects.filter( bus_stop_1=self.bus_stop_1).count() count_stop2 = ConnectedRoute.objects.filter( bus_stop_2=self.bus_stop_2).count() if count_stop1 + count_stop2 > 4: raise ValidationError('Only 4 connections allowed.') I tried to use this clean method, but i never found it useful is there anything that am missing -
Gmail django sending
Today, looking at a page about django recommendations, I got the concept of a fat model and skinny views, so I had a doubt if what it was doing was good or not and if it could be applied to a model and how? def EnvioGmail(self,Nombre,gmail): context = {"Gmail":gmail,"Nombre":Nombre} template = get_template("Correo.html") content = template.render(context)#Renderisamos la plantilla con el contexto email = EmailMultiAlternatives(#Este sirve para enviar muchos correos como html "Registro exitoso", "", settings.EMAIL_HOST_USER, [gmail] ) email.attach_alternative(content,"text/html")#Es para atajar el email y darle mas datos como el contenido y comos se mostrara email.send() def post(self,request,*args,**kwargs): Formmain = Usuarios(request.POST) if Formmain.is_valid(): Usuario = Formmain.cleaned_data["nombre"] Gmail = Formmain.cleaned_data["gmail"]#Aqui extraemos el gmail del objeto Formulario self.EnvioGmail(Usuario,Gmail) Formmain.save() return HttpResponseRedirect("/Informacion/") else: Mensaje ="Porfavor revisa tus datos" return render(request,"Base.html",{"Mensaje":Mensaje,"Formulario":Usuarios}) I hope someone can help me, I'm still learning many things about django. -
How to connect to existing instance of firefox using selenium in django and how to pass these arguments
I want to login to a page manually in firefox using selenium and use django to connect to this existing firefox browser and click on a link on this already opened page. I did see that a marionette port can be useful for this process but I am not sure how to add these arguments in the driver class and also how to call it to connect to this manually opened browser to click on an element and open a new browser. This is the driver class: class FirefoxDriver(webdriver.Firefox, CustomDriverBase): def init(self, *args, **kwargs): firefox_binary = FirefoxBinary(settings.FIREFOX_BINARY_PATH) super().init(firefox_binary=firefox_binary, *args, **kwargs) class BasePage: def init(self, driver: WebDriver): self.driver = driver def get_url(self, url: str) -> NoReturn: self.delay() self.driver.get(url=url) class HomePage(BasePage): url = 'any url which can be logged into' def get(self) -> NoReturn: self.get_url(url=self.url) self.click_button(locator_cls=locators.HomePageLocators, locator_name='submit') I want to login to a webpage manually in marionette port(and keep it open all the time) and in the HomePage class , I want to click on a link which has been opened on the marionette port and continue the process. I am not able to understand where the arguments for marionette port needs to be specified and how to click on a link … -
django make a one-to-many relationship contain a True value for only one object instance, others should revert to False on this field
I have the following django model: from django.db import models from django.db.models import Q, UniqueConstraint from django.contrib.auth.models import User import random class ReferralCode(models.Model): code_str = models.CharField(max_length=64, primary_key=True, default="".join( [chr(random.randrange(48, 123)) for y in range(64)])) active = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: constraints = [ UniqueConstraint( fields=["user", "active"], condition=Q(active=True), name="unique_active_code_for_user", ) ] On creation of a ReferralCode with active=True I want others to revert to False, how do I do that? Thank you -
Is there a sort of way to use Unit testing with django_tables2 with filters?
I have sql requests and the results in csv format. I already have included the ExportMixin to be able to export in csv format and compare the results. I read the documentation of django_tables2 on https://django-tables2.readthedocs.io/en/latest/index.html but didn't find a clue. I tried to integrate the basic unit testing with TestCase but couldn't apply all the filters to my queryset -
Django tests errors after changing from MemcachedCache to PyMemcacheCache
I'm in the process of upgrading my project to Django 4.1.13 from 4.0. MemcachedCache has been removed from Django 4.1 so I've switched to PyMemcacheCache. I can python manage.py runserver my local server with no problems. However, when I run the tests (with --settings=test) I get errors pymemcache.exceptions.MemcacheError: All servers seem to be down right now in settings/test.py i have CACHE_BACKEND = 'locmem:///' Test were running fine on Django 4.0 -
Django form class for unknown number of fields and type
I am very new to the django framework. I am trying to make a web application that helps students learn multiplication. I have the following problem: Lets take the multiplication of 2 numbers for exampele 532 x 42 I want to create a form class that generates only the needed input fields for all intermediate steps of the multiplication. 5 3 2 x 4 2 (1) [2][1][2][8] [1][0][6][4] ---------------- [2][2][3][4][4] In this example the brackets should represent input fields. The [] brackets are normal input fields and the () brackets are carry input fields. This is what I've tried so far: class AnswerForm(forms.Form): def __init__(self, product, *args, **kwargs): super(AnswerForm, self).__init__(*args, **kwargs) self.fieldsets = {} for index, multiplier in enumerate(product.multiplier_list): rowLength = len(str(multiplier * product.multiplicand)) fieldsetFields = [] for i in range(5, 0, -1): field_name = f'field_{i}' self.fields[field_name] = forms.CharField( label=f'Answer {i}', widget=forms.TextInput(attrs={'class': 'answer-cell', 'tabindex': i, 'maxlength': 1}), required=i <= rowLength ) fieldsetFields.append(self.fields[field_name]) # Determine if row or result if index + 1 == len(product.multiplier_list): fieldsetId = f'fieldset-{product.type}result' else: fieldsetId = f'fieldset-{product.type}row' self.fieldsets[fieldsetId] = fieldsetFields I used fieldsets to group the different types of input fields. In the template i check if the field is required. If so I print the … -
deploy two django projects with apache2 and mod_wsgi under windows server 2016
I am deploying two projects on Django, one of the two is going well but when I want to access the second, I have NOT FOUND on the browser here is my wsgi.py code from the first application: `import os,sys sys.path.append('C:/Apache24/htdocs/MEKAMBO') from django.core.wsgi import get_wsgi_application #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MEKAMBO.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "MEKAMBO.settings" application = get_wsgi_application()` here is my wsgi.py code for the second application: `import os,sys sys.path.append('C:/Apache24/htdocs/log_audit') from django.core.wsgi import get_wsgi_application #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'log_audit.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "log_audit.settings" application = get_wsgi_application() ` here is the httpd.conf code: `LoadFile "C:/Users/HELPDESK/AppData/Local/Programs/Python/Python312/python312.dll" LoadModule wsgi_module "C:/Users/HELPDESK/AppData/Local/Programs/Python/Python312/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp312-win_amd64.pyd" WSGIPythonHome C:/Apache24/htdocs/MEKAMBO/env WSGIPythonPath C:/Apache24/htdocs/MEKAMBO <VirtualHost *:80> ServerName www.mekambo.com DocumentRoot "C:/Apache24/htdocs/MEKAMBO/MEKAMBO" WSGIScriptAlias /mekambo "C:/Apache24/htdocs/MEKAMBO/MEKAMBO/wsgi.py" Alias /media/ C:/Apache24/htdocs/MEKAMBO/media/ Alias /static/ C:/Apache24/htdocs/MEKAMBO/static/ <Directory C:/Apache24/htdocs/MEKAMBO/static> Require all granted </Directory> <Directory C:/Apache24/htdocs/MEKAMBO/media> Require all granted </Directory> <Directory "C:/Apache24/htdocs/MEKAMBO/MEKAMBO"> <Files wsgi.py> Require all granted </Files> </Directory> <VirtualHost *:80> ServerName www.log_audit.com DocumentRoot "C:/Apache24/htdocs/log_audit/log_audit" WSGIScriptAlias /log_audit "C:/Apache24/htdocs/log_audit/log_audit/wsgi.py" <Directory "C:/Apache24/htdocs/log_audit/log_audit"> <Files wsgi.py> Require all granted </Files> </Directory> ` -
Extract the textContent of an element using hyperscript
I have 2 elements in the DOM <script id="info-length-lower" type="application/json">6</script> <script id="info-length-upper" type="application/json">6</script> And I need to get these in some hyperscript on one of the form fields, but nothing seems to give me a value. I've tried several variations: set lowerBound to the textContent of #info-length-lower set lowerBound to #info-length-lower.textContent ... and a few others along the way that I've forgotten now. How can I get this information out using hyperscript? -
Refer to another model and count its ManytomanyField
I have two models: class Post(models.Model): content = models.TextField(blank=False) author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="author") timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): likes_count = self.liked_by.all().count() return { "id": self.id, "content": self.content, "author": self.author.username, "author_id": self.author.id, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "likes": likes_count } and class Liking_System(models.Model): users_who_like = models.ManyToManyField("User", related_name="users_liked") post = models.ForeignKey("Post", on_delete=models.CASCADE, related_name="liked_by") def __str__(self): return f"Post {self.post.id} is liked by {', '.join([user.username for user in self.users_who_like.all()])}" I want in my Post model, it linked to the Liking_System and count how many users that has liked the post and return it. How can I do that? How do I modify the "likes_count = self.liked_by.all().count()". For example my post#1 is liked by two users A and B, but it returned only 1? -
Method Not Allowed: /music/add/ "POST" Error 405 for Django rest Framework
I am creating a spotify like backend and I am trying to create a track So it would take a POST request I tried bunch of different approaches through stack overflow and any resource I could get to. POST http://127.0.0.1:8000/music/add/ Content-Type: application/json Authorization: token 3e356c812614c3d4344e0d06773c27387b1e4c12 { "title": "Evil Ways", "duration": "00:03:47", "release_date": "2023-09-03", "audio_file": "/media/tracks/Music_Library.musiclibrary.zip", "artist": 2, "album": 2, "genre": 1 } I am sending the request through a .rest file and I get the response HTTP/1.1 405 Method Not Allowed Date: Thu, 08 Feb 2024 09:11:56 GMT Server: WSGIServer/0.2 CPython/3.9.0 Content-Type: application/json Vary: Accept, Cookie Allow: OPTIONS, GET X-Frame-Options: DENY Content-Length: 41 { "detail": "Method \"POST\" not allowed." } the end point is in urls.py file from django.urls import path from . import views urlpatterns = [ # other paths # all get requests work path('add/', views.add_track) ] In my views.py file I have from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from .models import Track, Artist, Genre, Album from .serializers import TrackSerializer from rest_framework.decorators import api_view, authentication_classes , permission_classes from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated # ... other views @api_view(['GET', 'POST']) @authentication_classes([SessionAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def add_track(request): if … -
How to call multiple variables in send_mail() function
enter image description here How do I call multiple variables in send_mail() message parameter function like employeeid,name, email,fromplace,toplace,vehicle,duration (see image). Also, I have stored all the data in the Script tag with the names given above and not in the views.py file. -
Django django-bootstrap-v5 works locally but failed with ModuleNotFoundError: No module named 'bootstrap5' on AWS Elastic beanstalk
I have a project that use the package: django-bootstrap-v5==1.0.11 everything works OK, but when I try to deploy to AWS Elastic Beanstalk server I get the error: ModuleNotFoundError: No module named 'bootstrap5' And when I delete the 'bootstrap5' from my INSTALLED_APPS the server is up... I'm new to Amazon EC2 service so not sure what is the write approach - Are all packages allowed? If not how can I check which one allowed and how to manually use others? will appreciate any help, Thanks! -
Django render_to_string not working on fieldname.help_text
I’m creating an app for a questionnaire and making use of the model fields help_text attribute, which represents the question of each data field. For this, I wrote some custom model form: class CustomModelForm(forms.ModelForm): """A customized ModelForm for Django. This class extends the base ModelForm class from Django's forms module. It provides additional functionality to handle errors and help text for form fields. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.errors: attrs = self[field].field.widget.attrs attrs.setdefault("class", "") attrs["class"] += " is-invalid" for field in self.fields: try: self.fields[field].help_text = self._meta.model._meta.get_field( field ).help_text except Exception: pass additionally I created a template tag together with a .html: @register.inclusion_tag("../templates/snippets/radioInlineField.html") def render_radioInlineInput_field(formfield): return {"formfield": formfield} {% with field=formfield %} <div class="col-sm-6 text-start"> {% if field.help_text %} <p class="mb-0">{{ field.help_text }}: </p> {% endif %} </div> <div class="col-sm-6 mt-0 "> {% for radio in field %} <div class="form-check form-check-inline"> {{ radio.tag }} <label class="form-check-label" for="id_{{ radio.id_for_label }}">{{ radio.choice_label }}</label> </div> {% endfor %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} </div> {% endwith %} Now everything works good with it, but if I have Form A (only consisting of the above mentioned type of fields) and … -
How to validate data when insert using raw SQL query
class Queue(models.Model): name = models.CharField(max_length=255, unique=True) api_token = models.CharField(max_length=255, default=secrets.token_hex(16)) class Message(models.Model): queue = models.ForeignKey(Queue, on_delete=models.CASCADE) subject = models.CharField(max_length=255) message = models.TextField() api_token = models.CharField(max_length=255) These are my models and I want to insert Message data using raw SQL query. But I want to match the api_token from the Message table to the selected Queue api_token when Insert. How to do that? -
Django ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS settings not fully understood
My Django server is running on 127.0.0.1:8001. I use nginx to reverse proxy my django server to port 80. The nginx config looks like this: server { listen 80; location / { proxy_pass http://127.0.0.1:8001; } location /static { root STATIC_ROOT; } } I got confused when I try to understand ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS settings. These 2 settings all don't work: ALLOWED_HOSTS = ["example.com"] CSRF_TRUSTED_ORIGINS = ["https://example.com"] Or ALLOWED_HOSTS = ["127.0.0.1"] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1"] Only this works ALLOWED_HOSTS = ["127.0.0.1"] CSRF_TRUSTED_ORIGINS = ["https://example.com"] Can anybody explains why I need to set them differently? If possible, how does nginx reverse proxy work generally? -
(React-Django) Getting 403 Forbidden for uploading file to google cloud storage using signed url
I created signed url to upload files (mp3 video file upto 1GB) from the client side directly on cloud storage. But when I try to upload the file, I am getting following error: ` SignatureDoesNotMatch Access denied. The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method. ` This is how the URL was generated: https://storage.googleapis.com/bucket-name/filename ?X-Goog-Algorithm=GOOG4-RSA-SHA256 &X-Goog-Credential=something.iam.gserviceaccount.com%2xyz%2Fauto%2Fstorage%2Fgoog4_request &X-Goog-Date=20240207T120631Z &X-Goog-Expires=900 &X-Goog-SignedHeaders=content-type%3Bhost &X-Goog-Signature=21... Front end is in react and I am first making a call to get the signedurl and then uploading the file. React code : const responseForSignedUrl = await axios.get( `${baseUrl}/api/posts/getuploadurl/` ); if (responseForSignedUrl.status !== 200) { throw new Error("Failed to obtain signed URL."); } const signedUrl = responseForSignedUrl.data.url; // Upload video file to Cloud Storage using the signed URL const videoFormData = new FormData(); videoFormData.append("file", video_file); const uploadResponse = await axios.put(signedUrl, videoFormData, { headers: { "Content-Type": "video/mp4", }, onUploadProgress: (progressEvent) => { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); setProgress(percentCompleted); }, }); if (!uploadResponse.ok) { throw new Error("Failed to upload video file."); } Backend code for signed url generation: def generate_upload_signed_url_v4(request): """Generates a v4 signed URL for uploading a blob using HTTP PUT. Note that … -
How do I combine identical cells in a column using python xlwt?
I use python xlwt to generate an excel file (report). I can't combine the cells of the column with the same values (column A and column with totals) in any way. For example, I have attached screenshots of how I get the output now and what kind of output it needs to be brought to. My function generates a report of the following type: enter image description here Please help me to make it look like this: enter image description here Report generation function: def export_excel(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = ("attachment; filename=Numbers_" + str(datetime.datetime.now().strftime("%d/%m/%y")) + '.xls') wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Numbers', cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Подразделение', 'Номер', 'Сумма', 'Итог (Сумма+ндс+абон.плата)', 'Итог по подразделению'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = ReportFilter(request.GET, queryset=Parser.objects.all().values_list( 'attachment__attachment', 'number', 'pay', 'result')).qs rows1 = Numbers.objects.filter(is_enabled=True).values_list('attachment__attachment', 'number') res = 0 temp = [] for item1 in rows: temp.append(item1) res += item1[3] for item2 in rows1: if Parser.objects.filter(number=item2[1]): None else: item2 = list(item2) item2.append(250) item2.append(250) res += item2[3] item2 = tuple(item2) temp.append(item2) temp.sort() temp = tuple(temp) for row in temp: row_num += 1 for col_num in range(len(row)): if isinstance(row[col_num], datetime.datetime): date_time = …