Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django stand alone app - sharing data with projects that use standalone app
I am using Django 3.2. I have written a stand alone app that handles user profile management. The app use MaxMindDb to map IP addresses to Countries and Cities. Applications that use my app, need to set a variable GEOIP_PATH in their settings.py file. Currently, I'm having to do this: GEOIP_PATH = os.path.join(BASE_DIR, 'geodata') Which means that I will have to make copies of the huge database for each project using the app. Is there a way to package the MaxMindDb with my app, so that I can refer to it's location a bit like this: GEOIP_PATH = os.path.join([PATH_TO_PIP_INSTALLATION_OF_MY_STANDALONE_APP], 'geodata') -
Django - how to sum 2 DecimalFields in a model and display in admin view?
I have 2 DecimalFields in 1 model. How can I sum both fields together and have the total show up in the admin view? price = models.DecimalField(max_digits=6, decimal_places=2) spotters = models.DecimalField(max_digits=6, decimal_places=2, default=150) There has to be a "container to retain the sum in admin view so I have: total_price = models.DecimalField(max_digits=100, decimal_places=3, default=0) at the end then I finish with a return method: def get_cost(self): return self.price + self.spotters but its not working -
ISSUES IMPORTING MODELS
Hope anyone here would be able to help me out. I'm trying to makemigrations but it's been impossible :/ I keep getting the following error: File "C:\Users\User\Documents\EBAC\Django\django\bookstore\order\models_init_.py", line 4, in from .order import Order File "C:\Users\User\Documents\EBAC\Django\django\bookstore\order\models\order.py", line 4, in from product.models import Product ModuleNotFoundError: No module named 'product.models' as you can see on the the file structure I have 2 apps order and product, I am trying to import the Product model inside my Order model, but it keep saying that there is no module named 'product.models' from django.contrib.auth.models import User from django.db import models from product.models import Product class Order(models.Model): product = models.ManyToManyField(Product, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) I have declared both apps on the settings.py: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'order', 'product', ] and have also create the init.py for the models folder: from .category import Category from .product import Product I have the impression that all the set up is correct and also the code, but it's not working, if anyone could help me out to find the issue here I would strongly appreciate. Thanks a lot -
Django doesn't validate or see the JWT token from Azure
I used azure-ad-verify-token 0.2.1 on Django-rest backend to validate a jwt token from Microsoft Azure, where the user is authenticated on the frontend with React. According to the documentation, this library should do everything on its own. from azure_ad_verify_token import verify_jwt azure_ad_app_id = 'my app id' azure_ad_issuer = 'https://exampletenant.b2clogin.com/0867afa-24e7-40e9-9d27-74bb598zzzzc/v2.0/' azure_ad_jwks_uri = 'https://exampletenant.b2clogin.com/exampletenant.onmicrosoft.com/B2C_1_app_sign_in/discovery/v2.0/keys' payload = verify_jwt( token='<AZURE_JWT_TO_VERIFY_HERE>', valid_audiences=[azure_ad_app_id], issuer=azure_ad_issuer, jwks_uri=azure_ad_jwks_uri, verify=True, ) print(payload) I don't understand the line token='<AZURE_JWT_TO_VERIFY_HERE>', how can I put the token there? Authorization from Azure on React is successful, and I get a access jwt-token that I can extract: token = request.headers['Authorization'] But I need to validate it and somehow insert it into a string token='<AZURE_JWT_TO_VERIFY_HERE>', but it doesn't recognize the request here. How can I put a token= from the header? And in general, is this the right way? Or am I missing something? Any help and hints would be very helpful and would be greatly appreciated. Or advise another library for token validation in Python. -
Generate a link to Stripe Customer Account Link regardless of the current browser account
I'm using Stripe in Django, I would like to generate a navigation link from django admin portal to Stripe Customer Account. eg: [Customer Id] I've concatenated the id to the following url: "https://dashboard.stripe.com/customers/" to be "https://dashboard.stripe.com/customers/cus_LX88WdbprptpWe" If I click the link, supposedly it opens the Stripe Account and navigates to the customer, this is incase the customer exists in this account. While if the customer actually exists, but currently in the browser I'm logged on a different stripe account, the customer response will not be found. eg: [Customer not found] What I wonder is how to generate a valid stripe customer account link that redirects to the customer's account as well as the correct Stripe Account to avoid the "not found customer" issue. Thanks -
How can i solve this error? I'm working with django on a school project and i'm stuck
i get this error " ModuleNotFoundError: No module named 'models' ". I created a model called Job and I imported it to the admin. But I have that error. I've tried switching up the names of the model and some other folder on the project cause I read somewhere that could be the issue but I can't seem to get my head around it. from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Job(models.Model): title = models.CharField(max_length=150) company = models.CharField(max_length=100) location = models.CharField(max_length=200) salary = models.CharField(max_length=100) nature = models.CharField(max_length=10, choices=TYPE_CHOICES, default=FULL_TIME) experience = models.CharField(max_length=10, choices=EXP_CHOICES, default=TIER1) summary = models.TextField() description = models.TextField() requirements = models.TextField() logo = models.ImageField (default='default.png', upload_to='upload_images') date_created = models.DateTimeField(default=timezone.now) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{} looking for {}'.format(self.company, self.title) then this is my input in the admin.py file from django.contrib import admin from models import Job admin.site.register(Job) -
How to redirect one html page to another html page in django
[this is my second page html code to redirect from first page][1] when I click the button in login I need to generate the next page by verifying valid login details how please help????? I will give my view.py file also this is views.py file please verify and help how to write efficient code -
Why aren't changes saved when editing a Django product?
Created a website with products. I need to make a window for editing them on the site in order to change the manufacturer and other characteristics. This must be done in a pop-up window. I have data displayed, I change it, but nothing changes when I save it. How can this problem be solved. My vievs: def parts(request): added = '' error = '' PartAllView = Part.objects.order_by('-id') if request.method == 'POST' and 'parts_add' in request.POST: form = PartForm(request.POST, request.FILES) if form.is_valid(): form.save() added = 'Добавлено' else: error = 'Данная запчасть уже добавлена' if request.method == 'POST' and 'parts_edit' in request.POST: PartPost = int(request.POST['parts_edit']) PartID = Part.objects.get(id=PartPost) if PartID: PartID.save() added = 'Запчасть успешно отредактирована' else: error = 'Ошибка редактирования' form = PartForm() data = { 'added': added, 'error': error, 'form': form, 'PartAllView': PartAllView, } return render(request, 'kross/parts.html', data) My HTML: {% if PartAllView %} {% for el in PartAllView %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal fade" id="partEdit{{ el.id }}"> <div class="modal-dialog modal-dialog-centered text-center" role="document"> <div class="modal-content modal-content-demo"> <div class="modal-header"> <h6 class="modal-title">Добавление запчасти</h6><button aria-label="Close" class="btn-close" data-bs-dismiss="modal"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="row row-sm"> <div class="col-lg-6"> <div class="form-group"> <input type="text" class="form-control" name="brand" value="{{ el.brand }}"> </div> </div> <div class="col-lg-6"> … -
django ORM query for sort by 2 item
I have one Model with name " ProgrammingQuestionAnswer ". at that I have user, time, accept I want to write a query for get Users have many accepted Question and those who are equal are sorted by time please help me this is my model: class ProgrammingQuestionAnswer(models.Model): programming_question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='programming_question_a', null=True, blank=True) time = models.DateTimeField(default=timezone.now) score = models.IntegerField(null=True, blank=True, default=0) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='writer_answer_programming_question', null=True, blank=True) accept = models.BooleanField(default=False) file = models.FileField(upload_to=content_file_name) result = models.TextField(null=True, blank=True) file_name = models.CharField(max_length=500, null=True, blank=True) max_score = models.IntegerField(null=True, blank=True, default=0) -
How to create a good Django Test?
I am currently doing testing on Django API endpoint. My current objective is to ensure that the API endpoint return 200 as status code. But I am not sure whether if i done it in a right way although the tests are successful.Are there any suggestions or improvement for my test case ? tests.py from django.test import TestCase,Client from rest_framework import status from rest_framework.test import APITestCase from .models import * import json client = Client() username = 'jeff' password = 'jeff' class StaffModelTest(APITestCase): def setUp(self): response = client.post('/admin/login/', {'username': username, 'password': password}) self.assertEqual(response.status_code, 302) def get_api(self,url): response = client.get(url) self.assertEqual(response.status_code,200) if response.status_code == 200: return "200 OK" else: return "Error Occurred" def test_login_url(self) : url = '/admin/login/' response = self.client.get(url, format = 'json') assert response.status_code == 200 def test_accounts_api(self): self.get_api('/accounts/api/v1/accounts/staff/') self.get_api('/accounts/api/v1/accounts/staff/1/') def test_accounts_department_api(self): self.get_api('/accounts/api/v1/accounts/department/') self.get_api('/accounts/api/v1/accounts/position/') def test_staff_statistics_api(self): self.get_api('/accounts/api/v1/accounts/staff/statistic/department') self.get_api('/accounts/api/v1/accounts/staff/statistic/religion') def test_staff_id_api(self): self.get_api('/accounts/api/v1/accounts/staff/1/family/') self.get_api('/accounts/api/v1/accounts/staff/1/family/1/') -
How to create non django files in the static files template in a Django Project
I have a folder in my django project called "templates", its linked to my main project which can access the files (HTML...) correctly as I can make it display stuff like "Hello World" but the project considers the files in the folder as django files even though when creating them I typed stuff like "main.css" or "main.html". The issue is it doesnt tell me if I have errors and it doesnt let me autofill so I was wondering if there was a way to fix this. Thx for any answers! Picture of my Project -
Microsoft authentication login
I want to authenticate my Django base website users by Microsoft authentication, I have followed a solution . by following the solution I successfully redirect my user to Microsoft login page but when I enter my credentials I got an error I have also follow the solution provided by Microsoft by adding this ( http://localhost:8000/microsoft_authentication/callback ) URL in my azure application but it does not work for me so can you please tell me that how can I integrate Microsoft authentication with my Django project -
Django average grouped by foreign key
I have this model class Makes(models.Model): student = models.ForeignKey(...) instrument = models.ForeignKey( to='users.Instrument', on_delete=models.CASCADE ) begin_date = models.DateField( null=True, blank=True ) end_date = models.DateField( null=True, blank=True ) And I want to get the average, grouped per instrument, of the timedelta between begin_date and end_date I tried this: from django.db.models import Avg, F, ExpressionWrapper, fields duration = ExpressionWrapper(F('end_date') - F('begin_date'), output_field=fields.DurationField()) instrument_data = ( Makes.objects .exclude(begin_date__isnull=True) .exclude(end_date__isnull=True) .annotate(duration=duration) .aggregate(average=Avg(duration)) # I can't even figure out how to also get the instrument name here ) But that got me the average of all the durations, and not the average duration per instrument. I also tried this: instrument_data = ( Makes.objects .exclude(begin_date__isnull=True .exclude(end_date__isnull=True) .annotate(duration=Avg(duration)) .values('instrument__instrument_name', 'duration') ) But that got me the "Average" of each individual Makes instance so in conclusion, how do I get a result that looks a bit like this <QuerySet[ { 'instrument__instrument_name': 'alt-viool', 'duration': datetime.timedelta(days=142) }, { 'instrument__instrument_name': 'contrabas', 'duration': datetime.timedelta(days=62) }, { 'instrument__instrument_name': 'viool', 'duration': datetime.timedelta(days=49) } ]> -
Django static files not consistent between DEBUG=True and after `collectstatic`
My "Select all {amount} {model}s" action, which should be in the actions bar while viewing a model page in the Django admin, does not work in production. Expected behaviour, as recorded running locally with DEBUG=True in local_settings.py: Behaviour on staging deployment and while running locally with DEBUG=False: I'm having issues with inconsistency between the static files my templates are working with between a local running of the runserver command with DEBUG=True vs. running the same codebase after running collectstatic and then running it with DEBUG=False in my settings. The differences in static files is also apparent in the listed sources when inspecting the page. Working correctly: Not working correctly: Running the collectstatic command gives me this output: Loading .env environment variables... Found another file with the destination path 'admin/js/actions.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin/js/admin/RelatedObjectLookups.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path … -
Django : upload direct folder to input type file instead selecting multiple files
How can we upload direct folder to input type file ? I mean user can upload direct folder of images or files instead of selecting multiple files? -
django Get Group Ids from Whatsapp,
I have problems How to get a name, id from WhatsApp API in Django application? When I click in plus icon want create contact with that id and name . ******urls.py ` path('add_contact/<int:contact_id>' , views.add_contact, name="add_contact"),` 1. List item ******template ` {% for cont in contact %} <td>{{cont.name}}</td> <td>{{cont.id}}</td> <td> <a href="{% url 'add_contact' cont.contact_id %}" class=" btn text-secondary px-0"> {% csrf_token %} </a> <i class="fa fa-plus" aria-hidden="true"></i> </a> </td>` ******views `@login_required def add_contact(request,contact_id): contact = Contact.objects.get(contact_id=contact_id) form = CreateContactForm(request.POST,instance=contact) if form.is_valid(): form.save() return render(request, 'dashboard/contact.html') *************enter image description here -
How to solve "detail": "Authentication credentials were not provided." error for Class-based APIView Django REST Framework?
I am using Django REST Framework and following this tutorial for retrieving all users when admin user is authenticated. Class-based APIView of Django REST Framework I am using Postman to test and trying to retrieve the list of all users registered in the system. At first I try to use my "User Login with Token" API in Postman to create the necessary token as shown below: I copied the value of the "token" key and pasted it as the value of the "Authorization" key in the "Headers" section of "Get All Users" API in Postman as shown below. It is a GET request and I get the error "detail": "Authentication credentials were not provided." as the response. Necessary code snippets are as follows: views.py class UserAccountListView(APIView): """ List of All Users in the System / Application * Requires Token Authentication. * Only Admin Users are able to access this view. """ authentication_classes = (TokenAuthentication, ) permission_classes = (IsAdminUser, ) def get(self, request, format=None): """ Returns a List of All Users """ full_names = [user.full_name for user in UsersAccount.objects.all()] return Response(full_names) settings.py REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ … -
Filter the Modal Data in django staff side
I have a model name Complain in which i have a field station(return police station name) foreign key with station table and user field foreign key relation with user table. Now what i want when i add staff user then it will show only the complain data that have same station name. thanks! -
'set' object is not a mapping (Error trying to add a list of choices.)
Generally, when I remove from the html template {{ createnewauctionhere.category}} this all works, but I would like to display a list from which to select a category anyway. This is part of the CS50 course. Could someone please explain to me what am I doing wrong and where am I making a mistake? models.py class Category(models.Model): choicecategory = ( ('1','Food'), ('2','Toys'), ('3','Fashion'), ('4','Electronics'), ('5','Home') ) category = models.CharField(max_length=300, choices=choicecategory) def __str__(self): return self.category class Auctionmodel(models.Model): title = models.CharField(max_length=300) content = models.TextField() price = models.IntegerField() pic = models.CharField(max_length=300, blank=True) category = models.ManyToManyField(Category, related_name='Category') def __str__(self): return f"Title: {self.title} Content: {self.content} Price: {self.price}" class Addauctionform(ModelForm): class Meta: model = Auctionmodel fields = '__all__' widgets = { "title": TextInput(attrs={'placeholder':"Title Of Auction"}), "content": Textarea(attrs={'placeholder':"Content Of Auction"}), "price": NumberInput(attrs={'placeholder':"Price Of Auction"}), "pic": TextInput(attrs={'placeholder':"Image Of Auction"}), "category": Select(attrs={'placeholder:"Category Of Auction'}) } createnewauction.html <form action="{% url 'createnewauction' %}" method='post'> {% csrf_token %} {{ createnewauctionhere.title}} <br> {{ createnewauctionhere.content}} <br> {{ createnewauctionhere.price}} <br> {{ createnewauctionhere.pic }} <br> {{ createnewauctionhere.category }} <br> <input type="submit" value="Create"> </form> -
What is this 'from asyncio.windows_events import NULL'?
Good Morning and Evening Everyone, This morning in my django app under the views.py I saw the following import line in my code: from asyncio.windows_events import NULL I'm not sure how this got here, but I was wondering how and why was it added to my code. Last thing I remember I did was ran python manage.py migrate . Any ideas??? -
unslugifying the already slugified text in django without using replace method
from django.utils.text import slugify urlparameter = slugify("This is my First trip") # this-is-my-first-trip now i want it to un-slugify it to previous text ('this is my first trip') but not using replace.("-", " ") Is there any django way to do so ?? -
Catching an exception in Django
I have been building an application using Django and Vuejs. The application using YouTube API to scrap for videos based on a few conditions that are set in the website that I am building. For some conditions I am getting a very weird error which I am not able to catch. What can be done to catch the error? Refer the screenshot: The error occurs at the place where I am printing Error 1. So many different times of errors occur here and I am not able to catch it, so that I can display customized messages based on the error. Area where the error was found -
Calling Hyperledger Fabric peer client and redirecting log in python
I'm creating a Rest API to interact with two systems (one of them is HLF). (peer is a binary of a program written in go that I don't want to change) I'm trying to use Django (Python) and Python Subprecess to call "./peer chaincode invoke...", but when I try to read the output, it returns an empty list. I would like to redirect the text from the console (log info) to the standard output. def read: os.chdir(str(Path.home()) + "/HLF/fabric/bin") os.environ['FABRIC_CFG_PATH'] = "../config/" cafile = "../../organizations/ordererOrganizations/omega.olympus.pt/msp/tlscacerts/ca-omega-olympus-pt-7054.pem" channel = "main-channel" label = "occv1" orderer = "cronus.omega.olympus.pt:7050" function='{"Args":["ReadAsset","00000"]}' command = ['./peer', 'chaincode', 'invoke', '-o', orderer, '--tls', '--cafile', cafile, '-C', channel, "-n", label, '-c', function] proc = subprocess.Popen(command, stdout=subprocess.PIPE) print("output", proc.stdout.readlines()) Output: 2022-06-14 12:11:13.254 UTC 0001 INFO [chaincodeCmd] chaincodeInvokeOrQuery -> Chaincode invoke successful. result: status:200 payload:"{\"ID\":\"00000\",\"ClientID\":\"00000\",\"consents\":\"\",\"timestamp\":\"2022-06-05 13:56:18\",\"cid\":\"12345\",\"hash\":\"--------------------------------------------\"}" output [] -
How to perform function from user uploaded image without saving it in database Django?
recently I'm trying to create a steganography tool in django, but I'm having some problems with how to perform function from a user uploaded image without saving the image in database. views.py def steganography(request): if request.method == 'POST': #Encryption if 'steg_en' in request.POST: cover_image = request.FILES['cover_image'] secret_message = request.POST['secret_message'] #perform steganography encryption function context_sten = { #return encrypted image } return render(request, 'steganography.html', context_sten) #Decryption elif 'steg_de' in request.POST: encrypted_image = request.FILES['encrypted_image'] #perform steganography decryption function context_stde = { #return decrypted text } return render(request, 'steganography.html', context_stde) else: return render(request, 'steganography.html') After performing the steganography functions whether encryption or decryption, it will return the output back to steganography.html steganography.html <!-- Encryption Input --> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="cover_image">Upload your cover image</label> <input type="file" class="form-control" name="cover_image" required> <label for="secret_message">Enter your secret message</label> <input type="text" class="form-control" name="secret_message" placeholder="Enter your secret message" required> <button type="submit" name="steg_en" class="btn btn-primary">Encrypt</button> </form> <!-- Encryption Output --> <!-- Decryption Input --> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="encrypted_image">Upload your encrypted image</label> <input type="file" class="form-control" name="encrypted_image" required> <button type="submit" name="steg_de" class="btn btn-primary">Decrypt</button> </form> <!-- Decryption Output --> {{ decrypted_text }} stego.py This is the code of steganography I refer. Refer link: https://dev.to/erikwhiting88/let-s-hide-a-secret-message-in-an-image-with-python-and-opencv-1jf5 -
JS script runs partially on heroku but fully locally (Django)
document.addEventListener('DOMContentLoaded', function() { // get button by id //document.getElementById('closedjs_$').style.display='none'; var trips = document.querySelectorAll('*[id^="closedjs"]'); // trips = document.querySelectorAll('.closedjs') trips.forEach((element) =>{element.style.display='none';}) // checking if current passengers >= max passengers so changing Join btn to Closed /* document.querySelectorAll('.joinleave').forEach((element) => { var route_id = element.dataset.id; var no_pass= parseFloat(document.querySelector(`#thepassengercounter_${route_id}`).innerHTML); var max_pass = parseFloat(document.querySelector(`#max_pass_${route_id}`).innerHTML); if (no_pass == max_pass){ if (element.innerHTML="Join"){ element.style.color = "#B22222"; element.style.border = "1px solid #B22222"; element.title="Closed"; element.innerHTML="Closed"; } else{ element.title="Leave"; element.innerHTML="Leave"; } } } )*/ // so as to not reload the page after joining or leaving a trip. It updates the innerHTML instantly //and then fetches as POST the route_id json page so as to update the DB document.querySelectorAll('.joinleave').forEach((element) => { element.onclick = () => { var route_id = element.dataset.id; fetch(`/route/${route_id}`) .then(response => response.json()) .then(route => { if (route.error) { console.log(route.error); alert(route.error) } var no_pass= parseFloat(document.querySelector(`#thepassengercounter_${route_id}`).innerHTML); var max_pass = route["no_pass"]; var dist = route["dist"]; var key_num = route["key_num"]; var co2=dist*2.40*2; var fin = document.querySelector(`#fin_${route_id}`).innerHTML; var diff_p = max_pass-no_pass //console.log(route_id); console.log('max passengers ', max_pass); console.log('current passengers ', no_pass); console.log('is date or time passed? ', fin); console.log('diff pass ', diff_p); alert('presssed') //CODE EXECUTES UP TO HERE THE ALERT 'PRESSED' IS DISLAYED// //console.log(dist) //console.log(key_num) // checking if current passengers >= max passengers so not allowing …