Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set up javascript and django applications to exchange jwt tokens
I have a SAP implemented on the Netlify platform. The processing for the app is implemented in a django api running on a hosted server. Users are authenticated on the Netlify app, but do not need to be authenticated in django. I now want authorised users to be able to post data to the api and the django server objects with the message Forbidden (CSRF cookie not set.): /api/save-archive/{...}/ I am looking at implementing JWT cookies and have considered djangorestframework_simplejwt but that seems to require that the user is authenticated in django My question is, what software elements do I need to be able to generate and consume a token is this scenario? -
Dynamically create a form / dynamically add fields to a form
I've been facing this issue in django and I don't know how to do. Here it is. I have the Product model, and a form allowing a person (not admin) to register a product. I would like to give the possibility to an admin to "build this form or update it", with the fields he wants. The Product template will then be updated with new fields, and the form filled by a person too. Is there a way to do this? Thanks -
Concatenate Properties of Django QuerySet
Can I join Django ORM Model properties/attributes into a string without introducing loops? I have a django model: class Foo(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=1000, db_collation='Latin1_General_CI_AS') I want to select the names into a string from a result of filtering: foos = Foo.objects.filter(id=[1,2,3]) Something equivalent of this piece of C#: using System; using System.Collections.Generic; using System.Linq; public class Program { public class Foo { public string Name { get; set; } } public static void Main() { List<Foo> foos = new List<Foo>(); foos.Add(new Foo { Name = "A1" }); foos.Add(new Foo { Name = "A2" }); Console.WriteLine(string.Join(",", foos.Select(x => x.Name))); } } Which outputs A1,A2. -
Get latest item date where item field_1 & item field_2 have duplicates
I'm using Django 4.0, and Python 3.8. I have a product that has a modification date, department name and designation. I want to retrieve each product but, for products that have the same designation and the same department, I only want to retrieve the last entry. Here is what i have now: ` products = Product.objects.all().order_by('designation') ` I tried sorting on the result and removing duplicate rows it worked for 10 rows but for 100 its dead For the following data: item: designation, date, department item_1, 01/01/1970, department_1 item_2, 01/01/1970, department_2 item_3, 01/01/1970, department_3 item_1, 01/02/1970, department_1 I want: item_1, 01/02/1970, department_1 item_2, 01/01/1970, department_2 item_3, 01/01/1970, department_3 Do you have any advice please ? -
Django/Wagtail Rest API URL Filter with no response
I am using Wagtail and I have an API called 127.0.0.1:8000/api/v2/stories. In the API I am having this JSON response { "count": 81, "results": [ { "id": 122, "title": "Test Blog", "blog_authors": [ { "id": 82, "meta": { "type": "blog.BlogAuthorsOrderable" }, "author_name": "Test", "author_website": null, "author_status": false, }, { "id": 121, "title": "Test Blog 1", "blog_authors": [ { "id": 81, "meta": { "type": "blog.BlogAuthorsOrderable" }, "author_name": "Test", "author_website": null, "author_status": false, }, } The main problem I am fetching is that I want to filter by author name. I have done this query in the URL ?author_name=Test & ?blog_authors__author_name=Test & ?author__name=Test But the response was { "message": "query parameter is not an operation or a recognised field: author_name" } I have added these fields in known_query_parameters but the response was the same as api/v2/stories/. I have tried DjangoFilterBackend but I got the same response every time. How Can I filter by author_name & author_status in the API? Here is my api.py class ProdPagesAPIViewSet(BaseAPIViewSet): renderer_classes = [JSONRenderer] pagination_class = CustomPagination filter_backends = [FieldsFilter, ChildOfFilter, AncestorOfFilter, DescendantOfFilter, OrderingFilter, TranslationOfFilter, LocaleFilter, SearchFilter,] known_query_parameters = frozenset( [ "limit", "offset", "fields", "order", "search", "search_operator", # Used by jQuery for cache-busting. See #1671 "_", # Required … -
Can't associate the correct IDs using the reverse ManyToMany relationship
**Hello, I'm trying to merge two models that are related through a ManyToMany field. Basically I want to establish a reverse relationship between the model "Position" and the model "Sale". Each sale can have multiple positions, but each position should be specific to its sale. Here is what happens. I filter through dates I know there's data (sales) and I get: sale_df sales_id transaction_id total_price customer salesman 0 11 3B6374D5ED85 300.0 Test Testuser 2022-10-25 1 12 D52E5123EDBE 900.0 Test Testuser 2022-10-24 (I purposefully removed "created" and "updated" because they didn't fit nicely here) position_df position_id product quantity price sales_id 0 10 TV 3 300.0 11 1 10 TV 3 300.0 11 2 11 Laptop 1 600.0 12 WHEN positions_df sales_id *should be* => position_id product quantity price sales_id 0 10 TV 3 300.0 11 1 10 TV 3 300.0 12 2 11 Laptop 1 600.0 12 It seems like when I get the sale_id in reverse through the method "get_sales_id()" it associates it with the first instance of the position, instead of prioritizing the sale_id Here is the code: models.py from django.db import models from products.models import Product from customers.models import Customer from profiles.models import Profile from django.utils import timezone … -
Is it OK to use Django development server for single-user applications?
I'm developing an application that controls some piece of complex hardware and exposes a front-end to the users (currently with Django templates, but soon with a separate front-end through DRF calls). My main points of interest are: user management. Admin users have more access session management. Ideally, one cannot login from multiple IPs at the same time. web-socket support for asynchronous notifications and real-time monitoring. asynchronous background operations. e.g. with celery workers Note that the users of these application are the hardware operators which are usually no more than 3-5 tops, and most of the times, only one of them is actively working on it so no real user concurrency, neither real need to scale. So my question is: Is there a real reason I would need to distribute my application using a production server such as gunicorn instead of simply running manage.py runserver? -
How to get exact values of the foreignkeys in django admin
class Mio_terminal(models.Model): terminal = models.CharField(max_length = 50) gate = models.CharField(max_length = 50) gate_status = models.CharField(max_length = 50, default = 'open') #open, occupied, under_maintenance class Meta: unique_together = [['terminal', 'gate']] class Mio_flight_schedule(models.Model): fact_guid = models.CharField(max_length=64, primary_key=True) airline_flight_key = models.ForeignKey(Mio_airline, related_name = 'flight_key', on_delete = models.CASCADE) source = models.CharField(max_length = 100) destination = models.CharField(max_length = 100) arrival_departure = models.CharField(max_length=12) time = models.DateTimeField() gate_code = models.ForeignKey(Mio_terminal, related_name = 'terminal_gate', null = True, on_delete = models.SET_NULL) baggage_carousel = models.CharField(max_length = 100) remarks = models.CharField(max_length = 100) terminal_code = models.ForeignKey(Mio_terminal, related_name = 'airport_terminal', null = True, on_delete = models.SET_NULL) this is models for terminal and flight schedule. I want to have terminal name and gate code instead of the object ... i know we can get this by using str method in models....but we get only single value for this...not more than one please let me know how should i deal with this? -
Creating a rating system scale 1-5 and average rating
enter image description here] This is in python with Django and using SQL as database. I am new to this language. I am having issues with creating the average rating for books. I want to get a list of books that userid's have rated and get the average of it. I don't know if I can use querysets. I also want to know how I can create a comment to warn people on postman that the scale is only 1-5. I don't know if I can do it as an if-else statement or not I look into the django website on aggregation to see if the average works but I can't seem to figure it out. I tried creating an if else statement but > is not supported between instances of -
How to associate an existing user with multiple social accounts (different emails)? [DRF_SOCIAL_OAUTH2]
I'm trying to associate user with multiple social accounts in Django Rest Framework. After user login, user can associate with social accounts (it doesn't matter same email or different email). Now I am using the library drf-social-oauth2. I have done signIn/singUp part. According to Social_Auth_Pipeline, I added this code to associate user SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) The endpoint "http://localhost:8000/auth/convert-token" can handle the singin/singup using social auth.(eg. Facebook, Google) social_core.pipeline.social_auth.associate_by_email managed to associate the user if same email. My Question is How can I connect/associate Social Accounts (* different email/same email) with current login user using drf_social_oauth2? Do I need to add field in user table to associate? OR Do I need to add something to setting.py?... Please advise me. Thank you. -
Active or inactive users
I'm trying to design a django application where users' accounts can only be activated after making payments...Inactive users are denied all the web functionalities until the make payments. How can I go about this? -
Django rest framework user model permissions
I am building a web app using REST API and I have a 4 users that I want them to access only the content they have added to the backend. I have created 3 users say farmers(3 farmers) and added content using each one of them. However, I have been unable to implement permissions such that a farmer can view and delete only what they added. Here's is my code in models.py User = get_user_model() # Create your models here. class Tender(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() date_due = models.DateField(default=datetime.date.today) location = models.CharField(max_length=255, null=False) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Input(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.DecimalField(max_digits=10, decimal_places=2) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Investor(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() location = models.CharField(max_length=255, null=False) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Here's what I implemented in permissions.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, … -
Problem using npm of chart.js in django Project
I tried to use Chart.js in my Django project , when I Use NPM package it's not working but when I use CDN It work Perfectly char.js version 3.9.1 here is my index.html file on my project <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {# <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>#} <script type="application/json" src="/node_modules/chart.js/dist/chart.js"></script> </head> <body> <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </body> </html> my console error in browser is : (index):17 Uncaught ReferenceError: Chart is not defined at (index):17:17 I tried to use chart.min.js in my script but not working. I also Try previous version of charj.js but … -
Python sleep if a function runs for 20 times
I have a function for sending an email which is used in a celery task i need to make the code sleep for a second if that email function is ran for 20 times how can i make this happpen. @app.task(bind=True) def send_email_reminder_due_date(self): send_email_from_template( subject_template_path='emails/0.txt', body_template_path='emails/1.html', template_data=template_data, to_email_list=email_list, fail_silently=False, content_subtype='html' ) so the above code is celery periodic task which runs daily i filter the todays date and send the email for all the records which are today's date if the number of records is more than 20 lets say so for evry 20 emails sent we need to make the code sleep for a second send_email_from_template is function which is used for sending an email -
Group Session in Django Channels
I'm looking for a solution where I want to create a group with n number of users and let them-users join the group. and then finally, delete this group once the work is complete. (the creator of the group can delete this or when everyone from the group disconnects). I have been thinking to design this for the last 3-4 days but I'm not able to. I'm building the transcriber app and this group is to maintain sessions on each topic. For every new topic/scenario, a new group/session is required. The question is - How and when should I delete the group? Suppose I created a group and then everyone joins, I can maintain a database and delete this group when everyone disconnects from this group, somehow I don't think this to be the best option Can anyone guide me to design the best possible option? Will provide more details if required. -
Django Web Application - Monitor local folder and import csv files to database
I have this Django web application project that needs to be hosted on a local network. In addition basic CRUD features, the scope requires to continuously monitor a local storage folder (C: or D: or E:) for csv files and import them to the database (Postgresql). I have already written the code for reading the csv files and importing them to the database and moving these csv files to another folder (after importing). What I don't know is where should I put this code and call the function (import_to_db), such that it runs continuously to scan the folder for new csv files? It cannot be a python command line interface. I am not fully conversant with Django REST Framework and not sure if it applies to this scope, since the csv files will be made available in a local folder. Any tips or references to examples/libraries would help. Code to Import: def get_files(): csv_files = [] for file in os.listdir(os.getcwd()): if file.endswith('.csv'): csv_files.append(file) return csv_files def move_files_to_folder(csv_files, destination): try: os.mkdir("BackupFiles") except: print('BackupFiles Directory Already Exists') finally: for file in csv_files: shutil.move(file, destination) os.chdir(destination) return csv_files def import_to_db(): csv_files = get_files() engine = create_engine( url="postgresql://{0}:{1}@{2}:{3}/{4}".format(user, password, host, port, database)) for file … -
Overlaping URLs in Django (two applications in one Django project)
I'm making my studying project, called GuitarStore. I have two application in this project - shop and blog. Here is fictional situation: I have that "contacts" page for my team of authors, and another "contacts" page for my sale team. Here's piece ofmy guitarstore/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')), path('blog/', include('blog.urls')), path('', RedirectView.as_view(url='/shop/', permanent=True)), ] piece of shop/urls.py: path('', views.shop, name='shop'), re_path(r'^section/(?P<id>\d+)$', views.section, name='section'), re_path(r'^product/(?P<pk>\d+)$', views.ProductDetailView.as_view(), name='product'), re_path(r'^manufacturer/(?P<id>\d+)$', views.manufacturer, name='manufacturer'), path('delivery', views.delivery, name='delivery'), path('contacts', views.contacts, name='contacts'), path('search', views.search, name='search'), and piece of blog/urls.py: path('', views.blog, name='blog'), re_path(r'^blog/(?P<month_n_year>\w{7})$', views.blog_filtered, name='blog'), re_path(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name='post'), path('gallery', views.gallery, name='gallery'), path('about', views.about, name='about'), path('contacts', views.contacts, name='contacts'), path('search', views.search, name='search'), I thought Django would come up with two separate paths like "shop/contacts" and "blog/contacts" but not. I have that piece of html template: <div class="top-nav"> <ul class="cl-effect-1"> <li><a href="{% url 'gallery' %}">Main</a></li> <li><a href="{% url 'about' %}">Abour us</a></li> <li><a href="{% url 'blog' %}">Blog</a></li> <li><a href="{% url 'contacts' %}">Contacts</a></li> </ul> </div> and all I get is "shop/contacts" for the last part of menu. Should I make sure that all my urls have a bit of excess so I can't overlap them or I just have to make some settings so my applications have some priorities … -
For-looping three columns per row in Django template
I'm trying to retrieve data from the database and render it in rows of three columns. I've tried as many methods as I could find, finally it seemed to be rendering with this code: <div class='container'> <div class="row"> {% for category in categories %} {% if not forloop.counter0|divisibleby:"3" %} <div class="col-6 col-md-4"> <h3>{{category.category_name}}</h3> {% for page in category.page_set.all %} <p>{{page.page_title}}</p> {% endfor %} </div> {% else %} <div class="row"> <div class="col-6 col-md-4"> <h3>{{category.category_name}}</h3> {% for page in category.page_set.all %} <p>{{page.page_title}}</p> {% endfor %} </div> {% endif %} {% endfor %} </div> It renders the elements in three columns but the columns are not aligned, and when checking the HTML, the 'row' class is the same for all the rows (giving it an id and checking by CSS), so I guess there's something I'm doing wrong. I'd like to get an output like: Category1 - Category2 - Category3 Category4 - Category5 - Category6 With the 'page' objects of each category underneath. The data is rendering OK, the view is simple (just getting all the Category objects). I just need this kind of data rendering in different rows of 3 columns. I've tried the divisibleby method, but I guess I'm still missing … -
Uploading image with FastAPI cause exc.ResourceClosedError
I have an endpoint which saves uploaded image to it: @router.post("/v1/installation/{installation_uuid}/image") @db.create_connection async def upload_installation_image(installation_uuid: UUID, request: Request): content_type = request.headers["content-type"] async with db.transaction(): installation = await get_installation_by_uuid(installation_uuid) if not installation: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Installation {installation} not found") try: content = await request.body() image_uuid = await save_installation_image(installation.uuid, content, content_type) except Exception as e: log.debug(f"An error raised while uploading image: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Error while uploading image to db" ) return {"image_uuid": image_uuid} save_installation_image make simple insert into DB. In my tests I send 3 request to this endpoint. and all works fine: tests.py # upload image 1 data1 = b"\x01\x02\x03\x61\x05\x61" response = session.post( f"/v1/installation/{installation_uuid}/image", data=data1, headers={"content-type": "image/png"} ) # upload image 2 data2 = b"\x01\x02\x03\x61\x05\x62" response = session.post( f"/v1/installation/{installation_uuid}/image", data=data2, headers={"content-type": "image/png"} ) # upload image 3 data3 = b"\x01\x02\x03\x61\x05\x63" response = session.post( f"/v1/installation/{installation_uuid}/image", data=data3, headers={"content-type": "image/png"} ) But when FE start calling that request, each request after first one start failing with this error: Traceback (most recent call last): File "/opt/kelvatek/camlin-relink-broker/venv/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 404, in run_asgi result = await app( # type: ignore[func-returns-value] File "/opt/kelvatek/camlin-relink-broker/venv/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) File "/opt/kelvatek/camlin-relink-broker/venv/lib/python3.9/site-packages/uvicorn/middleware/message_logger.py", line 86, in __call__ raise exc from None File "/opt/kelvatek/camlin-relink-broker/venv/lib/python3.9/site-packages/uvicorn/middleware/message_logger.py", line 82, in __call__ … -
How can I hide or remove a sub-menu inside dropdown menu? I am new to python django
So, I found the below Django source code file on the internet. generic_subnavigation.html {% load common_tags %} {% load navigation_tags %} {% if link|common_get_type == "<class 'mayan.apps.navigation.classes.Menu'>" %} <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true"> {% if link.icon %}{{ link.icon.render }}{% endif %} {{ link.label }} <span class="caret"></span> </a> <ul class="dropdown-menu"> {% navigation_resolve_menu name=link.name as sub_menus_results %} {% for sub_menu_results in sub_menus_results %} {% for link_group in sub_menu_results.link_groups %} {% with '' as li_class_active %} {% with link_group.links as object_navigation_links %} {% include 'navigation/generic_navigation.html' %} {% endwith %} {% endwith %} {% endfor %} {% endfor %} </ul> </li> {% else %} {% if as_li %} <li class="{% if link.active and li_class_active %}{{ li_class_active }}{% endif %}"> {% endif %} {% include link_template|default:'navigation/generic_link_instance.html' %} {% if as_li %} </li> {% endif %} {% endif %} The code renders a webpage with sub-menus shown in the picture below; How do I remove the "setup and tools" menu in the sub-menus shown in the picture? At least comment on it out. generic_link_instances.html {% if link.separator %} <li role="separator" class="divider"></li> {% elif link.text_span %} <li class="text-center link-text-span {{ link.html_extra_classes }}" >{{ link.text }}</li> {% else %} {% if link.disabled %} <a … -
Python cleaning text emoji-library django-error
I want to use the emoji library to replace emoji's in text, nothing fancy. conn = create_connection(database) cur1 = conn.cursor() cur2 = conn.cursor() sql_select = """SELECT msg_id, MessageClean FROM Tbl_RawDataPART where MessageClean <> ''""" count = 0 for row in cur1.execute(sql_select): count += 1 (msg_id, original_message,) = row # extracting all emoji's message_without_emoji = emoji.demojize(original_message) When I run this code I get an error. I can't figure out why and how to correct this (never used django). django.core.exceptions.ImproperlyConfigured: Requested setting EMOJI_IMG_TAG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
how can I use multi functions in one page without change the URL using Django?
I'm trying to use Django to build my yt-dlp app, I want to create one page with had toggle list or multi buttons, when I use the first action on the toggle list or button the yt-dlp will download the video file or best quality the video, and when I use the second action the yt-dlp will download the audio file, I tried this #views.py from django.shortcuts import render, redirect from yt_dlp import YoutubeDL def hq(request): if request.method == 'POST': URLS = request.POST['HQ'] # to input a url by the user opt = { 'format' : 'bestvideo/best' } with YoutubeDL(opt) as ydl: # with used to put ydl_opts and apply changes ydl.download(URLS) # to start downloading # print('Successfully downloaded') return render(request, 'video.html') # Create your views here. def ad(request): if request.method == 'POST': URLS = request.POST['audio'] # to input a url by the user opt = { 'format': 'bestaudio/best', } with YoutubeDL(opt) as ydl: # with used to put ydl_opts and apply changes ydl.download(URLS) # to start downloading # print('Successfully downloaded') return render(request, 'audio.html') # Create your views here. def list(request): return render(request, 'list.html') #list.html {% extends 'base.html' %} {% block title %} list {% endblock title %} {% block … -
Django raised 'django.utils.datastructures.MultiValueDictKeyError: 'image'' at uploading image
I was trying to upload an image via a form, but django raised "django.utils.datastructures.MultiValueDictKeyError: 'image'" in line 106, views.py. I don't know what's happening, and why is throwing me an error when I submit via a custom form, but it does not happen via admin interface. Can anybody help? My code: models.py: class listings(models.Model): is_sold = models.BooleanField( default=False, verbose_name="Is Sold") title = models.CharField(max_length=100) description = models.TextField(max_length=750) price = models.FloatField() user = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.IntegerField(default=0, choices=categoryChoices) image = models.ImageField(upload_to='uploads/', blank='True', null='True') time_posted = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-time_posted',) def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def __str__(self): return f"{self.id}: {self.title}" views.py: def add_auction(request): if request.method == "POST": title = request.POST["title"] description = request.POST["description"] price = request.POST["price"] image = request.POST["image"] category = request.POST["category"] user = request.user listing = listings(title=title, description=description, price=price, image=image, category=category, user=user) try: listing.save() except ValueError: return render(request, "auctions/add_auction.html", { "message": "Error adding auction." }) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/add_auction.html") template: <h1>Add Listing</h1> <form action="{% url 'add_auction' %}" method="POST"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" name="title" placeholder="Title"> </div> <div class="form-group"> <label for="description">Description</label> <textarea class="form-control" id="description" name="description" rows="3"></textarea> </div> <div class="form-group"> <label for="price">Price</label> <input type="float" class="form-control" id="price" name="price" placeholder="Price"> </div> <div class="form-group"> … -
Whats the process for taking a python function and transferring it to Django output?
I'm experimenting with Django, and had a few questions about how python functions are translated into Django outputs. Firstly, is it correct to use Http Responses to generate Django ouptut from python functions? For example, if I have a Hello world function that returns the string Hello world, is it as simple as creating another function within my views.py, and simply return an Http response of HelloWorld()? Is there a different way in which developers conduct this transition from python function to Django? Thanks. def HelloWorld(): return "Hello World" def test(request): return HttpResponse(HelloWorld()) -
Access denied for files uploaded to digital ocean private folder after I added the custom domain
access denied for files uploaded to private folder after I added the custom domain. If I included custom_domain=False then it works but the access goes to digitalocean and not custom domain. Is it possible to use access private file using custom domain? class PrivateMediaStorage(S3Boto3Storage): location = 'private' default_acl = 'private' file_overwrite = False custom_domain = False