Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create a modified table in python to download from django site
I have a django website with a database. On the site, you can add, change, delete information from the database. I made a button that, when clicked, downloads a .csv file. I open it in excel and it looks something like this: The data set does not matter, I have a different one, I took this one on the Internet for an example. I want that when I click on the "download report" button, I would create a table at least like in this example: Is it possible? At the moment, my views.py contains the following code to get data from the database and download it to an excel spreadsheet: def export_racks_view(request, id): response = HttpResponse(content_type='text/csv') response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response, delimiter=';', dialect='excel') writer.writerow([ 'Rack number', 'Name', 'Amount', 'Vendor', 'Model', 'Describe', 'numbering', 'responsible', 'financially responsible person', 'inventory number', 'row', 'place', 'height', 'width', 'depth', 'unit width', 'unit depth', 'rack type', 'place type', 'max load', 'power sockets', 'power sockets UPS', 'external ups', 'cooler', 'updated by', 'updated at', 'room name', 'building name', 'site name', 'department name', 'region name', ]) raw_report = Rack.objects.raw("""select rack.id as id, rack.rack_name, rack.rack_amount, rack.rack_vendor, rack.rack_model, rack.rack_description, rack.numbering_from_bottom_to_top, rack.responsible, rack.rack_financially_responsible_person, rack.rack_inventory_number, rack.row, rack.place, rack.rack_height, rack.rack_width, rack.rack_depth, rack.rack_unit_width, rack.rack_unit_depth, rack.rack_type, rack.rack_place_type, rack.max_load, … -
Django using same APIView for both logged in and non logged in users
How can we use the same Django rest APIView for both logged in and logged out (Public) users. If the authentication token is passed, the view should be able to give the request.user and if the authentication token is not passed, the request.user can be anonymous. Please let me know if this is possible or not? I tried to remove authentication_classes = [] permission_classes = [] from the view, but by default the authentication is applied for all the users. -
How can I get python to understand my commands such as python manage.py shell. Error code: python bash: command not found
What are the details of your problem? I am trying to run the command python manage.py shell. I am in the directory that has manage.py but python is acting like I don't have the file or the command ability for shell. I am using visual studio code and I ran the echo$PATH command and got this output: /Users/andrewstribling/Desktop/mike_mysite/project_env/bin:/Users/andrewstribling/anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/andrewstribling/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin i had installed anaconda but went back to visual studio code. is this tied to it? Also, my director has my project env folder inside of my project folder. What did you try and what were you expecting? I have tried deleting the project_env folder for my enviornment and creating another one. I have reached out to the discord community for django and have not gotten a response. I looked up venv errors on stack overflow and I am not understanding the Path Variable really is or how to change it. I have read stack over flow articles but I do not believe their situation applies to me. https://python.land/virtual-environments/virtualenv#How_a_Python_venv_works I expect that there is a way to change how my project is seeing this. -
How to solve Django Rest API Import "drf_yasg" could not be resolved
from drf_yasg.views import get_schema_view from drf_yasg import openapi In the settings.py file, I add 'drf_yasg', Im Using the Vscode... Here I'm trying to add Swagger but I got an unexpected problem Import "drf_yasg.views" could not be resolved Screenshot Image -
Django ImportError at /user/login d doesn't look like a module path
I am trying to create a simple login page using th LoginView from django.contrib.auth. Whenever I try to login a user a receive the following error: ImportError at /user/login d doesn't look like a module path This is my code for activating the view in the url: from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path("register", views.register_request, name="register"), path("login", auth_views.LoginView.as_view(template_name="user/login.html"), name="login"), path("logout", auth_views.LogoutView.as_view(template_name="user/logout.html"), name="logout") ] This is my html file user.login.html: {% extends "base/base.html" %} {% load crispy_forms_filters %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" > {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small><br> <small class="text-muted"> <a href="/">Forgot password?</a> </small> </div> </div> {% endblock content %} #Just as a comment, the logout view works perfectly fine, the error jusr occurs when I hit submit in the login.html. I have tried adding these lines to the settings.py fileÑ AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend' ) LOGIN_URL = 'user/login' -
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Django-rest-auth
I'm doing the Django password reset but this error always happens and I don't know why Here are the urls: from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('login/', views.login, name="login"), path('registrar/', views.registrar, name="registrar"), path('logout/', views.logout, name="logout"), path('reset/password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('reset/password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Here are my custom pages: my custom pages: And these are the project urls: 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('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), path('', include('home.urls')), path('turmas/', include('turmas.urls')), path('calendario/', include('calendario.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
I it possible to integrate python with CSS, Javascript, and HTML?
I have a frontend web application built with JavaScript, HTML, and CSS. I would like to incorporate the output of a Python script into my frontend without using a server or a full backend solution. The Python script is a simple neural network, and I want to display its output in the frontend, such as showing the result as a header or plotting a graph generated by the script. I have already tried printing the output to the console from the Python script, but I need assistance with transferring that output to the frontend. Is it possible to achieve this without a server? I am open to suggestions and starting with a simpler solution, like plotting a graph generated by the Python script in the frontend. I appreciate any guidance or code examples on how to accomplish this. Thank you! I have looked into Django but I feel as if that seems too complex and more server focused for the simple task I require. -
Why does the matching query does not exist error occur?
There is a model: class ProductRating(models.Model): class Meta: indexes = [ UniqueIndex(fields=['user', 'product']), ] user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) grade = models.BooleanField() created_time = models.DateTimeField(auto_now_add=True, verbose_name='created_time') I want to create a row in the database with a post request class PostRatingFromUser(generics.CreateAPIView): queryset = ProductRating.objects.all() permission_classes = [IsAdminOrAuthenticatedUser, ] serializer_class = ProductRatingSerializer def post(self, request, *args, **kwargs): rating_from_db = ProductRating.objects.get(product_id=kwargs['pk'], user=request.user) if rating_from_db: rating_from_db.grade = kwargs['grade'] rating_from_db.save() else: ProductRating.objects.create(product_id=kwargs['pk'], grade=kwargs['grade']).save() return Response(status=200) But before adding, I check if there is such a database, if there is, then I just change the value of 'grade' but it gives me an error: product.models.ProductRating.DoesNotExist: ProductRating matching query does not exist. -
In Django, how can I select an object from the database and pass the parameters not to the url, but in some other better way?
I'm new to Django, in a page i have a combobox which is populated by fields from a database (simply city names). I select an object from the database with parameters which I pass to the url. I know this isn't the cleanest approach and that there is a better way. Is there a better way to populate the combobox without passing database parameters to the url? Then passing the parameters in a different and better way. How could my code take a different approach? models.py from django.db import models class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name forms.py from .models import City class SelectCityForm(forms.Form): city = forms.ModelChoiceField(queryset=City.objects.all()) class Meta: model = City fields = ('name') views.py def city_detail(request): form = CitySelectForm() object = None if request.method == "POST": form = CitySelectForm(request.POST) if form.is_valid(): city_id = form.cleaned_data['city'] object = City.objects.get(id=city_id) context = {'form': form, 'object': object} return render(request, 'app1/home.html', context) home.html <form action="/url-to-city_detail-view/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> urls.py from django.urls import path, include from . import views from app1.views import index from app1 import views urlpatterns = [ path('', index, name='index'), #Aggiunto per combobox path('login/', views.sign_in, name='login'), path('logout/', views.sign_out, name='logout'), path('home/', views.home, … -
Django Error: Question matching query does not exist() Updating Questions and Choices to Primary Keys
I am currently attempting the official Django tutorial polls app. It has asked me to create questions for a poll app and than after that create answer choices. I made a mistake creating the questions and somehow made an empty query set which I believe set the primary key to 1 and 2 respectively for the blank questions. I went on to create questions 3, 4, and 5. I realized the blanks were there an I attempted to delete the two questions. After running the delete() command I removed them. I figured that the primary keys would be removed and everything would slide back into place. My question who invented python remained at pk=3. Now I am wondering what to do. Should I create answer choices off of primary key id 3 and run with it? Or should I find a way to reassign the answer choices. Well, I have asked the Django forums website and someone recommended to me that I run the command `[(q.id, q.question_text) for q in Question.objects.all()]' this command output: >>> [(q.id, q.question_text) for q in Question.objects.all()] [(3, 'Who invented python?'), (4, 'This question was changed by dot notation on the object.'), (5, 'Who invented Django?')] … -
django aggregate a list of dictionaries
I have this situation that I have a queryset with complex relation and i need this kind of data: filters: [{ colors: [{ 'black': '#000000' }, { 'white': '#111111' } ] }, { categories: [{ "Digital": [{ "mobile": [{ 'Apple': ['first_phone', 'second_phone'] }, {'Android': ['first_phone', 'second_phone']} ], }] }] } ] basically for categories its a 3 level children-parent situation. and the reason is i don't want to call my queryset multiple times since its a pretty heavy one. overall this is what i have in mind: queryset.aggregate( colors=ArrayAgg( {F('packs__colors__title'): F("packs__colors__hex_code")}, distinct=True, ), categories=ArrayAgg( { F('categories__title'): { F("categories__parent__title"): { F("categories__parent__parent__title") } } }, distinct=True,) ) for first level its working fine. but how can i make this kind of aggregations? -
Host the GOOGLE_CREDENTIALS on google cloud storage not working
What is the best way of accessing the GOOGLE_CREDENTIALS json file ? I tried hosting it on Google cloud storage and the link is public, but can't work in Django . I am using redner.com as my server. -
Error while signing up with Django (Backend) and Angular (Frontend)
I am encountering an error when trying to create a user from my Angular frontend using my Django backend. I have set up CORS in my backend to allow all origins (allow origin all), but I continue to receive the following errors When I send a POST request to the URL 'http://127.0.0.1:8000/api/users/', I get a "400 (Bad Request)" response in the console. If I remove the '/' from the URL and send the request to 'http://127.0.0.1:8000/api/users', I receive the following error: "Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/users' from origin 'http://localhost:4200/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request." I have already installed and configured the CORS package in my Django backend to allow access from all origins. Despite this, the error persists. Here are some additional details: Django version: v4.1.7 Angular version: v15 CORS configuration in my Django backend (code snippet): enter image description here I am stuck and unsure how to resolve this issue. Any help would be greatly appreciated. Thank you very much! -
Python & MimeTypes: Parsing Email Body & Data in a multipart email
I am working on a python script (with BeautifulSoup) that reads emails through a Gmail service account. I can successfully read through the mailparts for an email sent from Gmail and identify the "data" part to read through and find a keyword in the text or HTML. However, I am having issues reading through any email sent from an apple device. I assume I will encounter other email clients issues too. I'm wondering how apple mail clients structure their email parts. Ultimately, I must find the "data" part in the body of the email. Here is the portion fo the script causing my issue: def parse_parts(self, part): mimeType = part['mimeType'] body = "" if mimeType == "text/plain" or mimeType == "text/html": data = part['body']["data"] data = data.replace("-","+").replace("_","/") decoded_data = base64.b64decode(data) soup = BeautifulSoup(decoded_data , "lxml") body = soup.get_text() return body -
Why is my console shows the coding of my html file?
I was able to use the quantity increment but i accidentally undo my work and it turns out like this someone help me please >:( the console print out my base.html coding and does not increase the quantity (base.html) <!DOCTYPE html> <html lang="en"> {% load static %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script> <title>Python World</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> nav{ background-color: white; } .one-edge-shadow { box-shadow: 0 8px 2px -5px rgb(246, 245, 245); } .display-8{ font-weight: 200; font-size: 30px; } .badge { padding-left: 9px; padding-right: 9px; -webkit-border-radius: 9px; -moz-border-radius: 9px; border-radius: 9px; } .label-warning[href], .badge-warning[href] { background-color: #c67605; } #lblCartCount { font-size: 15px; background: #ff0000; color: #fff; padding: 0 5px; vertical-align: top; margin-left: -17px; } .btn-circle.btn-sm { width: 25px; height: 25px; padding: 7px; border-radius: 14px; font-size: 12px; text-align: center; font-weight: bold; } </style> <script> function cartpage() { window.location.href="{% url 'cartpage' %}" } </script> </head> <body> <!-- navbar --> <nav class="one-edge-shadow sticky-top navbar navbar-expand-lg navbar navbar-dark bg-primary"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul … -
How to best model a tree of generic content types in Django?
I have a Django API for managing a bunch of content related to D&D campaigns: characters, locations, factions, quests, etc. Until now the frontend has always displayed these types of content in their own tabs, so a list of characters, another list of locations, and within a tab content can be nested: locations can have sub-locations, but they are all in their own "silo". class Location(models.Model): name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255, blank=True) text = models.TextField(blank=True) icon = models.CharField(max_length=255, default="map-location-dot") parent = models.ForeignKey("self", on_delete=models.SET_NULL, blank=True, null=True) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) I am thinking about turning the frontend into one nested tree of all content types: so a location could have nested factions, which could have nested characters, and so on, totally free-form. I'm not really sure how to best model this in the database. One idea I have is to create a brand new model that contains the tree, with generic relations to content items via the contenttypes framework from Django. class Tree(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") parent_content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) parent_object_id = models.PositiveIntegerField(null=True) parent_content_object = GenericForeignKey("content_type", "object_id") order = models.PositiveIntegerField() campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) That would work (although I … -
Cannot add <Image> instance is on database "default", value is on database "None"
I'm developing and app in Django, and I'm getting this error when my form y submitted, the problem is given when it try to add images on the relationship ManyToMany. Internal Server Error: /publish_offer/ Traceback (most recent call last): File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Projects\revenue\management\views.py", line 49, in publish_offer oferta.imagenes.add(*imgs) File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1137, in add self._add_items( File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1397, in _add_items target_ids = self._get_target_ids(target_field_name, objs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1313, in _get_target_ids raise ValueError( ValueError: Cannot add "<ImagenesOferta: ImagenesOferta object (None)>": instance is on database "default", value is on database "None" [29/Jun/2023 16:10:20] "POST /publish_offer/ HTTP/1.1" 500 87580 This is my models: class ImagenesOferta(models.Model): imagen = models.ImageField(verbose_name='Imagen Oferta', blank=False, null=False, upload_to='img_ofertas/') class Meta: verbose_name = 'Imagen de Oferta' verbose_name_plural = 'Imagenes de Ofertas' ordering = ['-id'] class Oferta(models.Model): titulo = models.CharField(verbose_name='Título', max_length=100, null=False, blank=False) descripcion = models.TextField(verbose_name='Descripción', null=True, blank=True) cantidad = models.PositiveSmallIntegerField(verbose_name='Cantidad', null=False, blank=False, default=1) valor = models.DecimalField(verbose_name='Valor', max_digits=4, decimal_places=2, null=False, blank=False) material = models.CharField(verbose_name='Material', max_length=20, null=False, blank=False, choices=MATERIAL_CHOICES) imagenes = models.ManyToManyField(ImagenesOferta, verbose_name='Imagenes de la Oferta', blank=True) usuario = … -
How to access WSGIRequest multiple times?
I have an APIView that calls another APIView for check purpose, But after hours of searching I know now that it's not easy to access HttpRequest after turn into stream object and will cause the below error: django.http.request.RawPostDataException: You cannot access body after reading from request's data stream some are suggest to use request.data not request.body but I can't do it in such case: B.views.py from rest_framework import views from rest_framework.response import Response from A.views import A class B(views.APIView): def post(self, request, *args, **kwargs): http_response = A.as_view()(request._request) # So far so good, but if I want to access request.data after calling A.as_view() will raise # the exception. return Response(http_response.data) How to deal with this issue? source: issue2774 -
create constance django from model list
I need to implement functionality when only one user of users Model can has 'editor-role' I will use this constant in my drf api. So I need to create some django constant with one user id, and dropdown menu of all users in my django admin panel. How can I do it? I choose django-constant, but faced with the problem that list of model data couldn't init in settings py: CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_ADDITIONAL_FIELDS = { 'users_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': ( (None, "-----"), User.objects.all().split(",")) ) }], } CONSTANCE_CONFIG = { 'DEFAULT_USER': ('', 'default user', 'users_select'), } Any another ideas how to implement this functionality? -
Django hide media files link for certain people
I programmed a function where you can download a file from the media folder with the media files depending on the link. The problem is that if you change the path in the link you have access to all the media files and not just the ones you are supposed to download. Can I somehow ban the other links (with a permission or something) or is there a clever way to solve the whole thing? -
Is `pytz` deprecated now or in the future in Python?
pytz is used in the Django version: <=3.2 doc Selecting the current time zone as shown below: import pytz # Here from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) But, zoneinfo is used instead of pytz in the Django version: 4.0<= doc Selecting the current time zone as shown below: import zoneinfo # Here from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(zoneinfo.ZoneInfo(tzname)) else: timezone.deactivate() return self.get_response(request) My questions: Is pytz deprecated now or in the future in Python? Why isn't pytz used in the Django version: 4.0<= doc Selecting the current time zone? -
Django form saves only the last row, times the number of records in the form
I have a form which saves data. The problem is, only the last row of the form gets saved, multiplied by the number of records that appear in the form. I have a feeling that only the last data row is being passed, and it is being looped through. However, for the life of me, I just cannot figure this out. Thanks in advance for help. Here is the relevant code: Model: class MonthlySheet(models.Model): employeename = models.ForeignKey(Employees, on_delete=models.CASCADE, related_name='monthlysheets') uan = models.CharField(max_length=12) ip = models.CharField(max_length=15) epfowages = models.IntegerField() esicwages = models.IntegerField() twelve_percent = models.IntegerField() eight_three_three_percent = models.IntegerField() difference = models.IntegerField() working_days = models.IntegerField() ncp = models.IntegerField() zero_point_seven_five_percent = models.IntegerField() Form: class MonthlySheetForm(forms.Form): print("Starting monthlysheetform class validation") employeename_id = forms.IntegerField(required=True) establishmentid = forms.IntegerField(required=True) uan=forms.CharField(required=True) ip=forms.CharField(required=True) epfowages = forms.IntegerField(required=True) esicwages = forms.IntegerField(required=True) twelve_percent = forms.IntegerField(required=True) eight_three_three_percent = forms.IntegerField(required=True) difference = forms.IntegerField(required=True) working_days = forms.IntegerField(required=True) ncp = forms.IntegerField(required=True) zero_point_seven_five_percent = forms.IntegerField(required=True) def clean(self): print("Cleanse starting in MonthlySheetForm") cleaned_data = super().clean() epfowages = cleaned_data.get('epfowages') esicwages = cleaned_data.get('esicwages') establishmentid = cleaned_data.get('establishmentid') employeename_id = cleaned_data.get('employeename_id') return cleaned_data View: def add_monthlysheet(request): assert isinstance(request, HttpRequest) establishments = Establishment.objects.all() employees = [] establishmentname = request.session.get('establishmentname', '') establishment_id = '' # Set initial value for establishment_id monthlysheet = MonthlySheet.objects.all() if … -
What is the best way to save comma separated keywords posted from client side into database table using Django?
I have a text area input on a simple HTML page, where I am posting comma-separated keywords to save into my database table. For example, Keywords input is like: keyword1,keyword2,keyword3, ... I am using Django 3.2 and Tastypie as a API framework. Here is my Django model: class Keywords(models.Model): keyword = models.CharField(max_length=200, unique=True) class Meta: db_table = 'keywords' And Tastypie resource: class KeywordResource(ModelResource): class Meta(CommonMeta): queryset = Keywords.objects.all() resource_name = 'keyword-resource' filtering = {'id': ALL, 'keyword': ALL} allowed_methods = ['get', 'post', 'put', 'patch'] I want to save the comma-separated keyword in one post request from the client side. How can I post comma-separated keywords and insert them one by one into the table Keywords? Also, what would be the best way to use save() method from model or hydrate() method from tastypie resource to prepare the data to save? -
Django don't manually change the URL and go to the index.html page
I am new to Django. Let's assume my project name is mysite, and I have one app called Polls. I have 2 html in the templates file: "index.html", "df.html" Now, when I runserver, I have to manually change the URL, add "polls" after "http://127.0.0.1:8000/" to show the index.html, but I want when I click the link in the terminal, it can direct me to the index.html. I don't need to manually change the URL Thank you and any help if really appreciated! views.py def index(request): xxxx return render (request,"index.html") polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] mysite\urls.py from django.contrib import admin from django.urls import include, path from polls import views urlpatterns = [ path('polls/', include('polls.urls')), path('df/', views.df_show) ] -
Simple html form in Django
Could you please help me, I don't understand why html+css don't work as expected in Django. I use a simple form to upload two files, but it looks really ugly. index.html without id="upload_container" <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_1"> <button type="submit">Upload File 1</button> </form> <form method="POST" enctype="multipart/form-data" class="upload2"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_2"> <button type="submit">Upload File 2</button> </form> </div> </div> index.html with id="upload_container" <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1" id="upload_container"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_1"> <button type="submit">Upload File 1</button> </form> <form method="POST" enctype="multipart/form-data" class="upload2" id="upload_container"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_2"> <button type="submit">Upload File 2</button> </form> </div> </div> How I can fix it? I mean get Browse... button, but with css style.