Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stream data chunk by chunk in Django using StreamingHttpResponse and receive it in the front end using axios?
I am trying to stream data from my Django backend to my front-end using the StreamingHttpResponse and axios. However, I am encountering an issue where the data is being buffered and only received in the front-end once all the data is ready or when I stop the server. I am using the code provided above for the backend and front-end. I would like to know how I can prevent this buffering and receive the data chunk by chunk in the onDownloadProgress event of axios. Backend: def iterator(): for i in range(1000): yield f'chunk: {i}' sleep(0.2) def generate_post_text(request): stream = iterator() response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream'') response['Cache-Control'] = 'no-cache' response['X-Accel-Buffering'] = 'no' response.streaming = True return response And here is the front end code: axios({ url: '/api/gpt3/generate-post-text', method: 'GET', onDownloadProgress: progressEvent => { const dataChunk = progressEvent.currentTarget.response console.log(dataChunk) }, }).then(({data}) => Promise.resolve(data)) Backend middlewares: MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] I run the server locally on a Mac -
Creating object branched from object and setting the root object id to the parent_object field
With this function def post(request, note_id, comment_id=None): """Create a comment under a post/idea.""" request.data["owner"] = request.user["id"] request.data["note_id"] = note_id if comment_id: try: parent_comment = Comment.objects.get(id=comment_id) request.data["parent_comment"] = parent_comment except Comment.DoesNotExist: request.data["parent_comment"] = None else: request.data["parent_comment"] = None serializer = CommentSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) serializer for the comment model class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = "__all__" and my url path path("<uuid:note_id>/comments/<uuid:comment_id>/replies/", views.CommentsGetOrCreateView.as_view(), name="CommentRepliesGetOrCreateView") I'm trying to create Comment off of a Comment that is created off of a Note. Currently i can create a Note and create a Comment off of it and can retrieve comments under a comment but cant POST with the given url below as i need to. I currently get error on postman as ["parent_comment" : "Must be a valid UUID"] I have tried reorganizing my post method and tried changing the serializer so the parent_comment can be null. Ive also tried adding .id at the end of "request.data["parent_comment"] = parent_comment.id" -
Django Website on Godaddy Domain wont load without https://www
My django site cannot be loaded by just typing in example.com or https://example.com I have to fully type https://www.example.com Does anyone know why this may be? I thought it might have to be related to the SSL certicate but that all seemed fine. The domain is hosted with Godaddy and I am using Pythonanywhere.com to deploy my django site. -
Uploading files using design pattern with python
I used to upload csv, excel, json or geojson files in my a postegreSQL using Python/Django. I noticed that the scripts is redundant and sometimes difficult to maintain when we need to update key or columns. Is there a way to use design pattern? I have never used it before. Any suggestion or links could be hep! -
Django rest framework backend returns data on wrong Host after initial call on ECS using ALB
I am trying to have my frontend, which is on my current domain, communicate with my backend which is on a subdomain using https. On the initial login api call it succesfully manages to dispatch the post data to the right api endpoint located on the subdomain and it returns me the requested details using the same link as its Host. However, the subsequent calls that are triggered after the login api call all have their Host replaced with the DNS address of the ALB, which is not a Http and not the address I sent the call from. This prevents the data from being received and I get a mixed block error on it. The first post call seems functionally fine and retrieves the bearer and access tokens fine, however the subsequent or any other calls dont work. I am able to use the API endpoints fine using postman and on the api.example.com backend site. I don't have NGINX set up, I believe since the ALB performs the purpose already? Is this also the right judgement to take? I have seen some tutorials use it but none specifically that details the exact use of ECS and setting up Https … -
Need to get the last 3 elements Django-Queryset
Need to get the last 3 elements, but each one separately without using loops in Django-Queryset I try to get elements with use order_by(-id)[:3], but I need to be able to use each of the elements without “for” -
Django bulk upload the files inside the zip
We want to bulk upload the files which is inside the zip, earlier we used to upload file by file. But the problem with that logic is, if the zip file is big by size. It's taking so much time to upload. So i need some solution to resolve this. Old Logic: archive = ZipFile(zipfile, 'r') for filename in archive.namelist(): name = filename.split('/') if name[-1] != '' and '__MACOSX' not in name: f = archive.open(filename) library = BulkUpload() library.organisation = organisation_id library.course = course_obj library.file_path.save(filename, ContentFile(f.read())) I tried a new logic with bulk create, but there record is created in DB but file is not uploaded in the blob. When i check the DB, the file place only name is there. archive = ZipFile(zipfile, 'r') for filename in archive.namelist(): name = filename.split('/') if name[-1] != '' and '__MACOSX' not in name: request_obj.append(BulkUpload( organisation=data['organisation']['id'], course=course_obj, file_path=filename )) BulkUpload.objects.bulk_create(request_obj) -
Django admin filefield 404 on download
i have problems with my django app. Since a few days i have the problem that the download dont work on production but i cant find the reason why... I can upload files and they are stored in the correct folder, but as soon as i click on it i get a 404 error "file not found.." Here is my setup: settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] . . . TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") MEDIA_DIR = os.path.join(BASE_DIR, "media") STATIC_ROOT = STATIC_DIR STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "staticfiles/static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = MEDIA_DIR MEDIA_TEMPLATE_ROOT = os.path.join(MEDIA_ROOT, 'templates') MEDIA_TEMP = os.path.join(MEDIA_ROOT, 'tmp') urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('jet/', include('jet.urls', 'jet')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I tried many different configurations of the media_url, media_root etc... without success.. -
close socket blocked from consumer
I have an open socket in an infinite loop listening on an XMPP server to receive information regarding the presence of users. Whenever new information is received, it is sent to a consumer to update the list of online users in real time. This is the code for my socket: # get consumer channel layer channel_layer = get_channel_layer() # define socket s: socket.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock: ssl.SSLSocket = ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1_2) # connect to XMPP Server sock.connect((hostname, port)) # send request sock.sendall("<presence/>".encode()) while True: # receive presence presence = sock.recv(4096) async_to_sync(channel_layer.group_send)("presence_channel", {"type": "presence", "text": presence}) sock.close() And this is the code of my consumer: class PresenceConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.name = "presence_channel" # join channel await self.channel_layer.group_add(self.name, self.channel_name) await self.accept() async def disconnect(self, close_code): # leave channel await self.channel_layer.group_discard(self.name, self.channel_name) # receive message from channel async def presence(self, event): # Send message to WebSocket await self.send_json(event) I would like to know how I can stop the socket when I disconnect from the consumer (for example because the user refreshes the page or closes the application). I have tried used control flags or global variables, but the socket gets stuck on recv(). I also would not want to set a … -
Django error in modul i don't know how to fix this
(car) PS C:\Users\Lenovo\Desktop\Clg Project\7\CarDealerWeb-Django\CarDealerWeb-Django> python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Lenovo\Desktop\Clg Project\7\CarDealerWeb-Django\CarDealerWeb-Django\manage.py", line 21, in <module> File "C:\Users\Lenovo\Desktop\Clg Project\7\CarDealerWeb-Django\CarDealerWeb-Django\car\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Lenovo\Desktop\Clg Project\7\CarDealerWeb-Django\CarDealerWeb-Django\car\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ckeditor' error remove -
django janja compare database value
Hi I have some data store in the database. some of the value is default I want to check if the value is not default then pick the value and perform some action on it. product: "{{DB_report_query.product.name}}" {% if DB_report_query.product.summary != 'TBS' %} {{DB_report_query.summary}} {% endif %} But this does not work -
How to disable CSRF_COOKIE_SECURE in django
CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = False My frontend and backend run on different domains in development, I'm trying to enable setting csrf-token cookie using HTTP, but I guess False value for CSRF_COOKIE_SECURE option somehow gets interpreted as 'not set' and Chrome says My second guess is that it has to be True, otherwise it's not allowed to send cookies between domains. So my question is whether it's possible to set cookies via plain HTTP with cross-domain requests and if it is, what are the right Django settings for achieving this -
"Python 'banktype' cannot be converted to a MySQL type" error in django
When connecting to the banking portal, this error is given, which seems to be because the information is not being entered into the mysql database. Of course, this works correctly locally on sqlite3, but when it comes to the server, this error is given This is error: TypeError at /gotogateway/ Python 'banktype' cannot be converted to a MySQL type Request Method: GET Request URL: https://omidzaferan.ir/gotogateway/ Django Version: 4.1.5 Exception Type: TypeError Exception Value: Python 'banktype' cannot be converted to a MySQL type Exception Location: /home/omidzaf1/virtualenv/OmidZaferan/3.9/lib/python3.9/site-packages/mysql/connector/conversion.py, line 223, in to_mysql Raised during: core.views.go_to_gateway_view Python Executable: /home/omidzaf1/virtualenv/OmidZaferan/3.9/bin/python3.9 Python Version: 3.9.12 Python Path: ['', '/home/omidzaf1/OmidZaferan', '/home/omidzaf1/virtualenv/OmidZaferan/3.9/lib64/python39.zip', '/home/omidzaf1/virtualenv/OmidZaferan/3.9/lib64/python3.9', '/home/omidzaf1/virtualenv/OmidZaferan/3.9/lib64/python3.9/lib-dynload', '/opt/alt/python39/lib64/python3.9', '/opt/alt/python39/lib/python3.9', '/home/omidzaf1/virtualenv/OmidZaferan/3.9/lib/python3.9/site-packages'] Server time: Tue, 31 Jan 2023 15:15:54 +0330 -
Implement autopayment in PayPal Django?
Can we implement auto payment using PayPal in the Django Application? I want to implement an auto payment system using PayPal, but I am not able to find any proper solution regarding this. Can anyone help? -
Why doesn't django have a `pgettext_noop` function?
gettext_noop Is really great when you want to tag enum values to be translated dynamically later, and pgettext is also really great when some words can be used in different contexts with different meanings. Why is there no pgettext_noop to get best of both ? -
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: api_ingredient.meal_id
I try to save menu.json file data to my database sql in django rest_framework api. Can you help me? Can you check my database model is it okey? also I got error I mentioned below. models.py class Meal(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) is_vegetarian = models.BooleanField(default=False) is_vegan = models.BooleanField(default=False) def __str__(self): return self.name class Ingredient(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) groups = models.CharField(max_length=100) meal = models.ForeignKey(Meal, on_delete=models.CASCADE) def __str__(self): return self.name class Option(models.Model): id = models.AutoField(primary_key=True) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) name = models.CharField(max_length=100) quality = models.CharField(max_length=100) price = models.FloatField() per_amount = models.CharField(max_length=100) def __str__(self): return self.name class MealIngredient(models.Model): id = models.AutoField(primary_key=True) meal = models.ForeignKey(Meal, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) path = r"C:\Users\OSMAN MERT\Desktop\menu\menu_core\menu.json" with open(path) as f: data = json.loads(f.read()) for meal in data["meals"]: id = meal["id"] name = meal["name"] meal_obj, created = Meal.objects.get_or_create(name=name) for ingredient in meal["ingredients"]: name_in = ingredient["name"] ingredient_obj, created = Ingredient.objects.get_or_create(name=name_in) MealIngredient.objects.get_or_create(meal=meal_obj, ingredient=ingredient_obj) for ingre in data["ingredients"]: ingre_name = ingre["name"] ingre_obj, created = Ingredient.objects.get_or_create(name=ingre_name) for opti in ingre["options"]: opt_name = opti["name"] opt_quality = opti["quality"] opt_price = opti["price"] opt_amount = opti["per_amount"] Option.objects.get_or_create(ingredient=ingre_obj, name=opt_name, quality=opt_quality, price=opt_price, per_amount=opt_amount) I tried delete my database and makemigrations, migrate but it did not solve my problem. My error is: File … -
Is there anyway to remove the ul element from the django forms.errors?
I was wondering if there is anyway to remove the ul element form the django form.errors. Image what the page looks like This is what it looks like, but I don't like that indented offset look it has to it. Here is the code for template. {% extends 'base.html' %} {% block title %} Register {% endblock title %} {% block content %} {% if form.errors %} {% for field in form %} {{ field.errors }} {% endfor %} {% endif %} <form method="post"> {% csrf_token %} <div class="mt-4 mb-4"> <label for="{{ form.first_name.label }}"> {{ form.first_name.label }} </label> {{ form.first_name }} </div> <div class="mb-4"> <label for="{{ form.last_name.label }}"> {{ form.last_name.label }} </label> {{ form.last_name }} </div> <div class="mb-4"> <label for="{{ form.username.label }}"> {{ form.username.label }} </label> {{ form.username }} </div> <div class="mb-4"> <label for="{{ form.email.label }}"> {{ form.email.label }} </label> {{ form.email }} </div> <div class="mb-4"> <label for="{{ form.password.label }}"> {{ form.password.label }} </label> {{ form.password }} </div> <div class="mb-4"> <label for="{{ form.password2.label }}"> {{ form.password2.label }} </label> {{ form.password2 }} </div> <button class="btn btn-primary" type="submit"> Register </button> </form> {% endblock content %} I have set ul > errorlist to list-display-type: none, in my css but that didn't fix the … -
How do I update this form field so it stays hidden on page load?
I have this form in my Django project. On page load it should only show the entity name, but it's showing both the entity-name and quote-text fields. The page should only show the quote-text field when the entity-name is not in the database. The toggle works for all cases except page load. It's the line if (entities.length === 0) I need to update but I'm not sure what to update it to. <form> <label for="entity-name">Entity Name:</label> <input type="text" id="entity-name" name="entity-name" onkeyup="searchEntities()"> <div id="search_results"></div> </form> <form id="quote-form"> <label for="quote-text">Quote Text:</label> <textarea class="form-control" id="quote-text" name="quote-text" rows="3"></textarea> <button type="submit" class="btn btn-primary">Submit</button> </form> <script> function searchEntities() { const entityName = document.querySelector('#entity-name').value; console.log('hi'); console.log(entityName); fetch(`/search-entities/?entity_name=${entityName}`) .then(response => response.json()) .then(entities => { const searchResults = document.querySelector('#search_results'); searchResults.innerHTML = ''; if (entities.length === 0) { // Show the quote field document.querySelector('#quote-form').style.display = 'block'; } else { entities.forEach(entity => { const p = document.createElement('p'); p.innerHTML = entity.name; searchResults.appendChild(p); }); // Show the quote field document.querySelector('#quote-form').style.display = 'none'; } }); } </script> -
How to learn django ? Do i need to learn flask first?
I'm new to this coding and i recently finished learning python and i wanna learn django but my senior tell me to learn flask first and then only django bcoz django has many prewritten codes that they say is hard to understand .is that right? please tell me which way is better just to learn django right after python or to learn flask and then django? can somebody suggest me which way is better? -
You don't have permission to access that port
In my Django, when I try to run the server, it displays this error. What should be done to fix the error?enter image description here What should be done to fix the error?[ -
Query Database and remove Charfield Choices based on what is in database
I have created a booking form using Django forms. For selecting a time I have a series of choices. However, I want to only display those choices in the form if they don't already exist on that data and time. Here is my models.py: from django.db import models from django.contrib.auth.models import User from django.core import validators import datetime TIME_CHOICES = ( ('12:00:00', '12pm'), ('12:15:00', '12:15pm'), ('12:30:00', '12:30pm'), ('12:45:00', '12:45pm'), ('13:00:00', '1pm'), ('13:15:00', '1:15pm'), ('13:30:00', '1:30pm'), ('13:45:00', '1:45pm'), ('14:00:00', '2pm'), ('14:15:00', '2:15pm'), ('14:30:00', '2:30pm'), ('14:45:00', '2:45pm'), ('15:00:00', '3pm'), ('15:15:00', '3:15pm'), ('15:30:00', '3:30pm'), ('15:45:00', '3:45pm'), ('16:00:00', '4pm'), ('16:15:00', '4:15pm'), ('16:30:00', '4:30pm'), ('16:45:00', '4:45pm'), ('17:00:00', '5pm'), ('17:15:00', '5:15pm'), ('17:30:00', '5:30pm'), ('17:45:00', '5:45pm'), ('18:00:00', '6pm'), ('18:15:00', '6:15pm'), ('18:30:00', '6:30pm'), ('18:45:00', '6:45pm'), ('19:00:00', '7pm'), ('19:15:00', '7:15pm'), ('19:30:00', '7:30pm'), ('19:45:00', '7:45pm'), ('20:00:00', '8pm'), ('20:15:00', '8:15pm'), ('20:30:00', '8:30pm'), ('20:45:00', '8:45pm'), ('21:00:00', '9pm'), ('21:15:00', '9:15pm'), ('21:30:00', '9:30pm'), ('21:45:00', '9:45pm'), ('22:00:00', '10pm'), ('22:15:00', '10:15pm'), ('22:30:00', '10:30pm'), ('22:45:00', '10:45pm'), ) class Booking(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True ) first_name = models.CharField(max_length=25, null=False, blank=False) last_name = models.CharField(max_length=25, null=False, blank=False) email_address = models.EmailField(default="email@email.com") phone_number = models.IntegerField() date_of_booking = models.DateField(default=datetime.date.today()) time_of_booking = models.CharField( max_length=10, choices=TIME_CHOICES, default="" ) number_of_people = models.IntegerField() special_requests = models.CharField(max_length=200) def __str__(self): # code adapted from Models Part … -
How to implement Redis db without caching in django
I want to implement the Redis Database and Postgres in the Django cache, but I need to implement them separately. means I need to check the Redis manually and not through the Django caching. Could any help me implement this? -
django image gives me an error "This field is required."
When I send an image to the bank to save, it always returns this message "This field is required." but I fill the field with an image but it always returns this error. Views enter image description here Models enter image description here Forms enter image description here HTML enter image description here URLS enter image description here -
Websocket connection failed: With django and vue.js
I'm trying to set up websockets to show any new entry in Post model (I'm new with websockets) class Post(models.Model): title = models.CharField(max_length=200, unique=True) content = models.TextField() status = models.IntegerField(choices=STATUS, default=0) author = models.ForeignKey( User, related_name="blog_posts", on_delete=models.CASCADE, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) This is the consumers.py class PostConsumer(ListModelMixin, GenericAsyncAPIConsumer): queryset = Post.objects.all() serializer_class = PostSerializer permissions = (permissions.AllowAny,) For checking if it works I have an html and I'm handling the websockets with vue.js here's the more relevant part of the index.html <title>Testing Websockets</title> </head> <body> <div id="app" class="row mt-5"> <div class="col-1"></div> <div class="col-10"> <div class="card"> <p class="card-header">Display list of all the posts in Real-Time</p> <div class="card-body"> <table class="table align-middle mb-0 bg-white"> <thead class="bg-light"> <tr> <th>Title</th> <th>Status</th> <th>Author</th> </tr> </thead> <tbody> <tr v-for="post in posts"> <td> <p class="fw-normal mb-1">[[ post.title ]]</p> </td> <td> <span class="badge rounded-pill d-inline" :class="{'bg-success': post.status !== 'Draft', 'bg-warning': post.status === 'Draft'}" > [[ post.status ]] </span> </td> <td>[[ post.author ]]</td> </tr> </tbody> </table> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous" ></script> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script> <script> vueApp = new Vue({ el: "#app", delimiters: ["[[", "]]"], data() { return { posts: [], }; }, }); … -
How to convert this SQL query to Django Queryset?
I have this query which selects values from two different tables and used array agg over matched IDs how can I get same results using the queryset. Thank you! select sf.id_s2_users , array_agg(sp.id) from s2_followers sf left join s2_post sp on sp.id_s2_users = sf.id_s2_users1 where sp.id_s2_post_status = 1 and sf.id_s2_user_status = 1 group by sf.id_s2_users