Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to install postgres within docker container and containerizing django project
I am new to docker and web-development generally. When trying to containerize my django-project I run into an error and can't solve it for several days. The error might be silly, but I can't find a solution. I'll be very glad if someone helps me to solve me the problem. Thank you in advance. As operational system I use Ubuntu 22.04 Here is the output after commands docker compose build and docker compose up: [+] Running 2/0 ⠿ Container test_task-db_task-1 Created 0.0s ⠿ Container test_task_container Created 0.0s Attaching to test_task-db_task-1, test_task_container test_task-db_task-1 | test_task-db_task-1 | PostgreSQL Database directory appears to contain a database; Skipping initialization test_task-db_task-1 | test_task-db_task-1 | 2023-06-07 10:46:07.124 UTC [1] LOG: starting PostgreSQL 14.1 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.3.1_git20211027) 10.3.1 20211027, 64-bit test_task-db_task-1 | 2023-06-07 10:46:07.125 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 test_task-db_task-1 | 2023-06-07 10:46:07.125 UTC [1] LOG: listening on IPv6 address "::", port 5432 test_task-db_task-1 | 2023-06-07 10:46:07.147 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" test_task-db_task-1 | 2023-06-07 10:46:07.163 UTC [21] LOG: database system was shut down at 2023-06-07 10:45:29 UTC test_task-db_task-1 | 2023-06-07 10:46:07.218 UTC [1] LOG: database system is ready to accept connections test_task_container | Watching … -
Multiple form view, in which JSON fed to one form, constitutes another in Class Based Views
I want to create a class based view in Django that after receiving one form, will translate it to another and then accept the second form (both forms accept files - the first just one, the other several). I have tried the approach with MultiFormsView (you can check the question here): Cannot proceed with multiform view in class based views And then I moved a bit further with Tarquiniuses help with another method: I cannot pass the values between the methods in classBasedView Now the code looks like this: Django: @user_authenticated @user_hkm @translation def firmware_cbv2(request): class Firmware_view(FormView): template_name = "dev_tools/firmware_cbv2.html" form_class = forms.InitialFirmwareForm2 def get_success_url(self): return self.request.path def form_invalid(self, form): print("the form is invalid") return super().form_invalid(form) def get_context_data(self, message=None, bundle=None,**kwargs): context = super().get_context_data(**kwargs) context['bundle'] = bundle context['message'] = message return context def form_valid(self, form): bundle, message = {}, {} if request.FILES: if len(request.FILES) < 2 and "file" in request.FILES: file = request.FILES["file"] try: content = json.loads(file.read().decode('utf-8')) folder_name = utils.format_folder_name(content["title"]) units = [] for unit in content["units"]: units.append(unit) bundle["units"] = units bundle["file"] = { "name": folder_name, "content": json.dumps(content) } message.update({ "type": "info", "content": "The form was parsed successfully" }) except Exception as e: print("there was an error", e) else: print("I am … -
Tagged Posts not Paginating
I have a Django app that displays posts that are created using Django's built-in admin interface. The posts have tags incorporated using django-taggit (https://django-taggit.readthedocs.io/en/latest/) The main page (home.html) is set up to display posts and tags and when a tag is clicked, it takes you to a page (tag_posts.html) with all tagged posts e.g. If i click on a post with the tag 'apple', I am presented with a page that shows all posts tagged with 'apple'. The main page works as intended, as does the pagination for home.html. THE ISSUE: When viewing the list of tagged posts, it is showing the number of posts by the number specifed with paginate_by (in the code it's 2) but not showing me the option to click next/previous or page numbers. What I Have Attempted: I thought it may be the Bootstrap navigation links in the html file but I am using the same as in my home.html, which works. re-factored my class-based view to include the tag as part of the context and supplying to the html as a context variable Used basic html for navigation links The issue lies with TagPostsView Here is my view.py: from django.shortcuts import get_object_or_404, render from … -
what is more often used in practice: FBV or CBV?
I'm new to Django development, so I want to ask people who have more practice - what do they use more often? I'm of course assuming it's CBV since it's easier for others to read, but I'll ask anyway. thanks in advance for your reply -
Django - generate product page with one url and view function?
I have a list of products with product ids. How do i create the function to open the page based on the product_id and user_id? Currently I have in urls.py: path('product/<int:product_id>/', views.product, name='product'), And in my views.py: @login_required() def product(request, product_id, user_id=None): return render(request, 'users/product.html') I am new to Django and could not find an answer searching online... -
Fulltext Search in Django with Haystack/Whoosh - Displaying Search results with tags from models not in results
swarm intelligence, right now i try to implement a database fulltext-search in a Django-project with haystack and whoosh in the backend. Installation, configuration and indexing ist done. Search works as intended. So NOW I'm talking about displaying search results: "side" problem: Results seem to be not sorted. I would like to know, WHERE in the different code-tables from Django (views/forms/serach-index/urls.py) i can set a configuration for the result-ordering? Reason for Question is furthermore: When I am trying to set up the template for displaying the results, it is no problem to use a {{ result.object.last_name }} tag when result is from model, where "last_name" is included.... But if i get results from a child table, what do i have to do to display "last_name" from parent table, too? My search-indexes.py: from haystack import indexes from employees.models import Employees, Employments, Professions, ForeignMissions, \ LanguageAbilities, SecondDegrees, MilCourseDetails, CivCourseDetails class EmployeesIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') titel_rank = indexes.CharField(model_attr='title_rank', null=True) rank_short = indexes.CharField(model_attr='rank_short', null=True) last_name = indexes.EdgeNgramField(model_attr='last_name') first_name = indexes.CharField(model_attr='first_name') prefix_title = indexes.CharField(model_attr='prefix_title', null=True) suffix_title = indexes.CharField(model_attr='suffix_title', null=True) street = indexes.CharField(model_attr='street') building_number = indexes.CharField(model_attr='building_number') postal_code = indexes.CharField(model_attr='postal_code') city = indexes.CharField(model_attr='city') country = indexes.CharField(model_attr='country') employee_number = indexes.CharField(model_attr='employee_number') key_number = indexes.CharField(model_attr='key_number', null=True) … -
Django RESTAPI how to make calculation APIs PUT or POST?
Hi I'm trying to make calculation rest api using django. My objective is to save preprocessed_data(result) into the db table field The process is read raw data path(txt file) from db and calculate using pandas & numpy after that make result txt file save to db preprocessed_data field. this is my models.py class PreprocessData(models.Model): raw = models.FileField( upload_to=_user_directory_path, storage=OverwriteStorage(), preprocessed_data = models.CharField( max_length=200, null=True, blank=True, ) ) and views.py class PreprocessCalculate(APIView): def _get_object(self, pk): try: data = PreprocessData.objects.get(id=pk) return data except PreprocessData.DoesNotExist: raise NotFound #get or put or post which is the best design for api? # PUT API def put(self, request, pk): data = self._get_object(pk) serializer = PreprocessCalculateSerializer(data, request.data, partial=True) if serializer.is_valid(): updated_serializer = serializer.save() return Response(PreprocessDataSerializer(updated_serializer).data) else: return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) and serializers.py class PreprocessResultField(serializers.CharField): def to_representation(self, value) -> str: ret = {"result": value.test_func()} return ret def to_internal_value(self, data): return data["result"] class PreprocessCalculateSerializer(serializers.ModelSerializer): preprocessed_data = PreprocessResultField() class Meta: model = PreprocessData fields = ("uuid", "preprocessed_data") my question is when I use the above code. In db "preprocessed_field" is still null... what is the problem in custom field serializer? I choose "PUT" method to calculate raw file, but I think if I use "PUT" it has a problem to change … -
Override the django save and update function. both are working fine but for update function it is entering in a infinite loop
Override the django save and update function. both are working fine but for update function it is entering in a infinite loop class PrimitiveQuerySet(QuerySet): def update(self, *args, **kwargs): super().update(*args, **kwargs) super().using('New').update(*args, **kwargs) class Primitive(models.Model): modified_by = models.CharField(max_length=200, null=True) modified_on = models.DateTimeField(null=True) deleted_by = models.CharField(max_length=200, null=True) deleted_on = models.DateTimeField(null=True) deleted_flag = models.BooleanField(null=True, blank=True, default=False) objects = PrimitiveQuerySet.as_manager() def save(self, *args, **kwargs): # Dump data into default database super().save(*args, **kwargs) # Save the same data to the new database using_db = kwargs.pop('using', None) # Extract 'using' parameter self._state.db = using_db # Set the target database for saving self.save_base(using='New', force_insert=False, force_update=False ` I got the approach how to update and save data in two db but issue is it is going into infinite loop -
Django Chatterbot-how to add "default-response" to settings .py?
In my "django" application in settings.py I have: CHATTERBOT = { 'name': 'bot1', 'storage_adapter': "chatterbot.storage.SQLStorageAdapter", 'logic_adapters': [ 'chatterbot.logic.BestMatch', ] } How do I add the auto default response parameter? I tried countless ways but it doesn't work. -
Django on Android pydroid3.Python and Django are fully functional. But when I try to run Django admin site on Chrome it shows "Server error occured"
This is what am facing with with Django on my Android I'm using Pydroid on my phone. Python and Django are fully functional. But when I try to run Django admin site on Chrome it shows "Server error occurred. Contact administrator" System check identified no issues (0 silenced). April 28, 2022 - 16:28:28 Django version 4.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C. [28/Apr/2022 16:28:45] "GET /admin/ HTTP/1.1" 302 0 [28/Apr/2022 16:28:55] "GET /admin/ HTTP/1.1" 302 0 Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/zoneinfo/_common.py", line 12, in load_tzdata return importlib.resources.open_binary(package_name, resource_name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 88, in open_binary package = _get_package(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 49, in _get_package module = _resolve(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 40, in _resolve return import_module(name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 972, in _find_and_load_unlocked File "", line 228, in _call_with_frames_removed File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 972, in _find_and_load_unlocked File "", line 228, in _call_with_frames_removed File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 984, in _find_and_load_unlocked ModuleNotFoundError: No … -
How to create three dependent drapdowns in Django, that the second is dependent on the first, and the third is dependent on the first and the second?
In this program, the first drapdown is a field named education level, which is independent. Then there is a drapdown named field of study, which is related to the level of study. Then it has a drapdown called book, which is related to the first and second drapdown, which means the level of study and field of study. It is expected that after selecting a education level and field of study, the book drapdown will bring only the list of books that are related to this degree and field of study. -
Shopify embedded app "frame-ancestors 'none'" error
I am having some issues with my embedded app. I checked the app in incognito mode (chrome) and found that it is not loading any page. I have configured CSP headers on my django backend with django-csp with middleware (adding screenshot of the API call from XHR section from network tab. Tech Stack Frontend: React Backend: Django Inspection console prints this error: Refused to frame '' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'none'". I am not able to figure out the issue. I can provide more info if needed. class CSPMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Check if the request URL matches the desired prefix if request.path.startswith('/endpoint'): # Apply the CSP header for the desired URL prefix response['Content-Security-Policy'] = "frame-ancestors https://shopify-dev.myshopify.com https://admin.shopify.com;" return response -
ValueError: No route found for path 'admin/'
I'm running a Django server and encountering an error when trying to access all backend URLs. The specific error messages I'm receiving are: Exception inside application: No route found for path 'admin/'. Traceback (most recent call last): File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/routing.py", line 165, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'admin/'. HTTP GET /admin/ 500 [1.00, 127.0.0.1:54986] Exception inside application: No route found for path 'favicon.ico'. Traceback (most recent call last): File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/routing.py", line 165, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'favicon.ico'. HTTP GET /favicon.ico 500 [0.84, 127.0.0.1:54986] I have a routing.py file where I define the routes for WebSocket consumers. Here's the content of that file: from django.urls import path from channels.routing import URLRouter from WS.consumers import ( CodeConsumer, WhiteboardConsumer, ChatConsumer, ) ws_application = URLRouter( [ path("ws/code/", CodeConsumer.as_asgi()), path("ws/whiteboard/", WhiteboardConsumer.as_asgi()), path("ws/chat/", ChatConsumer.as_asgi()), ] ) And here's my asgi.py file: import os from django.core.asgi import get_asgi_application from channels import URLRouter, ProtocolTypeRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack … -
Using serializer with foreign key model when creating new entry
At first, I had this serializer and it works well for GET and POST(create new entry) class DrawingSerializer(ModelSerializer): drawing = serializers.FileField() detail = serializers.JSONField() class Meta: model = m.Drawing fields = ('id','detail','drawing','user','created_at','updated_at') in viewset where creating entry. class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def create(self, request, *args, **kwargs): request.data['user'] = request.user.id #set userid serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) # it makes the new entry with user return Response(serializer.data) and models.py class CustomUser(AbstractUser): detail = models.JSONField(default=dict,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Drawing(models.Model): drawing = f.FileField(upload_to='uploads/') detail = models.JSONField(default=dict) user = models.ForeignKey(CustomUser,on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In this casel, user is foreign key model. So I want to get the user's name,email and so on, then I changed Serializer like this. class DrawingSerializer(ModelSerializer): drawing = serializers.FileField() detail = serializers.JSONField() user = CustomUserSerializer(read_only=True) # change here class Meta: model = m.Drawing fields = ('id','detail','drawing','user','created_at','updated_at') It also works well for get. I can get the data from CustomUser Model as user. however when POST(creating), it shows the error django.db.utils.IntegrityError: (1048, "Column 'user_id' cannot be null") Why does this happen and what is the user_id? -
inline many to many field inside django admin
I have a model that has a many-to-many relationship with another model. I want to have the options inline in my question model in my Django admin. That is, stacked inline is not enough for me, because I want to be able to edit all the option fields there, not just a box to add in a more beautiful way. class Option(models.Model): ... class Question(models.Model): options = models.ManyToManyField(Option) i use TabularInline and StackerInline but not enough for me. Also, I used the Django-nested-inline package, but to implement it, it is necessary to have a foreign key relationship from the options to the questions, and I don't want it to be like that. -
In django how do i keep the user logged in in websocket
In my django project, I have a page that will send http request only when it is opened for the first time, after that a websocket connection is established and all data is passed through websocket. In order to keep the user logged in, I added this logic in the sent data method. During the test, it seems to have worked, and the expiration time of the session has always been what I expected. But after a period of time (more than SESSION_COOKIE_AGE), I refreshed the page and found that I was redirected to the login interface. async def send_data(self, event=None): data = event['message'] data = self.request_data(data) self.scope["session"].set_expiry(SESSION_COOKIE_AGE) await sync_to_async(self.scope["session"].save)() dic = {'status': '1', 'msg': 'success', 'data': data} await self.send(text_data=json.dumps(dic)) I want to know why this is happening and how can I go about it -
How to make auto search without pressing the search button in django
I want to create a search function where if I enter some words, it can automatically display the corresponding results of those words without pressing the search button. Here's the html script that I made: <div class="container-fluid"> <div class="landingtext text-center" style="margin-top: -450pt; color: aliceblue;"> <h1>#SearchBook,<br> Search your book</h1> </div> <br> <main style="text-align: center;"> <div style="display: inline-block;"> <form action="{% url 'search:search' %}" autocomplete="off" method="GET"> <input type="search" id="textInput" onkeyup="callSearchAPI(event)" name="q" placeholder="Search your book..." value="{{search}}"> <button type="submit" class="btn btn-light">Search</button> </form> <div class = "dropdown" id="dropdown"> </div> </div> </main> </div> <div class="container text-center"> {% for data in data %} <div class="book-wrapper text-center"> <div class="coverpage"> <img src="{{ data.book_cover}}"/> </div> <a>{{ data.book_title|text_short }}...</a> <p> {{ data.stock }} </p> </div> {% endfor %} {% if data|length > 0 %} <div class="d-pagination"> <ul class="pagination"> {% if data.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">First</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ data.previous_page_number }}">Previous</a> </li> {% endif %} {% for ord in data.paginator.page_range %} {% if data.number == ord %} <li class="page-item active"> <span class="page-link">{{ ord }} <span class="sr-only">(current)</span> </span> </li> {% elif ord > data.number|add:'-3' and ord < data.number|add:'3' %} <li class="page-item"> <a class="page-link" href="?page={{ ord }}">{{ ord }}</a> </li> {% endif %} {% endfor %} {% if data.has_next %} … -
issue with setting dynamo db created_at field
I am trying to add a new field 'created_time' in my existing dynamodb. another field 'updated_time' field already exists. I want to set the created_time only once, when the new record is created. updated_time updates at every change in record using .save() function of pynamodb. For this purpose I am using default_for_new for created_time in my django model class. But still my created_time is updated even when updated_time updates. (they are kind of moving in sync) Below is my code: from pynamodb.models import Model from pynamodb.attributes import UTCDateTimeAttribute from datetime import datetime class MyModel(Model): id = UnicodeAttribute(hash_key=True) created_time = UTCDateTimeAttribute(default_for_new=datetime.utcnow) updated_time = UTCDateTimeAttribute(default=datetime.utcnow()) and I am using the code as def fun(key, isrecordexist): data = MyModel(id=key, updated_time=datetime.utcnow(), created_time=datetime.utcnow) if isrecordexist: data.save(MyModel.id.does_not_exist()) else: data.save() isrecordexist is a bool value that is passed if record already exist in table. I have already tried the solution in Saving object creation datetime using Pynamodb -
Hosting Django APIs with Celery, Redis and ELK on AWS
I need some suggestions with the architecture of our application. The details are as follows: The application is being written in Django and hosted on AWS. We are using RDBMS as PostgreSQL and the ELK Stack (Open Source based, not the one provided by AWS) for storing Unstructured data for fast retrieval etc. So, my queries are: Currently we are using EC2 instances for hosting the application, but we would like to move to Serverless architecture and use AWS Fargate. Could someone please point towards how this can be done? We would like to use Celery and Redis to be used along with Django and host the same on AWS, but not 100% sure on how this can be done. How to incorporate/host the Open Source ELK on AWS? And that too along with AWS Fargate? How to use/enable the API Gateway and the Elastic Load Balancer in AWS for hosting the Django APIs? Regards, Subhash I'm unable to find a way to incorporate Celery and Redis with AWS Fargate. Also, I'm not sure if Open Source ELK can be hosted on AWS. -
FastAPI vs Flask vs Django for Machine Learning Projects with React.js as frontend?
I completed my Master's degree recently, and I now find myself with a significant amount of available time. I am eager to explore and bring Machine Learning ideas and projects to the web domain. In this regard, I would greatly appreciate valuable suggestions and recommendations for a suitable Python framework that aligns with my use case. I am looking for the best framework that allows me to seamlessly integrate Machine Learning capabilities into web-based projects. I have already gone through a lot of posts on Reddit, but nothing really speaks specifically to this topic. Thank you in advance for your insights and recommendations! -
Django deployment with Vercel error after succesful deployment: Serverless Function Invocation Failed
Tried to deploy my django project on vercel which was successfully deployed but then I get this error when I try to view my pages: [ERROR] ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Traceback (most recent call last): File "/var/task/vc__handler__python.py", line 159, in vc_handler response = Response.from_app(__vc_module.app, environ) File "/var/task/werkzeug/wrappers/base_response.py", line 287, in from_app return cls(*_run_wsgi_app(app, environ, buffered)) File "/var/task/werkzeug/test.py", line 1096, in run_wsgi_app app_rv = app(environ, start_response) File "/var/task/django/core/handlers/wsgi.py", line 131, in __call__ signals.request_started.send(sender=self.__class__, environ=environ) File "/var/task/django/dispatch/dispatcher.py", line 180, in send return [ File "/var/task/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/var/task/django/db/__init__.py", line 27, in reset_queries for conn in connections.all(): File "/var/task/django/utils/connection.py", line 76, in all return [self[alias] for alias in self] File "/var/task/django/utils/connection.py", line 76, in <listcomp> return [self[alias] for alias in self] File "/var/task/django/utils/connection.py", line 62, in __getitem__ conn = self.create_connection(alias) File "/var/task/django/db/utils.py", line 204, in create_connection backend = load_backend(db['ENGINE']) File "/var/task/django/db/utils.py", line 111, in load_backend return import_module('%s.base' % backend_name) File "/var/lang/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 … -
Django send html email with image as body
I am trying to send an html email with an image in the body using python-Django. But when I try to send the email I get the email without the image. So Tried hard coding a link to an image from the internet into my email context and the email was sent and the picture also did show up but then when i tried to send an email with a picture from my media files it wont load the picture when the user receives it. I wrote a test function to send an html email but it does not display the picture on the email. here is my code def send_html_email(subject, from_email, to_email, html_content): # Create the email message email = EmailMultiAlternatives(subject, strip_tags(html_content), from_email, to_email) email.attach_alternative(html_content, "text/html") # Send the email email.send() def send_email_with_picture(request): subject = "Example HTML Email" from_email = "sender email" to_email = ["<recipient email>"] # Retrieve the picture URL from your database email_instance = Emails.objects.get(subject="Test sending email with picture") picture_url = default_storage.url(email_instance.product1_image.name) # Retrieve the current domain current_site = get_current_site(request) domain = current_site.domain # Construct the complete absolute URL of the image picture_url = f"http://{domain}{picture_url}" # Render the HTML content with the absolute image URL html_content = … -
What is the best practice for displaying and filtering data in Django
I'm finding it difficult to find the answer to my question as the wording is too similar to how Django works! I have a simple database with a table called Records that has fields group id, project id, device_name. I want to show all the records for a particular project on a page and give the user filters to select a specific group and/or a specific device. I've no problem getting the data, connecting to foreign keys etc. At the moment I've got all the data loading and am displaying all the groups and devices for the project in select lists in a form. My idea was when they select a different item from a select list it posts the form to get the correct data. For example when they select Group1 it loads all the devices and records in group1. My question is: Is that the best way to do this? I feel this is a common use case but searching for Django filters obviously returns query filters. (The reason I'm using dropdown lists is I have limited space on the screen) Also, does anyone recommend any slick css templates or tools for making this common scenario look good? … -
POST error 403 trying to use auth token on local storage to access Django view, then display output in React component
I want to create a component that displays all the songs that were uploaded by a user. I am trying to do this by sending a POST request, which contains the user's username and the auth token from local storage, to the Django view which will filter out all the songs that were not uploaded by the user. The view should then send the list of the songs back to the component. The issue is that when I click on the page to see the user's songs, I get the POST error 403 forbidden. I suspect the issue is with the auth token because when I use a get request to get all songs from all users, not just one, it works. Here is my song list component function SongList(props) { const [songs, setSongs] = useState([]) useEffect(() => { axios.post('/api/songs/', { username: props.username }, { headers: { Authorization: `Bearer ${localStorage.getItem('authToken')}`, }, }).then((response) => { setSongs(response.data); }).catch((error) => { console.log(error); }); }, []); return ( <div> {songs.map((song) => ( <div key={song.id}> <h3>{song.name}</h3> </div> ))} </div> )} Here is my Django view, which worked normally before I added the username filter def getSongs(request): username = request.POST.get("username") songs = Song.objects.filter(username=username) return JsonResponse(list(songs), safe=False) … -
ModuleNotFoundError: No module named 'daphnedjango'
I am trying to add web sockets to my Django application. From my existing project, I starting following the Chat app found in the Daphne documentation. I installed Daphne and Channels, add daphne to the top of Installed Apps and reconfigure asgi.py exactly like the instructions. When I run the server, I get the following error. ❯ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.10/importlib/__init__.py", line 126, 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 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line …