Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handling JsonResponse in Django template
I'm trying to make a webpage in which you can specify a number of vectors, then insert modulus and angle for each one, and it will calculate the sum. My code can do the calculation, but I can't properly display the result on my template. views.py: def sum_view(request): if request.method == "POST": message = '' for j in range(2,12): if not request.POST.get(f'vector_mod_{j}'): num_vett = j - 1 result = Vector(0, 0) for i in range(num_vett): mod = float(request.POST.get(f'vector_mod_{i+1}')) ang = float(request.POST.get(f'vector_ang_{i+1}')) result += Vector(mod, ang) message = f'Modulus: {result.modulus}, angle: {result.angle}°' return JsonResponse({'message': message}) return render(request, 'vectsum/sum.html') The problem is that when I submit I see a sort of firefox developer tools view with a menu including 'JSON', 'Raw Data', 'Headers', and the correct message displayed in a console-like way. Here is the ajax part of my template: $(document).on('submit','#calculate',function(e){ e.preventDefault(); $.ajax({ type:'POST', headers: {'X-Requested-With': 'XMLHttpRequest'}, url:'/vectorialsum/', data: $('#calculate').serialize() success:function(data){ var mess = JSON.parse(data)['message'] document.getElementById('result').innerHTML += mess } }) }); How do I show the message in my page? -
Using the URLconf defined in myapp.urls, Django tried these URL patterns, in this order
I think I went through every available answer to this error but they all reference some other tutorial and a views.py which I do not have. After running the tutorial from here I get this 404 error. Using the URLconf defined in myapp.urls, Django tried these URL patterns, in this order: admin/ ^$ [name='home'] ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, market_data/, didn’t match any of these. The urls.py has the following code: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.urls import re_path as url from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='templates/static_pages/index.html'), name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) The root directory structure of this project is ~/market_data/myapp ~/market_data/myapp/static_media ~/market_data/myapp/static_files ~/market_data/myapp/static_files/admin ~/market_data/myapp/templates ~/market_data/myapp/templates/static_pages Thank you for any tips! -
The current path, search/, didn’t match any of these
I can't find the source of this error. all my routes and view functions work except this one. ---- urls.py path('search/', views.search, name='search'), --- views.py def search(request): return HttpResponse('test search page') even when I use def search(request): return render(request, 'store/store.html') I still have the same error I've been struggling with this problem for several days. Here is the error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/search/ Using the URLconf defined in config.urls, Django tried these URL patterns, in this order: admin/ [name='home'] store/ cart/ ^media/(?P<path>.*)$ The current path, search/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. here is the complete code of my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.store, name='store'), path('category/<slug:category_slug>/', views.store, name='products_by_category'), path('category/<slug:category_slug>/<slug:product_slug>/', views.product_detail, name='product_detail'), path('search/', views.search, name='search'), And the complete code of my views.py from django.shortcuts import render, get_object_or_404 from category.models import Category from .models import Product from cart.views import _session_id from cart.models import CartItem, Cart from django.http import HttpResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # Create your views here. … -
Django rest elasticsearch filter range in url query params
I am using elasticsearch with django rest framework.I am using this lib: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/ I am trying to filter by price range according to this docs: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/ This is my views: class TestAPIView(DocumentViewSet): document = TestDocument serializer_class = TestSerializer queryset = TestModel.objects.all() filter_backends = [ FilteringFilterBackend ] filter_fields = { 'price': { 'field': 'price', 'lookups': [ LOOKUP_FILTER_RANGE, LOOKUP_QUERY_IN, ], }, } and this is my document.py file @registry.register_document class TestDocument(Document): price = fields.IntegerField(attr='price') class Index: name = 'TestModel' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } class Django: model = TestModel fields = [ 'id', ] When i hit on browser this url: http://127.0.0.1:8000/search/api/v1/test-model/?price=12 It works very well, even when i try with this url : http://127.0.0.1:8000/search/api/v1/test-model/?price=55 it works, I am facing problem to filter by range, like i want to filter price 12 to price 90, in this case how can i pass query paramter for the range? can anyone help me in this case? -
How i can convert csv file to ofx file in django application using python
i want to do a small application to convert my ".csv" files to ".ofx" files using django, where i can upload a file".csv" then press a button to convert it to ".ofx" with the same filename of the csv imported . this is my models.py: class Blog(models.Model): csv = models.FileField() filename = models.CharField(max_length=20) this is my views.py: from .forms import BlogForm import itertools as it from meza.io import read_csv, IterStringIO from csv2ofx import utils from csv2ofx.ofx import OFX from csv2ofx.mappings.default import mapping def UploadFile(request): if request.method == 'POST': form = BlogForm(request.POST,request.FILES) if form.is_valid(): form.save() ofx = OFX(mapping) records = read_csv('/home/mariana/virtualenv/django_project/mycsv.csv', has_header=True) groups = ofx.gen_groups(records) trxns = ofx.gen_trxns(groups) cleaned_trxns = ofx.clean_trxns(trxns) data = utils.gen_data(cleaned_trxns) content = it.chain([ofx.header(), ofx.gen_body(data), ofx.footer()]) myfield = form.cleaned_data.get("filename") print(myfield) print("saved") response = HttpResponse(content_type='application/ofx') response['Content-Disposition'] = 'attachment; filename=myfield.ofx' return response else: form = BlogForm() print("not saved") context = { 'form':form, } return render(request, 'pages/Upload.html', context) enter image description here after pressing the button(convet) there was a file downloaded('myfield.ofx') but it's empty that's mean the csv file doesn't converted to ofx file... Thanks in advance. -
static/rest_framework/css/bootstrap.min.css” does not exist
I got with Django rest framework problem when I deployed Django project in production mode if I go to http://127.0.0.1:8000/myproj/api/v1/persons.json everything is displayed correctly if I go to https://example.com/myproj/api/v1/persons.json?format=api - layout breaks in the page code I see: link rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap.min.css" if I navigate to the path https://example.com/static/rest_framework/css/bootstrap.min.css I see this error in the browser: Page not found (404) “/data/Projects/myproj_dev/Django/myproj/static/rest_framework/css/bootstrap.min.css” does not exist Request Method: GET Request URL: https://example.com/static/rest_framework/css/bootstrap.min.css Raised by: django.views.static.serve Using the URLconf defined in myproj.urls, Django tried these URL patterns, in this order: admin/ myproj/ ^static/(?P<path>.*)$ The current path, static/rest_framework/css/bootstrap.min.css, matched the last one. I tried to find the file bootstrap.min.css and found it along this path: /data/Projects/myproj_dev/Django/myproj_venv/lib/python3.8/site-packages/rest_framework/static/rest_framework/css/bootstrap.min.css, but I don’t know what to do with it Unfortunately, I was unable to solve this problem. If anyone knows what to do I would be grateful for advice P.S. Django Newb -
Search functionality using ajax with django
I want to search username in search box.When click on the button submit it should display the matched records without page load.How to implement this in django.Also here is pagination functionality.View is function based.It works fine with page reload.But I want to implement this using ajax call. -
Problem separating the repository into two independent projects on git
I made a mistake at the starting of a project, and that was to write a kivy project and the backend written with django rest in a same folder and repository (meaning the required libraries are both in the same venv too) and now that I want to deploy Django project I do not know how to separate these two projects (which includes libraries) and I do not see any solution. For example, is it possible to create two separate branches for it? And if so, how? And how do I manage and distribute the requirements.txt libraries?(Because the number of libraries is very large and about 200 libraries and the project size is huge. I do not know if more explanation is needed but I am very confused and really need help. Thankful -
python loop until length
so I'm having trouble getting some data to my DB. I'm not that good with python and trying to learn. so this is the data I'm sending to the Django server: as you can see I'm getting FILES called doc[i] to the server and I want to save the name of the file in the DB. but I don't know how to loop through it. that's what I'm doing for now: def submit_quality_dept_application(request, application_id): doc0 = request.FILES['doc0'] length = request.data['length'] application = Application.objects.get(id=application_id) application_state = application.application_state application_state['doc0'] = doc0.name Application.objects.filter(id=application_id).update( application_state=application_state) return Response(length, status=status.HTTP_200_OK) that way it's working for doc0 and I can save its name in the DB. but I want to loop through every doc[i] and save it in DB. any suggestions? -
Retrieve data from models having reverse relationship in django rest
I have 3 models where model A has foreign key of another in reverse order like:- class Book(models.Model): name = models.CharField(max_length=100) img=models.CharField(blank=True) category=models.CharField(max_length=100,null=True) class Section(models.Model): book= models.ForeignKey(Book, related_name='books', on_delete=models.PROTECT) title= models.TextField(null=True) class SubSection(models.Model): section=models.ForeignKey(Section, related_name='sections', on_delete=models.PROTECT, null=True) sub_title= models.TextField(null=True) I am trying to fetch all sections and subsections on the basis of book id. Before I was using nested serializer but nested serializer slow down its response. i am trying to achieve it with select_related can anyone help me with view query and serializer class. I want response like: data=[ "section": "A", "title": "intro", "subsection": [ { "id": 1, "sub_title": "title" } ] ] -
Is there any way to forcibly resize an image to a given dimension in python?
I am using the pillow library. I have an image whose dimension is 1280x1920. When I upload the image, I want to resize the image to 800x600. But after uploading, the image resized to 475x350. Is there any way to forcibly resize the image into the given dimension? This is my code to resize the image in Django: img = Image.open(self.image.path) if img.width > 800 or img.height > 600: img.resize((800, 600), Image.ANTIALIAS) img.save(self.image.path) -
django blog like button error django.urls.exceptions.NoReverseMatch:
am making a django blog and trying to implement a Like button. Anyone got any help/ideas how to get this to work when am adding the code i get some errors. atm i got error: django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. I would really appreciate if someone could help me to get this like button up and runing since i been trying to fix it forever it feels like newsapp folder views.py from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'newsapp/main.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('newsapp:post-list') def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form … -
Django FileResponse Content-Disposition header not working for filename
I use the Content-Disposition header because the stored name of the files is different from the name they are served. But header not working in all files correctly, i'm directly passing filename to header. Filenames contains non-ASCII characters. Here is the download view i'm using: @api_view(['GET']) def download_streamer(request, **kwargs): dlo = DownloadLink.objects.get(token=kwargs['token']) if dlo.is_expired: return Response({'link_expired': 'Download link expired, try again'}, status=status.HTTP_410_GONE) else: mimetype, _ = mimetypes.guess_type(dlo.file_cache.stored_at) f_response = FileResponse(open(dlo.file_cache.stored_at, 'rb'), content_type=mimetype) f_response['Content-Disposition'] = f'attachment; filename={dlo.file_cache.origin.name}' f_response['Access-Control-Expose-Headers'] = 'Content-Disposition' FileActivity.objects.create(subject=dlo.file_cache.origin, action='GET', user=dlo.owner) return f_response Here is the valid response header which i want (file name not containing non-ASCII chars) content-disposition: attachment; filename=jinekolojik aciller.ppt But some files gives this headers (original filename: türkiyede sağlık politikaları.pdf) content-disposition: =?utf-8?q?attachment=3B_filename=3Dt=C3=BCrkiyede_sa=C4=9Fl=C4=B1k_politikalar=C4=B1=2Epdf?= -
Django makemigrations with docker-compose not working. Can't find module
I'm trying to run makemigrations using "docker-compose run makemigrations" after adding pillow to my project but it gives an error saying the "ModuleNotFoundError: No module named 'PIL'". I'm attempting to use pillow to compress uploaded images. Pillow has been added to settings.py and requirements.txt. I have also tried rebuilding the docker image. It also may be worth noting that the error doesn't appear when I run the server using "docker-compose up" Below are snippets of code: docker-compose.yml version: "3.9" services: db: image: postgres ports: - "5432" volumes: - ./data/db:/var/lib/postgresql/data web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db createsuperuser: build: . profiles: ["createsuperuser"] command: python manage.py createsuperuser volumes: - .:/code ports: - "8001" depends_on: - db makemigrations: build: . profiles: ["makemigrations"] command: python manage.py makemigrations volumes: - .:/code ports: - "8002" depends_on: - db migrate: build: . profiles: ["migrate"] command: python manage.py migrate volumes: - .:/code ports: - "8003" depends_on: - db models.py from PIL import Image ... class PropertyPhoto(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE, null=True, related_name="photos") photo = models.ImageField(upload_to=f"static/properties/{property}/photos/", null=True, default=None) def save(self, *args, **kwargs): instance = super(PropertyPhoto, self).save(*args, **kwargs) image = Image.open(instance.photo.path) image.save(instance.photo.path, quality=80, optimize=True) return instance Error when running makemigrations … -
How to build a API web server in Python
I hope you are well. I'm new to Python, I learned the language a while ago and was building mainly console applications. My goal in learning python was to build a web API server. Now that I have learned the language, I want to achieve my goal. But here is the problem, I did some research to know how to build a web API server but there are so many things I discovered like Django, Flask, FastAPI that I as a beginner am lost in the middle of it all and don't know which one to choose and learn. I come back from the JavaScript universe, and there is the Express package/framework which is known as the REFERENCE for building a web API server and I would like to know in the Python universe what is the REFERENCE for building a web API server in terms of functionality, community and other. Can you put me in order in all this? Thanks to you -
Django ratelimiter custom method
how can I put a custom function for the method in django-ratelimit? I want it to be like this: I filled out a form. Then check if the length of the name is less than 5. If the length of the name is less than 5 then as many times as we fill the form it will never block the user. But if the length is bigger every time and he fills the form 5 times then the limiter will block the user from accessing the page. -
django filter empty array in prefetch_related
I used prefetch_related and Prefetch to create a list of areas ( main category), needs (subcategory), and product categories (subsubcategory) for my products. filter_needs = Area.objects.filter(Exists(Need.objects.filter(category_need=OuterRef('pk')))) products = Area.objects.prefetch_related(Prefetch('need_area', queryset=filter_needs, to_attr='need_area__category_need__product')) .filter(need_area__category_need__product__isnull=False).distinct() Right now query renders all areas that contain the product but with all needs (even if there is no product in need). How can exclude all needs that are empty? -
Django Annotation Custom Value
I want to add a new col total_sum to every object of SomeModel. To calculate it I try to use my function calc_total_sum which requires id of the object and some external args. SomeModel.objects.all().annotate( total_sum=Value(calc_total_sum(F('pk'), start_date, end_date), DecimalField()) ) But this query seems to be wrong because then my function receives not value of each pk but just a function F How can I fix it? -
django debugger does not start in vscode
i'm trying to run a django debugger, but here's what happens. from .forms import RegisterUserForm, LoginUserForm, IndexPageForm, OrderTicketForm ImportError: attempted relative import with no known parent package launch.json "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "stopOnEntry": false, "python": "${config.python.pythonPath}", "program": "${workspaceRoot}/manage.py", "args": [ "runserver", "--no-color", "--noreload" ], "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "RedirectOutput", "DjangoDebugging" ] } ] location venv and django project - F:train/venv/ -
<QuerySet []> is returning empty in django
I am trying to create a queryset for getting the values of a DateTimeField which is DATETIME in the DB. The class in models.py: class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created', '-updated'] The class in models.py: class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name in views.py def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all() print(room_messages) context = {'room': room, 'room_messages': room_messages} return render(request, 'base/room.html', context) when i would render room_messages in "room.html" {% block content %} <h1>{{ room.name }}</h1> <p>{{ room.description }}</p> <div class="comment-wrapper"> <h3>Conversation</h3> <hr/> {% for room_message in room_messages %} <small> {{ room_message.user }} {{ room_message.created }} </small> {% endfor %} </div> {% endblock %} i cant see room_messages like that : the messages's page -
django pre_save signals not updating
The last line of the test at the bottom fails. I tried to reduce the code to the essential pieces. The explanation is in the comments for the code. class Concept(model.Model): is_deprecated= Boolean(default=False) ... class Tag(model.Model): concept_tags = ManyToManyField(Concepts, ...) is_deprecated= Boolean(default=False) ... class StatusInfo(model.Model): """the important thing is the pre_save signal""" status = '' affected_tag = ForeignKey(Tag, ...) ... @receiver(pre_save, sender=StatusInfo) def status_change_modification(sender, instance, *args, **kwargs): if instance.status == "d": # d for deprecated instance.affected_tag.is_deprecated = True # works c_tags = instance.affected_tag.concept_tags.all() print(f"{c_tags = }") # when I run the test below this shows that I have included self.concept_with_deprecated_tag c_tags.update(is_deprecated=True) # doesn't seem to work but I don't want to trigger a save() on concepts (referenced through concept_tags) because concepts has it's own signals that will trigger. ##### in the tests/status_info.py ####### def test_status_set_tag_info_deprecated(self): """ if you add the statusInfo to a tag it will set the tag and related concepts to is_deprecated == True """ self.concept_with_deprecated_tag.is_deprecated = False # set temporarily for the test self.assertFalse(self.deprecated_tag.is_deprecated) self.main_status_info = StatusInfoFactory( affected_tag=self.deprecated_tag, status="d", by=self.new_replacement_tag) self.assertTrue(self.deprecated_tag.is_deprecated) self.assertTrue(self.concept_with_deprecated_tag.is_deprecated) # this is one concept from the list and it fails to be changed. -
'AuthenticationForm' object has no attribute 'cleaned_data'
I override a custom django login by importing the AuthenticationForm and using the code below in my views.py but the only problem Im getting is that when i try to clean the form it always gives an error: 'AuthenticationForm' object has no attribute 'cleaned_data'. What should I do to resolve this problem? Here is my views.py for overriding custom django login from django.contrib.auth.forms import AuthenticationForm def auth_login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] username = form.cleaned_data['username'] user = authenticate(username=username,password=password) if user: if user.is_superuser: login(request,user) return redirect('/dashboard') else: login(request,user) return redirect('/') else: messages.error(request,'Username or password not correct') return redirect('/accounts/login') return render(request,'registration/login.html',{'form':form}) -
Check if an image contains a face then add to an image folder
I am working with Django Rest Framework to create a Face Recognition API. I have created a standalone application for Face Recognition using 'face_recognition' library in Python and OpenCV. Now I need to convert this standalone project to an API. In model.py I have created a class named Person Which contains some fields for registering a person like name, email, password, and also an image. The person uploads an image and it gets saved to the media directory. I want to check whether the uploaded image contains a face or not. It should be saved in the media directory if and only if it contains only one face. Otherwise, there should be a message saying "The uploaded image does not contain a face or contains more than one face". I am new to the Django Framework and APIs in general. Any help is greatly appreciated. The codes are as follows: models.py # Create your models here. from django.db import models # lets us explicitly set upload path and filename def upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class Person(models.Model): name = models.CharField(max_length=60, blank=False, null=False) image_url = models.ImageField(upload_to=upload_to, blank=True, null=True) def __str__(self): return self.name serializers.py from rest_framework import serializers from .models import Person class … -
Django testing view with pytest
Could you please helpe me debugging this test? I got this error (I don't know whay since, I have no pk in view): django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.I think the error is due to pk=request.user.id passed as argument in User objects in the view function. class TestViews(TestCase): def setUp(self): self.client = Client() self.create_campaign_naming_tool_url = reverse('create_campaign_naming_tool') self.user = User.objects.create_user( username = 'admin', email = 'admin@sigma.fr', password = '1234' ) def test_create_campaign_naming_tool(self): response = self.client.get(self.create_campaign_naming_tool_url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'form.html') Here is my view def create_campaign_naming_tool(request): current_user = User.objects.get(pk=request.user.id) form = CampaignNamingToolForm(initial={'user': current_user}) context = { 'form': form, } if request.method == 'POST': campaign = CampaignNamingTool(user=current_user) form = CampaignNamingToolForm(request.POST, instance=campaign) if form.is_valid(): form.save() messages.success(request, "Your campaign haven ben\ success fully created.") return render(request, 'form.html', context) return render(request, 'form.html', context) -
How to add files in Django session?
I want to get some files from the user and after getting the files, I want the user should make a payment after payment is done, an order should be created and the files should be stored against that order in the Database. I know how to create an order and store the files in a database. I have used Django's sessions to store the string data. But want to store files also. I have used the following code : In HTML: <form method="POST" enctype="multipart/form-data"> <input type="file" name="filename"> </form> In views.py : if request.method == "POST": request.session['filename'] = request.FILES['filename'] It throws errors as : Object of type InMemoryUploadedFile is not JSON serializable