Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django file displays the contents of a database outside the dropdown menu
I have a delete employee page in my Django project where I get all the names of the employees in the dropdown menu from the database. the main issue is when I run the code the content which is supposed to be shown inside the dropdown menu is shown ouside. the code is as below: ''' {% extends 'app/base.html' %} {% block para %} <title>delete employee</title> <body style="background-color:powderblue;"></body> <style type="text/css"> label{ width: 200px; display: inline-block; margin: 4px; text-align: left; font-weight:bold; } input{ width: 200px; display: inline-block; margin: 4px; text-align: left; border-radius: 10px; } select{ width: 200px; display: inline-block; margin: 4px; text-align: left; border-radius: 10px; } form{ border-radius: 10px; background: rgb(155, 206, 219) ; color: white; width: 450px; padding: 4px; margin:auto; } </style> <form action="" > <h3 class="text-center text-uppercase"style="color:black; font-weight:bold">delete-employee</h3> {% csrf_token %} <label for="" class="text-uppercase">select:</label> {% for emp in emps %} <option value="ceo" class="text-uppercase">{{emp.name}}</option> {% endfor %} <select name="designation" id="designation"> <option value="associates" selected class="text-uppercase">name</option> </select><br><br> <div class="container"> <input type="submit" value="submit" class="text-uppercase text-center"> </div> </form> </div> {% endblock para %}''' -
Python Django or Flask for web development?
I have intermediate Python skills and want to learn web development. Should I start with Django or Flask? When I search for answers I only see benefits or downsides of them, but not anyone saying which one is better. And since I don't have any experience, I cant decide. I know it always comes down to what you want to create etc. But what would you say, is better overall? Is it possible to answer that question? -
how to utilize get_queryset with id parameter foreach particular foreign key items in class based views?
first of all, I am very new to django and thank you for patience, I want to make web site for showing how the league stands and shows the particular team footballer here what I have done so far... models.py class League(models.Model): name = models.CharField(max_length=255) country = models.CharField(max_length=255) founded = models.DateField() def __str__(self): return self.name class Team(models.Model): league = models.ForeignKey( League, blank=True, null=True, on_delete=models.CASCADE) image = models.ImageField( upload_to="images/", default='images/Wolves.png', blank=True, null=True) name = models.CharField(max_length=255) win = models.IntegerField(blank=True, null=True) draw = models.IntegerField(blank=True, null=True) loss = models.IntegerField(blank=True, null=True) scored = models.IntegerField(blank=True, null=True) conceded = models.IntegerField(blank=True, null=True) founded = models.DateField(blank=True, null=True) games = models.IntegerField(blank=True, null=True) point = models.IntegerField(blank=True, null=True) average = models.IntegerField(blank=True, null=True) class Meta: ordering = [ '-point', '-average' ] def __str__(self): return self.name def save(self, *args, **kwargs): self.games = self.win + self.draw + self.loss self.point = self.win*3 + self.draw self.average = self.scored - self.conceded super(Team, self).save(*args, **kwargs) it would be great if I utilize from slug item instead of id To make easy understand of which league you are in urls.py urlpatterns = [ path('', home, name='home'), path(r'^/league/(?P<id>\d+)/$', LeagueListView.as_view(), name='league'), In order to learn what class based views is I should use them somehow once clicked in th base.html 's navbar, … -
'Python.h' file not found on virtualenv in macOS
I use macOS Monterey 12.4 as my OS, and I'm trying to install django inside of a virtual environment created with pipenv. If I run the command pipenv shell to create a new virtualenv, then pipenv install django, I get this output: Installing django... Error: An error occurred while installing django! Error text: Collecting django Using cached Django-4.1.1-py3-none-any.whl (8.1 MB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.3-py3-none-any.whl (42 kB) Collecting backports.zoneinfo Using cached backports.zoneinfo-0.2.1.tar.gz (74 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'done' Collecting asgiref<4,>=3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml): started Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' Failed to build backports.zoneinfo error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [43 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-arm64-cpython-38 creating build/lib.macosx-10.14-arm64-cpython-38/backports copying src/backports/__init__.py -> build/lib.macosx-10.14-arm64-cpython-38/backports creating build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py … -
Django and HTMX realtime for all users
Can I make a realtime data refreshing in all users pages without them refreshing the page, once the database is updated, Using HTMX only, without django channels or AJAX or Json???? -
django python: how to display multiple items from 1 categorie under 1 categorie name in html template
i am new to python django. this is my code. views.py def gerechten(request): template = loader.get_template('café/gerechten.html') mydata = gerecht_info.objects.all() mydata2 = gerechten_Categorie.objects.all() context = { 'mygerecht': mydata, 'mycategories': mydata2 } return HttpResponse(template.render(context, request)) and models.py class gerechten_Categorie(models.Model): categorie = models.CharField(max_length=200) def __str__(self): return self.categorie class gerecht_info(models.Model): categorie = models.ForeignKey(gerechten_Categorie, on_delete=models.CASCADE) gerecht_name = models.CharField(max_length=200) gerecht_description = models.CharField(max_length=500, blank=True, null=True) gerecht_price = models.CharField(max_length=50) def __str__(self): return self.gerecht_name def drinkdesc(self): return self.gerecht_description def drinkprice(self): return self.gerecht_price and gerechten.html {% if mygerecht %} {% for cat in mygerecht %} <div class="flex"> <div class="menu-head center"> <h2>{{cat.categorie}}</h2> </div> <div class="menu-item"> <ul class="price"> <li>{{cat.gerecht_name}}</li> <li>€{{cat.gerecht_price}}</li> </ul> {% if cat.gerecht_description %} <p>{{cat.gerecht_description}}</p> {% else %} <p></p> {% endif %} </div> </div> {% endfor %} {% else %} <div class="menu-head center"> <h2>no items avaible</h2> </div> {% endif %} my site now looks like this: image of my site https://i.stack.imgur.com/lrhhs.png but i want to make all the info from 'Hapjes' into 1 'Hapjes' categorie, not seperated. already thanks for taking your time to respond. kind regards subjoel -
flutter and stripe (setupIntents)
I know this library flutter_stripe, which to me seems to be very limited in stripe interactions, it only does paymentIntent creation and that is basically it. Please do argue if I am wrong. I am looking forward to see if there are other packages, if any, for flutter to interact with stripe in more depth, I am trying to avoid Android/IOS native languages. I do these in backend: create stripe customer, create setup intent for each customer as they try or either add bank card or make purchase. I am looking forward that client will interact to stripe for the following: 1 Confirm setup intents 2 Send card data to stripe Another question, could you please assess my payment flow? If it is faulty please recommend another way Once setupintent is confirmed for the user, they hit backend for whatever purchase they want to make, backend contacts Stripe, fetches the setupintent, creates and confirms the paymentintent. Thank you, I appreciate help. -
How to pass a value in a Django drop down from a ModelForm
I want to display different fonts for users from a drop-down. The drop-down derives its values from the model which has choices option. The problem is when a certain font is chosen, it saves well in the database but the “value” is not caught. Here is the flow of the project: Model: class Company(models.Model): name = models.CharField(max_length=100, null=True, blank=True first_font = models.CharField(max_length=100, choices=header_font, blank=True, null=True) second_font = models.CharField(max_length=100, choices=body_font, blank=True, null=True) class Meta: verbose_name_plural = "Companies" def __str__(self): return self.name Forms.py class CompanyForm(forms.ModelForm): def __init__(self, *args, user=None, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.fields['first_font'].widget.attrs = {'class': 'select',} self.fields['second_font'].widget.attrs = {'class': 'select',} class Meta: model = Company fields = ('first_font', 'second_font',) Template output: I have used HTMX to take the value of the drop-down and pass it to a partial template so that it can be inserted in a class and return a well-formatted sentence with the font applied. <form action="" method="POST" enctype="multipart/form-data"> <div class="column is-4"> <h2>Choose fonts for documents</h2> <div class="field"> <label class="label">Heading Font</label> <div class="select is-fullwidth" name = "heading_font" hx-get="{% url 'main_font' %}" hx-target="#main-font" hx-trigger="change" > {{ form.first_font }} </div> <div id="main-font"> <p>This is your font</p> </div> </div> <div class="field"> <label class="label">Body Font</label> <div class="select is-fullwidth" name = "body_font" hx-get="{% url … -
How can I Filter Two Models at Once using Date Range in Django with Forms and Count
I am working on a Django project and I want to query two different Models; Income and Expenditure using Date Range with Django Forms. I can query one Model at once but don't know how I can query both the Income and Expenditure table at the same time and as well count number of objects in both Models. Below are my Models: class Expenditure(models.Model): description = models.CharField(max_length=100, null=False) source = models.CharField(max_length=100, choices=CATEGORY_EXPENSES, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) amount = models.PositiveIntegerField(null=False) Remarks = models.CharField(max_length=120, null=True) date = models.DateField(auto_now_add=False, auto_now=False, null=False) addedDate = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Expenses' def __str__(self): return self.description class Income(models.Model): description = models.CharField(max_length=100, null=False) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) amount = models.PositiveIntegerField(null=False) remarks = models.CharField(max_length=120, null=True) date = models.DateField(auto_now_add=False, auto_now=False, null=False) addedDate = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Income Sources' def __str__(self): return self.description My Django forms as in forms.py: class IncomeSearchForm(forms.ModelForm): start_date = forms.DateField(required=True, widget = IncomeDateField) end_date = forms.DateField(required=True, widget = IncomeDateField) class Meta: model = Income fields = ['start_date', 'end_date'] My views.py where I am able to use Date Range with Search form to query Income Model for Date Range Report. def SearchIncomeRange(request): #check for user session if 'user' not in request.session: return … -
I cant click on image url in Django
So I wanted to have this logo in the blog app, which was going to be part of each page, so users can always click on it, and ideally, when they click on it, it shall lead them to a page with articles. So this the code that I written in base file, but for some reason its not clickable: base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Articles</title> <link rel="stylesheet" href="{% static 'styles.css' %}" > </head> <body> <div class = "wrapper"> <h1><a href = "{% url 'articles:list' %}"> </a><img src="{% static 'article.png' %}"/> </h1> {% block content %} {% endblock %} </div> </body> </html> Any suggestions how to fix it? -
Retun data from a Django view after a javascript AJAX POST request
I am using Javascript to send an asynchronous request to a Django View. The View is able to receive data from the POST request, but I can't seem to return a message to confirm that everything worked. I was expecting that xhttp.responseText would contain the message Thankyou, but it is empty. The html part looks like this: <textarea id="message"></textarea> <input type="submit" value="Send" id="send_button onclick="submit_message()"/> The javascript looks like this: function submit_message(){ document.getElementById("send_button").value="Sent - Thankyou!"; message = document.getElementById("message").value var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/send-message"); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("csrfmiddlewaretoken={{ csrf_token }}&message="+message); console.log('Sent POST request') console.log(xhttp.responseText) } I was hoping that xhttp.responseText would print Thankyou to the console. The Django View function looks like this: def send_message(request): message = request.POST.get('message') print(message) return HttpResponse('Thankyou') The message variable prints out as expected, but Thankyou doesn't seem to be returned. I am doing AJAX with JS for the first time, so I expect I've just misunderstood something simple. -
Automate raising ImproperlyConfigure if environment variable is missing
I have the following code in one of my views.py: tl_key = os.getenv("TRANSLOADIT_KEY") tl_secret = os.getenv("TRANSLOADIT_SECRET") if not tl_key: logger.critical("TRANSLOADIT_KEY not set") raise ImproperlyConfigured if not tl_secret: logger.critical("TRANSLOADIT_SECRET not set") raise ImproperlyConfigured I know that if Django doesn't find SECRET_KEY or DEBUG environment variable, it will raise ImproperlyConfigured exception. Is there a way I can specify which env variables are required so that the said exception is raised automatically? -
How to pass form field without filling in Django? And add extra field to for answer?
I wanna make patient information register form. I did model.py and form.py but, when i come to use, i couldn't pass the form without filling. Forexample, in this image evlilik tarihi means marriage date, evlilik tarihi 2 means second marriage date, when i filling the form i want to leave empty the evlilik tarihi 2 field. But always i took this error "TypeError: init() got an unexpected keyword argument 'blank'" I used null=True, blank=True, but nothing. How can i pass the form field without filling. And second question is, i made three form field for multiple marriage but is there any way how can i add button to this marriage field, and someone had second or third marriage, he can easily add button and give marriage date to me. How can i do this? Form.py class HastaBilgiForm(forms.ModelForm): class Meta: model = HastaBilgi fields = '__all__' widgets = { 'hasta_ad_soyad' : forms.TextInput(attrs={'class': 'form-control'}), 'hasta_dogum_tarihi' : forms.TextInput(attrs={'class': 'form-control'}), 'hasta_dogum_yeri' : forms.TextInput(attrs={'class': 'form-control'}), 'evlilik_tarihi_1' : forms.TextInput(attrs={'class': 'form-control'}), 'evlilik_tarihi_2' : forms.TextInput(attrs={'class': 'form-control'}), 'evlilik_tarihi_3' : forms.TextInput(attrs={'class': 'form-control'}), 'bosanma_tarihi_1' : forms.TextInput(attrs={'class': 'form-control'}), 'bosanma_tarihi_2' : forms.TextInput(attrs={'class': 'form-control'}), 'bosanma_tarihi_3' : forms.TextInput(attrs={'class': 'form-control'}), 'ogrenim_durumu' : forms.Select(choices=choices2, attrs={'class': 'form-control'}), 'meslek' : forms.TextInput(attrs={'class': 'form-control'}), 'kan_grubu' : forms.Select(choices=choices1, attrs={'class': 'form-control'}), 'boy' : … -
Django export-import use both ExportActionModelAdmin and ExportMixin together
In admin.py, using either: from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportActionModelAdmin, admin.ModelAdmin): # stuff or from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportMixin, admin.ModelAdmin): # stuff works well, but I'm not able to have both together: from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportActionModelAdmin, ExportMixin, admin.ModelAdmin): # stuff In this latter case, the top right 'Export' button is missing (but the drop-down menu is OK). How could I use both ExportActionModelAdmin and ExportMixin from import_export.admin in my admin classes in order to have both the drop-down menu for a fine grain selection, and the 'Export' button for exporting all the model in one click? Doc URL: https://django-import-export.readthedocs.io/en/latest/getting_started.html#exporting-data -
why I am getting 401 error while sending a post request to auth/users in android studio but same request works in browser? wrong with my request?
I have an API which allows post request to register new users. It works in browser but when I try making this post request in my android project.I get 401 unauthorized response, I don't know what is wrong with my request!? private static String makeHttpRequest(URL url, String info) throws IOException { String jsonResponse = ""; if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; OutputStream outputStream = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setDoOutput(true); //write to the stream outputStream = urlConnection.getOutputStream(); byte[] input = info.getBytes(Charset.forName("UTF-8")); outputStream.write(input, 0, input.length); urlConnection.connect(); //read the response if (urlConnection.getResponseCode() == 200) { authenticated = true; inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } return jsonResponse; } -
Fetch Nested Data Using Ajax
I am having difficulties in fetching data which leads the output in this "[object Object]" Here is the sample data that I am fetching: { "id": 1, "logs": [ { "id": 1, "login_time": "2022-09-24T08:43:48.988768Z", "logout_time": "2022-09-24T08:43:48.988768Z", "work_hours": 0, "user": 1 }, { "id": 2, "login_time": "2022-09-24T10:24:59.564850Z", "logout_time": "2022-09-24T10:24:59.564850Z", "work_hours": 0, "user": 1 } ] } And here is the AJAX Code that I am using: function userlist(){ var wrapper = document.getElementById(`userlist`) var url = 'http://127.0.0.1:8000/userapi/' fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data) var list = data for (var i in list){ var item = ` <div id="data-row-${i}"> ${list[i].logs} </div> ` wrapper.innerHTML += item } }) } -
Online registration form with Django/Python
I need to create an online registration form. with the possibility of recording at your leisure, (with an interval of 1 hour), for example, recording at 12, then automatically close the possibility (selection) of recording from 12:00 to 13:00. at the same time, it is necessary to give the opportunity to sign up only for free hours. Please, recommend how to implement this problem in Django/Python -
Watail is not showing features for RichTextField in wagtail admin page edit form
wagtail RichTextField is not showing the features I gave (bold, italic, etc..) on the wagtail admin page edit. How can I add that? am I missing something? I also tried with admin.FieldPnale("banner_subtitle") which also did not work for me. HomePage class HomePage(Page): template = "home/home_page.html" banner_title = models.CharField(max_length=100, blank=False, null=True) max_count = 1 banner_subtitle = RichTextField(features=['bold', 'italic']) banner_image = models.ForeignKey( to="wagtailimages.Image", null=True, blank=False, on_delete=models.SET_NULL, related_name="+" ) banner_cta = models.ForeignKey( to="wagtailcore.Page", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) content_panels = Page.content_panels + [ FieldPanel("banner_title"), FieldPanel("banner_subtitle"), ImageChooserPanel("banner_image"), PageChooserPanel("banner_cta"), ] pip freeze output anyascii==0.3.1 asgiref==3.5.2 beautifulsoup4==4.11.1 certifi==2022.9.14 charset-normalizer==2.1.1 Django==4.1.1 django-filter==22.1 django-modelcluster==6.0 django-permissionedforms==0.1 django-taggit==3.0.0 django-treebeard==4.5.1 djangorestframework==3.14.0 draftjs-exporter==2.1.7 et-xmlfile==1.1.0 html5lib==1.1 idna==3.4 l18n==2021.3 openpyxl==3.0.10 Pillow==9.2.0 pytz==2022.2.1 requests==2.28.1 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.2 tablib==3.2.1 telepath==0.3 urllib3==1.26.12 wagtail==4.0.1 webencodings==0.5.1 Willow==1.4.1 xlrd==2.0.1 XlsxWriter==3.0.3 xlwt==1.3.0 wagtail admin edit page -
Django Amazon Ses E-mail address is not verified
i'm a django developer, I'm doing a project but I have a problem I have a recording section in my project that works when an approved user tries for an amazon ses account, but I get errors when unapproved users register how can I solve this https://prnt.sc/m0lZBh9Xtpo5 -
How to make user specific forms?
So I want to make it so a "Tutor" can select a "Student", now each tutor has a different set of Students so the drop down list needs to be unique. So this is the part of forms where question comes from, tutor1 get's passed through by response into views, then from views it needs to be passed into the form so Students.objects.all displays all of the students that tutor1 has. (The query set part is fine and I believe the Field is also correct) the part that doesn't work is passing in response or passing in the tutor1 into the form and so far I can't find anywhere how to do this. student = forms.ModelChoiceField(queryset = Students.objects.all(tutor=tutor1.id)) This is the last piece of the hard part of my website so I'd be so grateful if anyone knows how to fix this. -
how can I save docker's database data locally on my server?
I'm running an app inside a docker container. That app uses docker Postgres image to save data in a database. I need to keep a local copy of this database's data to avoid losing data if the container is removed or purged somehow ..so I am using volumes inside my `docker-compose.YAML file,, but still the local DB folder is always empty .. so whenever I move the container or purge it the data are lost docker-compose.yaml version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data ports: - '5433:5432' restart: always command: -p 5433 environment: - POSTGRES_DB=mydata - POSTGRES_USER=mydata - POSTGRES_PASSWORD=mydata@ - PGDATA=/tmp django-apache2: build: . container_name: rolla_django restart: always environment: - POSTGRES_DB=mydata - POSTGRES_USER=mydata - POSTGRES_PASSWORD=mydata@ - PGDATA=/tmp ports: - '4002:80' - '4003:443' volumes: - ./www/:/var/www/html - ./www/demo_app/static_files:/var/www/html/demo_app/static_files - ./www/demo_app/media:/var/www/html/demo_app/media # command: sh -c 'python manage.py migrate && python manage.py loaddata db_backkup.json && apache2ctl -D FOREGROUND' command: sh -c 'wait-for-it db:5433 -- python manage.py migrate && apache2ctl -D FOREGROUND' depends_on: - db as you can see i used ./data/db:/var/lib/postgresql/data , but locally the ./data/db directory is always empty !! -
Why this Javascript code is not working. Jquery already added in inter file. HTML and Javascript code below here. Django Project, Tailwind CSS
/** JavaScript Code **/ $(".changeQuantity").click(function (e) { e.preventDefault(); var product_id = $(this).closest(".product_data").find(".prod_id").val(); var product_qty = $(this).closest(".product_data").find(".qty_input").val(); var token = $('input[name="csrfmiddlewaretoken"]').val(); $.ajax({ method: "POST", url: "/update-cart", data: { product_id: product_id, product_qty: product_qty, csrfmiddlewaretoken: token, }, success: function (response) { console.log(response); alertify.success(response.status); }, }); }); /- ---"HTML CODE"--/ <span class="flex flex-row h-10 w-32 rounded-lg relative bg-transparent mt-1"> <button data-action="decrement" class=" changeQuantity text-gray-600 bg-gray-300 hover:text-gray-700 hover:bg-gray-400 h-full w-20 rounded-l cursor-pointer outline-none"> <span class="m-auto text-2xl font-thin">−</span> </button> <input type="text" class=" qty_input focus:outline-none text-center w-full font-semibold text-md md:text-basecursor-default flex items-center outline-none" name="custom-input-number" value="{{ item.product_qty }}"></input> <button data-action="increment" class=" changeQuantity bg-gray-300 text-gray-600 hover:text-gray-700 hover:bg-gray-400 h-full w-20 rounded-r cursor-pointer"> <span class="m-auto text-2xl font-thin">+</span> </button> </span> -
Want to download the file which was recently uploaded by user in django?
This is my models.py from django.db import models import os # Create your models here. class Fileupload(models.Model): file=models.FileField( upload_to='media') date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file def filename(self): return os.path.basename(self.file.name) This is my Views.py from msilib.schema import File from urllib import response from django.shortcuts import render,HttpResponse from .models import Fileupload from .encryptfile import encrypt # import required module import os from cryptography.fernet import Fernet # Django file encrytion process from https://pypi.org/project/django-encrypted-files/ # Import mimetypes module import mimetypes # def index(request): # return render(request, 'index.html') def base(request): if request.method == 'POST': file2 =request.FILES["file"] # name = request.FILES["file"].name # path = "media/"+name document = Fileupload.objects.create(file=file2) document.save() fname = Fileupload.filename(document) global path1 path1 ="media/"+fname # print(fname) #encrypting the uploaded file which is file2 # opening the key key = Fernet.generate_key() with open("thekey.key","wb") as thekey: thekey.write(key) # opening the original file to encrypt with open(path1, 'rb') as file: original = file2.read() # encrypting the file encrypted = Fernet(key).encrypt(original) # opening the file in write mode and # writing the encrypted data with open(path1, 'wb') as encrypted_file: encrypted_file.write(encrypted) return render(request,'download.html') else: return render(request, 'base.html') def download(request): # Define Django project base directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Define text file name # filename = Fileupload.filename() # … -
create tables according to the multiple schema from django model
How to create tables according to the multiple schema on a postgresql from model. However , I am not familiar with django. Can anyone point me in the right direction ? -
Resolving names of all Django related models when exporting a table to a text file (csv)
I have a simple Django (4.1/Python3.9) table with textual and numerical fields. In this table, four of these are ForeignKeys: 1 is referencing itself 1 is referencing an other table through a OneToMany relationship (aka simple ForeignKey) 2 are referencing 2 other tables through a ManyToMany relationship Django is kind enough, when using the model._meta.get_fields() method, to retrieve all related fields along with the usual fields of the model. And that's what I want. Within the admin page of that model, I can see all these related fields as "resolved", e.g. their name is displayed instead of their ids, this is because of the usual __str__(self) method we can use in the model classes: from django.db import models class Foo(models.Model): name = model.CharFields( max_length=100, unique=True, verbose_name="Foo name" ) # here are some other usual data fields self_relation = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True ) bar = models.ForeignKey( "Bar", on_delete=models.CASCADE, null=True, blank=True ) baz = models.ManyToManyField(Baz) qux = models.ManyToManyField(Qux) def __str__(self): return self.name class Bar(models.Model): name = model.CharFields( max_length=100, unique=True, verbose_name="Bar name" ) # ... def __str__(self): return self.name class Baz(models.Model): name = model.CharFields( max_length=100, unique=True, verbose_name="Baz name" ) # ... def __str__(self): return self.name class Qux(models.Model): name = model.CharFields( max_length=100, …