Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
submitting django crispy form with file field and some other text fields using fetch and then
I am trying to submit my crispy form using fetch and then methods to django backend. All my fields are submitting to the server. but files are shown as empty fields in the server. below, is my front end from {{ photo.media }} <form action="" method="post" class="form my-4 px-2" enctype="multipart/form-data" id="photo_form" onsubmit=""> {% csrf_token %} {{photo|crispy}} <input type="submit" value="Add" class="btn btn-primary btn-lg"> </form> Here is the ajax request I made <script> const photoForm = document.querySelector('#photo_form'); console.log(photoForm.values); photoForm.addEventListener('submit', (event) => { event.preventDefault(); const photoFormData = new FormData(photoForm); photoFormData.forEach((value, key) => { console.log(key + ': ' + value); }); fetch("{% url 'add_photo' %}", { method: 'POST', body: photoFormData, contentType: false, processData: false, }) .then((response) => response.json()) .then((data) => { console.log(data); if (data.result == 'success') { $('.modal-body').html('Form submission was successful!'); $('#modal-dialog').modal('show'); photoForm.reset(); } else { $('.modal-body').html('There was an error with the form submission.'); $('#modal-dialog').modal('show'); } }); }); </script> Below, is the model I Made class Photos(models.Model): photo_title = models.CharField(max_length=50, blank=False) photo_description = models.CharField(max_length=50, blank=False) photo_date = models.DateField(blank=False) photo_location = models.CharField(max_length=50, blank=False) photo_file = models.ImageField(upload_to='photos', blank=False) def __str__(self): return self.photo_title Below, is the view function """ ajax add photo event to home wall """ def add_photo(request): if request.method == 'POST': response_data = {} photoForm … -
obj.id printing loop of the ids, need to get only the recent/top one
It's a function inside the class ServiceReportCallbackAdmin(BaseAdmin):, I'm calling save_meta from another function, def save_meta(self,obj, form): print(obj.id) when i'm calling this function, i'm getting: 51 45 34 24 17 10 5 3 1 But i just want to get 51 only for further use, how can i do that? -
How to save or upload an image from LOCAL directory to ImageField of database object in DJANGO
i was trying to create some products in ecommerce project in django and i had the data file ready and just wanted to loop throw the data and save to the database with Product.objects.create(image='', ...) but i couldnt upload the images from local directory to database!!! i tried these ways: 1- first try: with open('IMAGE_PATH', 'rb') as f: image = f.read() Product.objects.create(image=image) didnt work!!! 2- second try: image = open('IMAGE_PATH', 'rb') Product.objects.create(image=image) 3- third try: module_dir = dir_path = os.path.dirname(os.path.realpath(__file__)) for p in products: file_path = os.path.join(module_dir, p['image']) Product.objects.create() product.image.save( file_path, File(open(file_path, 'rb')) ) product.save() -
How can I fix this error? json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
https://youtu.be/0iB5IPoTDts?t=4690 I am currently trying to like a product with my microservice per request. Here is the code from his video: https://github.com/scalablescripts/python-microservices This is my code: from flask import Flask, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from sqlalchemy import UniqueConstraint from dataclasses import dataclass import requests \#from markupsafe import escape \#from jinja2 import escape app = Flask(__name__) app.config\["SQLALCHEMY_DATABASE_URI"\] = 'mysql://root:root@db/main' CORS(app) db = SQLAlchemy(app) @dataclass class Product(db.Model): id: int title: str image: str id = db.Column(db.Integer, primary_key=True, autoincrement=False) title = db.Column(db.String(200)) image = db.Column(db.String(200)) @dataclass class ProductUser(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) product_id = db.Column(db.Integer) UniqueConstraint('user_id', 'product_id', name='user_product_unique') @app.route('/api/products') def index(): return jsonify(Product.query.all()) @app.route('/api/products/\<int:id\>/like', methods=\['POST'\]) def like(id): req = requests.get('http://host.docker.internal:8000/api/user') return jsonify(req.json()) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') The API user is called which creates a random user, see code: from django.contrib import admin from django.urls import path from .views import ProductViewSet, UserAPIView urlpatterns = [ path('products', ProductViewSet.as_view({ 'get': 'list', 'post': 'create' })), path('products/<str:pk>', ProductViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'delete': 'destroy' })), path('user', UserAPIView.as_view()) ] and this is the class that will be executed: class UserAPIView(APIView): def get(self, _): users = User.objects.all() user = random.choice(users) return Response({ 'id': user.id }) I get the following error … -
Javascript: how to get calculate multiple input values in loop using javascript?
I am trying to calculate the the value of some input field in my django template using javascipt (onkeyup=(), the form is in a loop e.g {% for p in prediction %} {% endfor %}. I have this simple line to grab the input values (NOTE: They are in a loop) let stake_amount_input = document.querySelector("#amount").value let shares_amount_input = document.querySelector("#shares").value Based on the fact that i have all these function in a django loop, am i not supposed to get all the input fields values when i calculate the other objects in the loop. Based on the fact that i have all these function in a django loop, am i not supposed to get all the odds when i console.log(odds) {% for p in prediction.prediction_data.all %} <form action="#" method="POST"> <input type="number" value="" name="amount" id="amount" class="shares" onkeyup="CalculateNewBalance()"> <input type="number" value="" name="shares" id="shares" class="shares" onkeyup="CalculateNewBalance()"> <script> function CalculateNewBalance(){ let stake_amount_input = document.querySelector(".amount").value let shares_amount_input = document.querySelector(".shares").value let potential_win = document.querySelector(".potential-win") let potential_win_value = parseFloat(stake_amount_input) * parseInt(shares_amount_input) potential_win.innerHTML = "$" + potential_win_value // if the potential_win innerHTML shows Nan, then i want to change the innerHTML to $0.00, but this is not working too if (potential_win === isNan) { potential_win.innerHTML = "$0.00" } </script> … -
How to use dumpdata and loaddata for Django Groups with some permissions?
While writing testcases, I required fixtures or we can say json data to pre-populate database. I have a project which is using Django Groups and Permissions models. Now, when I use command for dump data python manage.py dumpdata auth.Groups > fixtures/groups.json It will dump all data in groups.json file as show below. Note: groups are added on the fly means when a specific registration form is triggered, it will create specific group and also add related related permissions in that group which i have defiend in code. But if group is already created, it will not try to create it again just simply assign that group to user. Here, permissions are listed accourding to their id's. Note: Some permissions are defaults and others are custom permissions defiend in models. Now, I recreate database. Then, migrated with python manage.py migrate and created some users so that groups are created dynamically and permissions are assigned to that group which I mentioned above. Then, again used dump data command, this time ids are different. Also when I verified permissions in groups in django admin-panel, its showing different permission assigned to group to that of I coded. From this, I assume that whenever I … -
Django How can I upload a csv file?
I do that : With that whenf i click on Envoyée , i do'nt have modal for choice my csv file . Can you help me please ? forms.py class CSVUploadForm(forms.Form): csv_file = forms.FileField() views.py def upload_csv(request): form = forms.CSVUploadForm(instance=request.user) if request.method == 'POST': form = CSVUploadForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): # do something with the file form.save() csv_file = request.FILES['csv_file'] return render(request, 'password_change_done.html',) else: form = CSVUploadForm() return render(request, 'Paramétres.html', {'form': form}) Paramétres.html <form method="post" enctype="multipart/form-data"> {{ form.as_p }} `your text` {% csrf_token %} {# \<input type="submit" value="Upload"\>#} \<button class="btn btn-primary btnSendPP" type="submit" \>Envoyé\</button\> \</form\> -
My html isn't connecting to my css only when running trought server
I am making a django app and when I try to run the different pages the html is loading but not the css, when i open the files normaly(not from server) it all works fine, but when i run them trought the server it searches for the css at the url page. Here is an example: at url:http://127.0.0.1:8000/profile/create/ the html is all working but css isn't and I get this in the terminal: [21/Dec/2022 10:11:54] "GET /profile/create/ HTTP/1.1" 200 1374 Not Found: /profile/create/style.css [21/Dec/2022 10:11:54] "GET /profile/create/style.css HTTP/1.1" 404 2993 The html and css are in the same directory and here is my connection from my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="style.css"> <title>MyPlantApp</title> </head> -
Django rest api csv to json
I would like to create a django rest api that receives a csv file and then response the file in a json format. How do I achieve this without using models and anything related with databases? I don't want to use a database because it's assumed that the csv files will have different structure every time This is my first django project and I've seen lots of tutorials, even I did the first tutorial from django website but I can't understand how to do this task without the database. Thanks! -
How to set the Current user_id in the Django-Rest-Framework?
Alsomt all the answers are talking about how to set current user in the class with paraemter generics.ListCreateAPIView. But I'm just using APIView and I'm using function "post" to post the data. Can someone tell me how can I set a current user_id in this file. And do I need to add something in the serializers.py too? views.py class CreateVideo(APIView): permissions_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) serializer = VideoSerializer(data=request.data) user=self.request.user.id if serializer.is_valid(): serializer.save(user) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I created a variable "user" with self.request.user.id in it and then I passed it to the serializer.save(user). And when I created new video on the frontend side. It me gave a Bad Reuest Error. -
How can i load all fixtures inside particular directory While writing TestCases in Djnago using Pytest
I have multiple fixtures(json files) inside admin folder and i need to load all the fixtures of that directory without mannuallly writing all fixtures location. I have tried below code but but it's not working @pytest.fixture(scope='session') def load_admin_data(django_db_setup, django_db_blocker): fixtures = [ 'fixtures_for_tests/admin/*.json' ] with django_db_blocker.unblock(): call_command('loaddata', *fixtures) I need to give each and every fixture's location like shown below: @pytest.fixture(scope='session') def load_admin_data(django_db_setup, django_db_blocker): fixtures = [ 'fixtures_for_tests/admin/data1.json', 'fixtures_for_tests/admin/data2.json', ] with django_db_blocker.unblock(): call_command('loaddata', *fixtures) Note: One approch which i figure out is get all fixture location using some script is there any other way to give fixture location using some regex pattern while loaddata? I'm expecting that i'm able to give dyanamic path or regex pattern of fixture location -
Uncaught TypeError: $.ajax is not a function in Django
I have a function that works in the following manner: function ajax_display_schema_helper(schema_name){ $.ajax({ ... ... ... }); }; ajax_display_schema_helper('example schema'); But when I call the function above as following: $('.dropdown-item').click(function() { ajax_display_schema_helper(schema_name); }); I get the "$.ajax is not a function" error. What is the reason that it doesn't work when the function is called in the second way? -
Django allauth google login with Google identity
The google sign in javascript library is being deprecated: Warning: The Google Sign-In JavaScript platform library for Web is deprecated, and unavailable for download after March 31, 2023. The solutions in this guide are based on this library and therefore also deprecated. Use instead the new Google Identity Services for Web solution to quickly and easily sign users into your app using their Google accounts. By default, new client IDs are now blocked from using the older platform library; existing client IDs are unaffected. New client IDs created before July 29th, 2022 may set the plugin_name to enable use of the legacy Google platform library. The existing oauth implementation from django-allauth requires the users to either use server-based redirect with the Oauth2.0 code or send in both the access_token and id_token for processing the login, The implementation by google now only gives us the id_token and all the required data like name, profile picture etc. is included in the JWT token. Thus, the login fails as I am unable to send in both the access token and the id token. There are two approaches that come to my mind for solving this: I either override the social login view and … -
Why getting g++ not recognized as a command while running subprocess in python?
I have an online ide which takes code and language from the user and upon submitting the server has to execute the file. I have g++ installed on my system still upon execution I get the following error in subprocess module: 'g++' is not recognized as an internal or external command, operable program or batch file. '.' is not recognized as an internal or external command, operable program or batch file. The function for file execution is : def execute_file(file_name,language): if(language=="cpp"): #g++ xyz.cpp subprocess.call(["g++","code/" + file_name],shell=True) #this only compiles the code subprocess.call(["./a.out"],shell=True) #this executes the compiled file. my code file is there in the /code directory. The directory structure is : -
django.db.utils.ProgrammingError: column tickets_ticket.track_code does not exist
I used postgresql and I want add a new field to my model: track_code = models.CharField(max_length=32, verbose_name=_('کد رهگیری'), default=generate_rrr_unique_trackcode) but after migrate i received this error: django.db.utils.ProgrammingError: column tickets_ticket.track_code does not exist LINE 1: SELECT (1) AS "a" FROM "tickets_ticket" WHERE "tickets_ticke... I used the command: python3 manage.py migrate app_name 0001 and delete the last migration file and then try again but not working... -
How to import csv or json file into the model & create taboe for that data
I've a csv/json file. I need to include the file as a database for the django app. & I need to show the data as a table in frontend. So can't understand where I should insert the file so that it create table for me. I've create a django web application. With a app. Just trying to import file intothe model but in dbsqlite there is no change. -
drf Writable nested serializers "This field is required."
Here is the code: Models.py class Question(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='questions') question = models.CharField('lesson name', max_length=120) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options') option = models.CharField('test option', max_length=100) correct = models.BooleanField(default=False) Views.py class QuestionAPIView(generics.CreateAPIView): queryset = Question.objects.all() serializer_class = QuestionSerializer Serializers.py class OptionSerializer(serializers.ModelSerializer): class Meta: model = Option fields = ('option', 'correct') class QuestionSerializer(serializers.ModelSerializer): options = OptionSerializer(many=True) class Meta: model = Question fields = ('lesson', 'question', 'options') def create(self, validated_data): options_data = validated_data.pop('options') question = Question.objects.create(**validated_data) for option_data in options_data: Option.objects.create(question=question, **option_data) return question I'm try create test question with few option of answers like this: data = { "lesson": 2, "question": "This is our first question?", "options": [ { "option": "Option 1", "correct": True }, { "option": "Option 2 ", "correct": False }, { "option": "Option 3", "correct": True } ] } But in postman and in the TestCase I've got: { "options": [ "This field is required." ] } What is the problem of validation? Documentation here https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers Thanks. -
How to return a value from javascript function to django template in the same view?
I am just getting a value from an input tag by javascript. But Now I need to pass this value to the Django template on the same page to do my required task. <!DOCTYPE HTML> <HTML> <body> <h1>In Django Template</h1> <input type="text" id="agency_id" name="fname" value="1"> <select class="select" name="delivery_agent" id="DeliveryAgent"> <option class="form-control" value="{{ agent.id }}" {% if agent.id == delivery_agency_id %} selected="selected" {% endif %}>{{ agent.name }} </option> {% endfor %} </select> <script> var delivery_agency_id = document.getElementById("agency_id").value; alert(delivery_agency_id ) </script> Here, I am getting the agency_id by script. Now I need to pass it to the if condition as above code. Please help me to solve it. -
Reset Avatar ImageField to Default when User Clear Avatar Through DRF or Django Admin
I have django model ImageField called avatar. I want to enable user clear their avatar, so Blank = True. The problem is when user clear their avatar, the ImageField path is now empty. What i want is, the ImageField back to default. models.py class Profile(models.Model): AVATAR_UPLOAD_TO = "account_avatar/" DEFAULT_AVATAR = "default.jpg" user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) avatar = sorl.thumbnail.ImageField(upload_to=AVATAR_UPLOAD_TO, default=AVATAR_UPLOAD_TO+DEFAULT_AVATAR, blank=True, null=True) I see some related questions Django ImageField overwrites existing path when empty. But the behaviour is not exactly what i want. This answer required the user to upload new avatar, so user couldn't clear their avatar. Another related questions Django - How to reset model fields to their default value?. But i can't implement the save() method on my models I have tried to implement save() method on Profile model, but it don't work as expected def save(self, *args, **kwargs): if not self.avatar.name: setattr(self, 'avatar.name', self.avatar.field.default) super().save(*args, **kwargs) # Call the "real" save() method. I am new to Django and Django Rest Framework. Please help me, i stuck with this problem from a few days ago. Could you please help with my problems. Thanks in advance! -
Share env across GitHub Actions workflows
I have a GitHub Action (test-python.yml) intended to test a Django application. It utilizes the env tag like so towards the top of the file: env: SECRET_KEY: test DEBUG: False ... I want to make another workflow - not a job in the same workflow - that is reliant on the same variables. I could obviously just make another file for said workflow and copy the env however this seems slightly flaky, I'd rather somehow share the env variables across numerous workflows so I only have to keep it up to date in one place. Is there a way to do this? Thank you in advance! -
I am developing ecommerce website from django. While integrating payment on the project and running the server I got page not found error (404)
The error I got while I enter the customer detail and click on checkout: This is my views.py of payment. Here I have imported stripe module using stripe api and created checkout session: from django.shortcuts import render, redirect, reverse, get_object_or_404 from decimal import Decimal import stripe from django.conf import settings from orders.models import Order # Create your views here. stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = settings.STRIPE_API_VERSION def payment_process(request): order_id = request.session.get('order_id', None) order = get_object_or_404(Order, id=order_id) if request.method == 'POST': success_url = request.build_absolute_uri(reverse('payment:completed')) cancel_url = request.build_absolute_uri(reverse('payment:canceled')) session_data = { 'mode': 'payment', 'client_reference_id': order_id, 'success_url': success_url, 'cancel_url': cancel_url, 'line_items': [] } for item in order.items.all(): session_data['line_items'].append({ 'price_data': { 'unit_amount': int(item.price * Decimal(100)), 'currency': 'usd', 'product_data': { 'name': item.product.name, }, }, 'quantity': item.quantity, }) session = stripe.checkout.Session.create(**session_data) return redirect(session.url, code=303) else: return render(request, 'payment/process.html', locals()) def payment_completed(request): return render(request, 'payment/completed.html') def payment_canceled(request): return render(request, 'payment/canceled.html') This is urls.py of payment where I have created URL patterns for process where the order summary is displayed, stripe checkout session. completed for the successfull payment and canceled for payment cancelation. : from django.urls import path from . import views app_name = 'payment' urlpatterns = [ path('canceled/', views.payment_canceled, name='canceled'), path('completed/', views.payment_completed, name='completed'), path('process/', views.payment_process, name='process'), ] This … -
How to run external python file and show data in front end of django in the form of table
Hi Guys I want to run my external py scipt and the output will be on json I want to show the data in form of rows and table in front end, the data is dynamic regression testing data. how to I show that using django -
What is the best way to parse this request.data in drf, when the request is form-data?
I have this form which sends an image along with some other data. I am using django-rest-framework in the back end. I need to take out couple of fields from this form input and do some operations and use the remaining fields to send to my ModelSerializer for posting the form data. What is the best way to achieve this? <QueryDict: {'areaName': ['Mall-24F'], 'devices': ['[\n {\n "name": "device_001",\n "coordinates": [\n 23,\n 56\n ],\n },\n {\n "name": "device_002",\n "coordinates": [\n 24,\n 57\n ],\n },\n {\n "name": "device_003",\n "coordinates": [\n 25,\n 58\n ],\n }\n]'], 'floorMap': [<InMemoryUploadedFile: 1653650801973.png (image/png)>]}> This is how request.data looks like. What I have tried doing is context = request.data context["name"] = context.pop("areaName")[0] context["floor_map"] = context.pop("floorMap")[0] Basically I only want "name" and "floor_map" to be sent to ModelSerializer. I have read that request.data is immutable, but here it is mutable. I think I am missing something. -
Heroku: python version problems
I am trying to deploy a Django app on Heroku, but I am having compatibility issues with the requirements.txt file, it specifies "python-3.11.1". According to Heroku's documentation, Heroku stack 22 supports Python 3.11.1. But each time I try to deploy using the Heroku CLI, I get an error message. -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/usr/lib/python3.10/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 9: warning: command substitution: ignored null byte in input ! Requested runtime '��python-3.11.1 ! For supported versions, see: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed I tried git push heroku master I have followed the buildpack checking tutorial in the documentation: heroku buildpacks heroku buildpacks:clear heroku buildpacks:add heroku/python -
My Paginator not working at the last page button
when click next and previous button is working, but the last page not working model.py class VenueForm(ModelForm): class Meta: model = Venue fields = ( 'name', 'address', 'zip_code', 'phone', 'web', 'email_address' ) labels = { 'name': '', 'address': '', 'zip_code': '', 'phone': '', 'web': '', 'email_address': '', } widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Venue Name'}), 'address': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Address'}), 'zip_code': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Zip Code'}), 'phone': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Phone'}), 'web': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Web'}), 'email_address': forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Email'}), } view.py from .models import Event, Venue from django.core.paginator import Paginator def list_venues(request): venue_list = Venue.objects.all() p = Paginator(Venue.objects.all(), 3) page = request.GET.get('page') venues = p.get_page(page) nums = "a" * venues.paginator.num_pages return render(request, 'events/venue.html', { 'venue_list': venue_list, 'venues': venues, 'nums': nums}) events/venue.html <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> {% if venues.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">&laquo; First</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ venues.previous_page_number }}">Previous</a> </li> {% endif %} {% for i in nums %} <li class="page-item"> <a class="page-link" href="?page={{ forloop.counter }}">{{ forloop.counter }} </a> </li> {% endfor %} {% if venues.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ venues.next_page_number }}">Next</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ venues.paginator.num_pages ))">Last &raquo;</a> …