Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exiftools not installing on Heroku
I am trying to deploy my first project on Heroku and having an issue trying to install Exiftools on Heroku. My site is highly dependent on using ExifField within my models to get image information from pictures which is then displayed within my Django Admin to be edited etc. This all works fine locally in development. Exiffield relies on Exiftool.exe to work, so I have to install a buildpack to Heroku which I have done, but it fails to see it during release when pushing to Heroku via CLI. All Django modules have installed OK. I have added Procfile , requirements, runtime and everything seems to go OK, it even states it's intalled Exiftool but fails on release. Log below. Any help would be greatly appreciated. I was thinking it was issue with Procfile but it seems correct. release: python manage.py migrate web: gunicorn blog.wsgi Enumerating objects: 7, done. Counting objects: 100% (7/7), done. Delta compression using up to 16 threads Compressing objects: 100% (3/3), done. Writing objects: 100% (4/4), 375 bytes | 375.00 KiB/s, done. Total 4 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the … -
ModuleNotFoundError: No module named 'pip' not
I have an error when installing any package using pip Below the snippet: (venv) D:\projectodb>pip install psycopg2 Traceback (most recent call last): File "C:\Users\joao.malebo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\joao.malebo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "D:\projectodb\venv\Scripts\pip.exe\__main__.py", line 4, in <module> ModuleNotFoundError: No module named 'pip' (venv) D:\projectodb>` -
Rendering dynamic search in PDF xhtml2pdf Django
I am having some problems in rendering a a search query in PDF in Django. What I am trying to achieve is to print in PDF a web page search (I am filtering some data basically) and print the results in PDF. I can be more clear with some code. views.py def total_flight_hours(request): students = Student.objects.all() instructors = Instructor.objects.all() aircrafts = Aircraft.objects.all() start_date = request.POST.get('start_date') if not start_date: start_date = dt.now().date() end_date = request.POST.get('end_date') if not end_date: end_date = dt.now().date() student = request.POST.get('student') if not student: student = '' instructor = request.POST.get('instructor') if not instructor: instructor = '' aircraft = request.POST.get('aircraft') if not aircraft: aircraft = '' log_entry = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft)) log_entry_dual = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft) & Q(solo_flight=False)) total_flight_hours = log_entry_dual.aggregate(eet=Sum(ExpressionWrapper( F('ata') - F('etd'), output_field=IntegerField()), output_field=DurationField()))['eet'] if total_flight_hours != None: total_flight_hours = duration(total_flight_hours) log_entry_solo = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft) & Q(solo_flight=True)) total_flight_hours_solo = log_entry_solo.aggregate(eet=Sum(ExpressionWrapper( F('ata') - F('etd'), output_field=IntegerField()), output_field=DurationField()))['eet'] if total_flight_hours_solo != None: total_flight_hours_solo = duration(total_flight_hours_solo) log_entry_list = zip(log_entry, log_entry_solo) student_mission = StudentMission.objects.filter( log_entry_id__in=log_entry) month_begin = dt.today().replace(day=1, hour=0, minute=0, second=0, microsecond=0) today = dt.today().date() context = { 'log_entry': log_entry, 'log_entry_solo': log_entry_solo, 'total_flight_hours': … -
Pagination not taking effect on webpage
I'm applying pagination on my sports.html page, In views.py I'm using listview and using paginate_by = 2 but issue is pagination is not taking effect on webpage. Pagination numbers are visible on page and when clicking on those page numbers it's not showing any error but all posts are visible on all pages, posts are not dividing up by paginate_by value. Pastebin link for your reference: https://pastebin.com/utnd6v5N can anyone point out what I'm doing wrong here. -
Edit FileField file contents from Django Admin
I have a situation where I have python scripts that are stored as files that need to be modified from the Admin panel. Currently some of my models can have scripts attached to them: class Action(PolymorphicModel): title = models.CharField(max_length=100) text = BBCodeField('text', blank=True) action_script = models.FileField(upload_to='action_scripts') In my Admin panel I can upload a file but I have been asked to make this file editable in-place if the user has the right permissions. I've searched all over for an idiomatic way to do this, and so far I've come up with the following ideas: Override the FileField widget to include an text edit box and save button. This seems very brute forced Replace models.FileField with subclass of models.TextField, implement read from file, save to file, but then I lose the upload widget and data still gets stored in DB. This seems dirty because in the database all I'm storing is a filename. FileField feels like the right field type here. Write a custom ModelForm that includes forms.TextField. Handle save to file using the save method. I'm not sure how to accomplish this because I would have to generate a filename on the fly and I don't have a primary key … -
Handle deadlock in django with corrupted savepoint
I have an unavoidable bulk_create deadlock in my code. I decided to handle this part inside an atomic block and re-issue transaction when deadlock happened. Something like this: while True: try: with transaction.atomic(): bulk_create_some_data() return except OperationalError: log_error() continue But this causes error You can't execute queries until the end of the 'atomic' block. I checked history of statements of mysql and found that the savepoint has been corrupted as below log shows. *************************** 1. row *************************** event_id: 1 SQL_TEXT: set autocommit=0 MESSAGE_TEXT: NULL *************************** 2. row *************************** event_id: 2 SQL_TEXT: SAVEPOINT `s139836523404544_x2` MESSAGE_TEXT: NULL *************************** 3. row *************************** event_id: 3 SQL_TEXT: INSERT INTO `Transaction` ... MESSAGE_TEXT: Deadlock found when trying to get lock; try restarting transaction *************************** 4. row *************************** event_id: 4 SQL_TEXT: ROLLBACK TO SAVEPOINT `s139836523404544_x2` MESSAGE_TEXT: SAVEPOINT s139836523404544_x2 does not exist I found this thread which explains corruption of a savepoint is possible, it is an old thread and I am not sure whether it is still valid or not. How can I manage scenario like this to prevent an unavoidable lock causes my program crash. I am using django 3.1 and mysql 8.0. -
What's the difference between Reverse vs. Redirect in Django?
I am doing a django project, and is very confused about reverse, reverse_lazy and redirect. Can redirect function redirect with parameters? Or should I change method to reverse whenever I want to post parameters? -
can i make a view visible to some specific users and other not on Django
I want to make some pages not accessible for some users , what i mean for example i want to make user1 can see a viewa and can not see a viewb, I have tried to do that I have developed 2 functions of permissions and role user function: then i have go to home template where there was a sidebar contain 2 list(every list call a view) , I want to make just the users that are permitted tosee this view-list can see it on the navigate bar; here is the code in template.html: <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> {% if perms.app1_name.is_normaluser_login_required %} <li class="nav-item"> <a href="#" class="nav-link"> <i class="nav-icon fas fa-tachometer-alt"></i> <p> Module 1 <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="{%url 'form_module1'%}" class="nav-link"> <i class="far fa-circle nav-icon"></i> </a> </li> </ul> </li> {% endif %} {% if perms.app2_name.is_privilgeuser_login_required %} <!----> <li class="nav-item"> <a href="#" class="nav-link"> <i class="nav-icon fas fa-tachometer-alt"></i> <p> Module2 <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="{%url 'form_module2'%}" class="nav-link"> <i class="far fa-circle nav-icon"></i> </a> </li> </ul> </li> {% endif %} </ul> </nav> ---> after that the two lists disappear from the … -
distinct() method doesn't work with values() in Django
I am following Mosh's Django course, and I followed him step by step untill I get stack in this issue here, for him it works fine, but for me it doesn't work, I can't call distanct() method from values() why is that? I have searched in Django documentation and I found nothing I thought may they update it ,Igoogled it too but I haven't found an answer yet, could any one here help me ? queryset = OrderItem.objects.values('product_id').distinct() -
How do add some specific loaders to my webpack.config.js file
I want to add image-webpack-loader, file-loader and url-loader into my webpack.config.js file This is my webpack.config.js file: const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, //additional configuration to handle *.ccs files { test: /\.css$/i, use: ["style-loader", "css-loader"], }, { test: /\.(png|jpg|jpeg|gif|svg|eot|ttf|woff|woff2)$/, loader: "url-loader", options: { limit: 10000, }, }, { test: /\.json$/, use: [ { loader: "file-loader", options: { name: "data/[name].[ext]", }, }, ], },//end loader ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], }; I have tried this configuration tell me if this is right or what changes I should do to this... -
How to prefill serializer with user and fixed data?
I'm creating a simple game in which, after you log in, you need to create a character. My first problem is that I don´t know how to map the character I want to create to the User field (that has a OneToOne relationship). I'm using Simple DRF simple JWT for registration/login (which returns, after login, just the token and the refresh token) I wanted to prefill some fields (like hp set to 100, lvl to 1, etc). My approach is the following but it's not working, always getting something like "lvl": [ "field is required."] : Serializer: class CreateCharacterSerializer(serializers.ModelSerializer): hp = serializers.IntegerField(required=True) lvl = serializers.IntegerField(required=True) class Meta: model = Character fields = ('user', 'name', 'lvl', 'hp', 'current_hp', 'strength', 'agility',) def create(self, validated_data): instance = self.Meta.model(**validated_data) validated_data["lvl"] = 1 instance.save() return instance Views: class CharacterCreate(generics.CreateAPIView, PostUserWritePermission): permission_classes = [PostUserWritePermission] queryset = Character.objects.all() serializer_class = CharacterSerializer def post(self, request, format='json'): serializer = CreateCharacterSerializer(data=request.data) if serializer.is_valid(): character = serializer.save() if character: json = serializer.data return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to save a list of numbers to Django model
I am pulling some data from an API and I want to store it in my Django model. The data is a baseball inning and then runs scored that inning and comes to me like this... "innings":[ 0:0 1:3 2:0 3:0 4:1 5:2 6:0 7:0 8:4 ] I access each individual value like... for game in games: first_inning = game['scoreboard']['score']['innings'][0] second_inning = game['scoreboard']['score']['innings'][1] etc... But if I wanted to save all the data as it is and start the innings at 1 instead of 0, which type of field would I use and how would I do that? Would it be an ArrayField? I really appreciate your help. -
Add Tables As A Field In Django Python
So I Am Making A Shop Website I wanted to ask how do we add tables as a field? Do we use foreign key or something in Django I am using SQLite btw -
DRF Serializer IntegerField Validation To Make Sure ForeignKey Does Exists
I've a ModelSerializer class which uses an IntegerField as a replace for a ForeingKey relation. class CartItemCreateSerializer(serializers.ModelSerializer): product_id = serializers.IntegerField() class Meta: model = CartItem fields = ('id', 'product_id', 'quantity') def validate_product_id(self, value): if not Product.objects.filter(pk=value).exists(): raise serializers.ValidationError('Product not found') return value def save(self, **kwargs): product_id = self.validated_data['product_id'] cart_id = self.context['cart_id'] product = Product.objects.get(id=product_id) # product = get_object_or_404(Product, id=product_id) cart_item, _ = CartItem.objects.get_or_create( cart_id=cart_id, product=product) cart_item.quantity += self.validated_data['quantity'] cart_item.save() self.instance = cart_item return self.instance I've two questions about this class, first regarding the code, the validate_product_id method does a db call to check if the requested Product object exists and then inside the save method there is another call to db to get the same Product again, I think this way is not optimized for querying the same object twice. Is there a better way to check for the existence or raising proper error? second if I use get_object_or_404 the amount of code to write will decrease but there is no chance to raise a concise but relevant Error Message, so What do you usually do? -
Dump data frame values into a PostgreSQL table python
I have this data frame I want to dump this data into a Postgres table which has a foreign key of supplier and origin how can I do that, note that all the information of a supplier and origin exists in another data frame. -
S3 AWS for static files and heroku not working?
I am getting this error log from heroku after configuring S3 for static files. Can someone tell me what is wrong? https://i.stack.imgur.com/71Cja.jpg -
Custom Django template tag is not accessible at all pages
I am creating an app where there is no database because I am working with rest API, so the thing I want to show user phone number on the top of navbar at every page, I created a custom template tag and I am calling get_user_phone(user_phone) whenever someone logs in and pass that logged in user to this method and after loading the tag in the base template I am seeing the phone number but the issue is all other other pages which are extended by that base page is not showing this phone number @register.simple_tag() def get_user_phone(user_phone): return user_phone I am accesssing the user phone like this after loading the template {% get_user_phone user_phone %} -
how to find the diifrence of two time values
i have two functions one for add time to database from html if request.POST: time=request.POST.get("time") print(time) c.execute("insert into addtime(atime) values('"+str(time)+"')") conn.commit()```` I have an Html code to take the time `<form method="POST" > {% csrf_token %} <label>TIMES :</label> <input type="time" name="time" maxlength="30" required="" max="13" title="Enter characters only"> <input type="submit" name="subject" value="ADD Subjects"> </form> ` Here i have a function to compare two times one from database and other one is current time `def alarm(request): f="" time1=[] c.execute("select atime from addtime") data=c.fetchall() for i in data: for j in i: time1.append(j) from datetime import datetime now = datetime.now() print(now) import time f=time.strftime("%H:%M:%S") return HttpResponse("hai") how can I compare the two functions? the database value is stored in a list. later it is appended as string, the current time is also in string format! how can I compare these times, I WANT TO KNOW WHICH VALUE IS MORE CLOSE TO CURRENT TIME AND THE DIFFRENCE BETWEEN THEM? -
Do passing Django Queryset to method triggers database
I'm using Django for my backend and I'm wondering whether doing following thing hits the database. I know Django Querysets are lazy thus doing this only hits the database once : records = RecordModel.objects.all() records = records.filter(id__in=[1, 2, 3]) records = records.filter(name__in=["some", "random", "strings"]) print(records) In that case the database is really triggered when we try to print records. But when passing Queryset as method parameter. Is the database hit 2 times ? For instance: def some_api_endpoint(request): records = RecordModel.objects.all() records = RecordModel.filter_queryset(records, request.query_params) return Response(MySerializer(records, many=True).data) where filter_queryset performs some filtering on the queryset according to the request parameters. I'm wondering here if records are evaluated when passing it to filter_queryset AND when returning them in the Response ? Thanks in advance :) ! -
how to limit the number of time a button is clicked in django
i want to implement how to limit the number of time a button is clicked in django then send the user to the login page. To be more clear with my question, there is a download button and users can download pdfs when they are not logged in, now i want the max download to be 5 before a user is then redirect to the login or maybe register page so they can continue downloading. I tried this simple javascript code to do it but what is does it just increment the number when a button is clicked i do not really know how check if it's upto five click and then redirect. <script type="text/javascript"> var count = 0; var btn = document.getElementById("btn"); var disp = document.getElementById("display"); btn.onclick = function () { count++; disp.innerHTML = count; disp.save; } </script> <button id="btn">Click here to download </button> <span id="display">0</span>Clicked any more information needed? i available to provide it -
Django Real-time notifications in cross-platform apps without using django channels and redis server
Is there a way to get real-time notifications from Django to cross-platform apps without using Django channels and the Redis server? I am using Django in the back end and React in the front end. I used django channels and redis server locally. But due to some limitations, I was unable to push it to AWS. So I need to do it without django channels and redis server. Is there any way to do that? -
django.db.utils.ProgrammingError: column c.relispartition does not exist
USING: MacbookAir M1 (2020), MacOs Monterey(12.2.1), Python (3.10.2), Django (4.0.2), PostgreSQL (14.2) I started a simple django app and when i'm trying to connect my db (postgresql) i get this error File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: column c.relispartition does not exist LINE 3: CASE WHEN c.relispartition THEN 'p' WHEN c.relki... here is my settings.py DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql", 'OPTIONS': { 'options': '-c search_path=prg' }, "NAME": "******", "USER": "******", "PASSWORD": "******", "HOST": "**.***.***.***", "PORT": "5432" } } Never had problems with other db postgres. Have you ever seen something like this? -
aiohttp async with stripe Django
I am learning Django and I am trying to use aiohttp but I am unable to figure how can I use it with stripe API calls. This is my code: class ListCardSerializer(serializers.Serializer): pm = serializers.SerializerMethodField() class Meta: model = Bill fields = ["pm"] def get_pm(self, obj): stripe.api_key = settings.STRIPE_API_KEY cost = stripe.Customer.retrieve(customer_id) pm = stripe.Customer.list_payment_methods( customer_id, type="card" ) return pm I am new to Django any help will be appreciated. I am trying to convert my functions into async await. -
How to get value from dropdown list in django
I am trying to create an application which gets date from a db and then gets input from the user and returns data for that specific user-input value. I am facing an error while doing this. Views.py : from django.shortcuts import render from apple.models import predictions from django.views.generic import View # Create your views here. def home_view(request): return render(request, 'homepage.html') def post(request): company = str(request.POST.get("company-names")) final_date = request.POST["date1"] price = predictions.objects.filter(date=final_date) for x in price: pred = x.company return render(request, 'results.html', {'price': pred}) def back_view(request): return render(request, 'homepage.html') Homepage.html : <!DOCTYPE html> {% extends "base.html" %} {% block content %} <html> <body> <div class="login"> <h1 id = "page-title">Predict Stock Prices</h1> <h3 id = "date-title">Enter date (in format - yyyy-mm-dd)</h3> <h3 id = "company-title">Choose Company</h3> <form action="post" method="post"> {% csrf_token %} <select name="company-names" id="company-names" selected="selected"> <option value="reliance">Reliance</option> <option value="tcs">TCS</option> </select> <!-- <input type="text" id="company-names" name="company-names" placeholder="Company from Nifty-50"> --> <input type="text" name="date1" placeholder="Date after ( 2020-02-18 )" id="date-form" /> <input type="submit" id="button-submit" value="Predict" /> </form> </div> </body> {% endblock %} </html> Error I am getting : Error What my DB looks like : DB -
Search algorithm for crowded database Django
I am looking for search algorithm in order to fast search. I am currently using levenshtein_ratio_and_distance algorithm in order to search. But it is still taking a lot of time to search. Here is my code: def levenshtein_ratio_and_distance(s, t, ratio_calc = False): # Initialize matrix of zeros rows = len(s)+1 cols = len(t)+1 distance = np.zeros((rows,cols),dtype = int) # Populate matrix of zeros with the indeces of each character of both strings for i in range(1, rows): for k in range(1,cols): distance[i][0] = i distance[0][k] = k # Iterate over the matrix to compute the cost of deletions,insertions and/or substitutions for col in range(1, cols): for row in range(1, rows): if s[row-1] == t[col-1]: cost = 0 # If the characters are the same in the two strings in a given position [i,j] then the cost is 0 else: # In order to align the results with those of the Python Levenshtein package, if we choose to calculate the ratio # the cost of a substitution is 2. If we calculate just distance, then the cost of a substitution is 1. if ratio_calc == True: cost = 2 else: cost = 1 distance[row][col] = min(distance[row-1][col] + 1, # Cost of …