Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
message Request-URI Too Long
I'm kinda new at django and I have a problem with Error 414. I've made a web-application which should get a text from html textarea, process it and return processed text to a user but when I try to test it with +-big text I get an error 414. There's a code if needed: def result(request): get_text = request.GET['usertext'] get_r = request.GET['urls'] if get_r == 'urlsn': get_text = fm.func1(get_text) get_text = fm.func2(get_text) get_text = fm.func3(get_text) get_text = fm.func4(get_text) get_text = fm.func5(get_text) elif get_r == 'urlsy': get_text = fm.func1(get_text) get_text = fm.func2(get_text) get_text = fm.func3(get_text) get_text = fm.func4(get_text) get_text = fm.func6(get_text) return render(request, 'pt_result.html', {'processed_text':get_text}) -
DRF create method raise 'null value in column "project_id_id" violates not-null constraint' django rest framework
I got an integrity error while assign new sites to the existing project id's I followed the same solution from this answer Please find there models & serializers & views while trying with below script I got integrity error 'null value in column "project_id" violates not-null constraint DETAIL: Failing row contains (18, , null, 2022-06-14 16:43:12.319679+00, 2022-06-14 16:43:12.319679+00, t, 3, 3, null).' class CreateNewProjetSerial(serializers.ModelSerializer): site_name = ProjectSiteSerializer(many=True, read_only = True) assigned_to_id = AssignedUserSerializer(many=True, read_only = True) site_names = serializers.ListField( child = serializers.CharField(), write_only = True) user_ids = serializers.ListField( child = serializers.IntegerField(), write_only = True) project_ids = serializers.ListField( child = serializers.IntegerField(), write_only=True ) class Meta: model = Project fields = ['site_name','project_name','assigned_to_id', 'project_ids','site_names', 'user_ids'] def create(self, validated_data): site_names = validated_data.pop('site_names') user_ids = validated_data.pop('user_ids') project_ids = validated_data.pop('project_ids') new_project = ProjectSite.objects.create(**validated_data) for project in project_ids : new_project_site = Project.objects.create(project_id_id=project, **validated_data) for user_id in user_ids: Assignment.objects.create(assigned_to_id__id=user_id, site_id=new_project_site) return new_project json object for post { "site_names": ["site1106", "site2106"], "user_ids": [1], "project_id": [16] } -
How to convert QuerySet string intro String in Django template?
Django template shows the categories as for example <QuerySet [<Category: Fashion>]> I want it to show just as Fashion. index.html {% for auction in auctions %} <li>Auction: {{ auction.title }} Content: {{ auction.content }} Price: {{auction.price}} Category: {{ auction.category.all|slice:":1" }} <img src="{{auction.pic}}" alt="{{auction.title}} pic"> </li> {% endfor %} models.py class Category(models.Model): FOOD = 'FO' TOYS = 'TO' FASHION = 'FA' ELECTRONICS = 'EL' HOME = 'HO' NOTHING = 'NO' CHOICECATEGORY = ( (FOOD,'Food'), (TOYS,'Toys'), (FASHION,'Fashion'), (ELECTRONICS,'Electronics'), (HOME,'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') categorysomething = Category.objects.filter(category=category).first() views.py def index(request): return render(request, "auctions/index.html", { "auctions": Auctionmodel.objects.all() }) -
Django crispy forms renders select2 field twice
I am using django crispy forms for a ModelForm. In this form I have a field which I would like to display as a Select2MultipleWidget (Provided by django-select2). When displaying the form like this: {{ form }} the field renders just fine. However when using the crispy tag like {% crispy form %} the select2 widget renders twice: This problem does not arise when using the crispy filter like this: {% form|crispy %}. Why is this happening? Should I simply use the filter instead of the tag or is there any workaround here? -
Django - Parent imageField url isnt showing on template
This is my model structure. Institution - name - logo - .... Course - Owner ( foriegnKey with Institution ) - name - terms - ..... So now, am just calling data's like. courses = Course.objects.filter(name__icontains=query).values('id','name','terms','owner__name', 'owner__logo') And trying to display the owner__logo as {{data.owner__logo.url}}. But its not working, as the img src shows (unknown). But when this Institution logo thing works on some other view when i directly call it. but when i call via relationship its not working. If i use {{data.owner__logo}} then it just passes the url without the full path. How to make this work, please help ! -
Django REST multiple serializers aren't saved
I'm trying to add a user profile to the user so they can be updated . I tried to update it one by one and I found that serializer1 is updated if I didn't add serializer 2 to the list , it doesn't update the value and when the user doesn't have a profile it creates one for him views.py @api_view(['POST']) def user_update(request,pk): if request.method == "POST": user = User.objects.get(pk=pk) try: user_p = UserProfile.objects.get(user=user) except: user_p = UserProfile.objects.create(user=user) serializer1 = UserSerializer(instance = user , data = request.data) serializer2 = UserUpdateSerializer(instance = user_p , data = request.data) if serializer1.is_valid() and serializer2.is_valid(): serializer1.save() serializer2.save() Serializer_list = [serializer1.data, serializer2.data] return Response(Serializer_list) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email'] class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = '__all__' models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) image = models.ImageField(upload_to='user',default='default.png') def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300 : output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) -
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>