Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Expire every User after x days of creating in django
I want to expire every user after x days of creating in django Can this possible in django-python? Thanks -
Django sorl.thumbnail
I have problem ModuleNotFoundError: No module named 'sorl' I installed it and tried even again. (env) PS path> pip install sorl-thumbnail Requirement already satisfied: sorl-thumbnail in path\env\lib\site-packages (12.8.0) Django starts with that env activated. Module was installed with env also activated. I tried also to pip install without virtual enviroment. It's also added in Installed_Apps ... 'simple_history', 'widget_tweaks', 'sorl.thumbnail', ] Any tips? 🙄 -
How to take two paramters (start_date and end date) to filter out events in django using query_params.get()?
I want to pass two parameters in GET method in django. The one is start_date and the second is end_date. But I just know about passing only one method. here is my code where I want to filter out account deposit history in range of dates . class BusinessDonationHistoryController(BaseController): view = ListView @entity(Business, arg="business") def read(self, request, response, business): request.query_params.get() #Here I need help deposits = Deposit.objects.filter( business=business, deposit_type=deposit_types.BUSINESS_DONATION) credit_accounts = CreditAccount.objects.filter(deposit__in=deposits) deposit_map = defaultdict(list) # create a mapping of deposit id and associated credit accounts for credit_account in credit_accounts: deposit_map[credit_account.deposit_id].append(credit_account) history = [] for deposit in deposits: history.append({ "date": deposit.created_date, "total_amount": from_cents(deposit.amount), "amount_disbursed": from_cents(sum([ca.total_amount - ca.current_amount for ca in deposit_map.get(deposit.id)])) }) print(history) Checked all the links on StackOverflow but I found nothing relevant. checked this link even -
Criptografia Django/dekstop [closed]
Olá. Estou precisando fazer uma aplicação tanto web como dekstop para o curso que estou fazendo, e ambas as aplicações necessitam utilizar o mesmo banco de dados. Decidi iniciar pela parte Web, utilizando python-django, e criei as tabelas pro banco pelos models mesmo. E para os usuários decidi usar o model do User mesmo. Porém, encontrei o problema para a criação de usuário pela plataforma dekstop, pois não consigo fazer uma criptografia que o django saiba ler, já que pela aplicação desktop não estou utilizando o django. Alguém tem alguma sugestão? -
Django serve a PDF document loaded from Mongodb
I am storing PDF documents in MongoDB; base64 encoded. I want to serve these PDFs from a view function. I'm hoping to eventually embed them into an HTML embed element or Iframe. For now, I'm just trying to get this to work. Similar questions: django PDF FileResponse "Failed to load PDF document." (OP forgot to call .seek on the buffer) Django FileResponse PDF - pdf font changes in frontend - (Django DRF and React.js) (no answer yet) how to display base64 encoded pdf? (answers don't involved Django) Here is my view: def pdf(request, pdf_id): document = mongo_db_client.get_document(pdf_id) # uses a find_one query, returns a cursor on the document pdf = base64.b64decode(document.read()) print(f"pdf type: {type(pdf)}") print(f"pdf length: {len(pdf)}") # We save the PDF to the filesystem to check # That at least that works: with open("loaded_pdf.pdf", "wb") as f: f.write(pdf) # See: https://docs.djangoproject.com/en/4.0/howto/outputting-pdf/ _buffer = io.BytesIO(pdf) p = canvas.Canvas(_buffer) p.showPage() p.save() _buffer.seek(0) return FileResponse(_buffer, content_type='application/pdf') The output of this is that I am able to view the PDF saved to the filesystem and the print output is: pdf type: <class 'bytes'> pdf length: 669764 Now, for one of the PDFs that I have, I can open the URL and view it … -
Ultimate Front-end bootcamp for a Python-Django developer
I have learned a lot about Django and Python making some projects, however I often find myself struglling with front-end part, which is why I wanted to know if there is an ultimate course that could teach all the needed stuff of Front-end (Html, Css, JavaScript and Bootstrap) so that I could become a full stack developer. Thank you! -
ValueError: Content-Type header is "text/html", not "application/json" django python
I am trying to rub a test for one of my views but I keep getting this error raise ValueError( ValueError: Content-Type header is "text/html", not "application/json" Here is the view function def add_to_cart(request): cart = Cart(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) product_qty = int(request.POST.get("productqty")) product = get_object_or_404(Product, id=product_id) cart.add(product=product, qty=product_qty) product_qty = cart.__len__() response = JsonResponse({"qty": product_qty}) return response Here is the URL path from django.urls import path from . import views app_name = "cart" urlpatterns = [ path("add/", views.add_to_cart, name="add_to_cart"), ] And lastly the test def test_add_to_cart(self): response = self.client.post(reverse('cart:add_to_cart'), { "productid": 3, "productqty": 1, "action":'post', }, xhr=True) print(response.status_code) self.assertTrue(response.json(), {'qty':4}) response = self.client.post(reverse('cart:add_to_cart'), { "productid": 2, "productqty": 1, "action":'post', }, xhr=True) self.assertTrue(response.json(), {'qty':3}) -
How to deploy elasticsearch dsl in aws ec2?
Am trying to deploy elasticsearch dsl django app in aws ec2 but I have certain questions? there is a command python manage.py search_index --reload what should i need to do with this. It needs to run in background whenever i update my databse or export microservice. -
i want to scan out text from an image passed in a django form to tesseract ocr in views.py and pass result to html template
iam using django framework and i want to scan out text from an image passed in a form to tesseract ocr in views.py and pass result to html template. Iam still challenged on how to read this image from the form without sending it to the database. I request for your assistance iam using django 4.0.2 in a virtual environment my python version is 3.10.2 My forms.py from django import forms class uploadform(forms.Form): first_name= forms.CharField(max_length=100) image= forms.ImageField(max_length=100) My html template {% extends 'hm.html' %} {% block content %} <br> <h1>Here you are able to make Uploads</h1> <form class="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} {{text}} <button type="submit" name="button" class='btn btn-primary'>Upload your image</button> </form> <p>{{imge}}</p> {{k}} {{h}} {% endblock %} My urls.py file is from django.contrib import admin from django.urls import path, include from scannerapp import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',views.home_view,name='home'), path('new/',views.upload, name="uppath"), ] if settings.DEBUG:#This is just for development purposes, dont use it in production urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) my views.py from django.shortcuts import render, redirect from django.http import HttpResponse,JsonResponse from django.views.generic import FormView from .forms import uploadform from django.views.decorators.csrf import csrf_exempt from django.core.files.storage import FileSystemStorage import json import pytesseract from PIL … -
Empty row in Mysql table when i inserted data from the HTML form
username=request.GET.get('username') password=request.GET.get('password') Email=request.GET.get('Email') conform_password=request.GET.get('conform_password') mySql_insert_query = """INSERT INTO loginapp_loginuser ( email, username,pasword,conform_password) VALUES ( Email,username, password, conform_password) """[enter image description here] [1] I am getting empty data instead actual data in row i don know what is the problem with my code, please review it once and give me the feedback, thank you for your support [1]: https://i.stack.imgur.com/Fteyj.png -
How to solve response 405 error in Python Requests?
I am creating a project with Django. I want to post a file and a parameter (sector) with python-requests. I created a function for that but I cannot add a parameter. Here is my code: def mytestview(request): form = PDFTestForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): pdf = form.save() file_address = ("C:/fray/otc/"+pdf.pdf.name) url = 'https://api.myaddress.com/pdf' files = {'bill': open(file_address, 'rb')} values = {'bill': file_address, 'SectorInfo': {'code': "A", 'name': "Tlk"}} r = requests.put(url, files=files, data=values, headers={'Authorization': 'Bearer access_token'}) print(r) # <Response [405]> else: messages.error(request, 'Please, upload a valid file.') context = { 'form': form } return render(request, 'testthat.html', context) //PUT Swagger Look: { "sectorInfo": { "code": "string", "name": "string" }, "bill": { "id": 0, "name": "string", "size": 0 }, } Note: When I used POST instead of PUT, still gives the same error. -
Category and Subcategories OPT Group select in Django
I have two three models: Announce Category Subcategory This is my form.py # Formulaire de la depose d'une annonce class AnnonceForm(forms.ModelForm): title = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Titre de mon annonce'})) category = forms.ModelChoiceField(queryset=Souscat.objects.all(), empty_label='Selectionnez une categorie', label="", help_text="", widget=forms.Select(attrs={'class': 'form-control'})) class Meta: model = Annonce fields = ('title','category') And this is my models: # Catégories class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=True, unique=True) created_date = models.DateTimeField(default=timezone.now) class Meta: verbose_name = "Catégorie" verbose_name_plural = "Catégories" def __str__(self): return self.title # Sous catégories class Souscat(models.Model): category = models.ForeignKey(Category, related_name="s_category", on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField(null=True, unique=True) created_date = models.DateTimeField(default=timezone.now) class Meta: verbose_name = "Sous catégorie" verbose_name_plural = "Sous catégories" def __str__(self): return self.title On my annouce, i will get only subcategories, but on my select i want to show the categories and the subcategories can be selectable. I have see this is possible with "optgroup", but i have successfull get all the subcategories on my but, i want to show the categories (not selectable) in my select with the subcategories (selectable). For have the category i make simply {{ form.category }} How can i make this ? Thank you -
How to upload a file in Django and get other file in response
i have a task to do and task description is : The user uploads an excel file and then this file is sent via request and received in response an excel file and pdf file. i have problem to write views function what the best way to do this task? -
make a new django model that looks like a list
I want to add a model, but I don't get it working. my models.py class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id now i would like to have a model that would be kind of a list. so in there i would like the article_id and search_id. so i can access all articles that were found with the search_id=''. Or i could find in which searches a particular article would appear. How should the model look like? -
Django form's not valid
This question might be asked alot in stackoverflow but i couldn't find the answer. Take a look at code: # models.py class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.CharField(max_length=200, null=True, blank=True) room = models.ForeignKey(Room, on_delete=models.CASCADE, blank=True, null=True) posted = models.TimeField(auto_now_add=True) def __str__(self): return self.body views.py: class RoomInsideView(View): template_name = 'room/room_inside.html' form_class = SendMessageForm room = None def get(self, request, room_id, room_slug): self.room = Room.objects.get(id=room_id) if self.room.is_private: return redirect('room:private_room_auth', self.room.id) form = self.form_class() context = { 'room': self.room, 'form': form, } return render(request, self.template_name, context) def post(self, request, room_id, room_slug): form = self.form_class(request.POST) print(request.POST) if form.is_valid(): new_msg = Message(body=form.cleaned_data['body']) new_msg.user = request.user in all_messages = Message.objects.filter(room=self.room) messages.error(request, 'form not valid', 'warning') return render(request, self.template_name, {'form': form, 'message': all_messages}) forms.py: class SendMessageForm(forms.ModelForm): class Meta: model = Message fields = ('body',) widgets = { 'body': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Send'}), } template: <form method="post" action="" novalidate> {% csrf_token %} {{ form.non_field_errors }} {{ form.body.errors }} {{ form.body }} <input type="submit" value="Send" class="btn btn-primary"> </form> as I added a messages.error if form is not valid it's returning form not valid and I can't find where am I doing wrong -
i want to execute INSERT query in Django project without touching Models.py
i don't want to make table in my models.py as my database is very large and want to perform a INSERT query in it.it is possible to perform this without touching models.py. please help me if you have any idea. sorry for any mistakes, thanks in advance. -
django-storages dropbox - SuspiciousFileOperation
I try to upload a picture in Django-Admin, without success. I made a minimal app with basic informations, but it fails when I want to upload the ImageField to the server (storage on Dropbox). I installed django-storages, and here is my settings : DROPBOX_OAUTH2_TOKEN = "my_token_here" DROPBOX_ROOT_PATH = 'storage' My model : class Picture(BaseModel): title = models.CharField(max_length=80, default='', blank=True) description = models.TextField(default='', blank=True) image = models.ImageField(blank=True, null=True) I get the following error : SuspiciousFileOperation at / Detected path traversal attempt in '/home/me/Code/my-project/storage/my_image.JPG' Environment: Request Method: POST Request URL: http://127.0.0.1:8001/admin/gallery/picture/add/ Django Version: 4.0.2 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gallery'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1670, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File … -
How to prevent user login from multiple devices in Django?
I am facing issue in Django, I want to prevent multiple device login in Django, I am creating custom session and setting True & False when user is login or logout. When i am closing browser still it is in True state in back-end , I want to update it on browser close. Any ideas how to solve it in a best way. -
How to send partial status of request to frontend by django python?
Suppose, I have sent a post request from react to Django rest API and that request is time taking. I want to get how many percentages it has been processed and send to the frontend without sending the real response? -
Unable to filter products by category. Categories do not show when clicked Django
I am trying to filter listings/products by categories, clicking on the name of any category should take the user to a page that displays all of the listings in that category. When I click on the Category tab, it displays the names of the categories that have been listed but it does not show any listing/products attached to that category. I have implemented this so far and would like help knowing why I am having this error. URLS.PY path("category", views.all_category, name="all_category"), MODELS.PY class Category(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, max_length=12, null=True, blank=True, on_delete=models.CASCADE) LAYOUT.HTML <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Active Listings</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'all_category' %}">Category</a> {% for category in categories %} <a class="nav-link" href="{% url 'all_category' %}?category={{ category.name}}">{{ category.name}}</a> {% endfor %} </li> VIEWS.PY def all_category(request): categories = Category.objects.all() category = request.GET.get('category') if category == None: products = Auction.objects.all().order_by('-created_at') else: products = Auction.objects.filter(category__name=category) context = {'categories':categories, 'products':products} return render(request, 'auctions/layout.html', context) I also tried implementing this but this seemed worse off as it … -
Registration or login as a user of project in django framework
I'm new to django framework.i've already familiar with php.In php if I need to register as admin or user.. I've just create a table for admin or user and register them via SQL queries but it's blind for me dive into django..Django has already have some tables like django.admin.log , django.user like that ,is there any table existing for admin or user? Can I use those tables for my project as a admin or register login? Please clarify about it, -
OIDC Redirect URI Error in Dockerized Django
I'm running two applications using docker-compose. Each application has a bunch of containers. The intention is for App A (django app) to host the OIDC provider, while App B (some other app) will authenticate users by calling the App A API. I'm using the django-oidc-provider library (https://django-oidc-provider.readthedocs.io/en/latest/index.html) I've already configured the OIDC integration on both sides. However, every time App B redirects to App A, I hit the following error: Redirect URI Error The request fails due to a missing, invalid, or mismatching redirection URI (redirect_uri). Even though the redirect_uri matches exactly on both sides. Here's my docker-compose.yml: version: '3' networks: default: external: name: datahub-gms_default services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: dqt container_name: dqt hostname: dqt platform: linux/x86_64 depends_on: - postgres volumes: - .:/app:z environment: - DJANGO_READ_DOT_ENV_FILE=true env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/local/postgres/Dockerfile image: postgres container_name: postgres hostname: postgres volumes: - dqt_local_postgres_data:/var/lib/postgresql/data:Z - dqt_local_postgres_data_backups:/backups:z env_file: - ./.envs/.local/.postgres broker: container_name: broker depends_on: - zookeeper environment: - KAFKA_BROKER_ID=1 - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092 - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 - KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0 - KAFKA_HEAP_OPTS=-Xms256m -Xmx256m hostname: broker image: confluentinc/cp-kafka:5.4.0 ports: - 29092:29092 - 9092:9092 datahub-actions: depends_on: - datahub-gms environment: - GMS_HOST=datahub-gms - GMS_PORT=8080 - … -
Django / Bootstrap forms - Input size - Python
I'm learning Django together with Bootstrap (5.1.3), and I'd like to keep my code as simple as possible for future updates. That's why I went for generic views in Django (Create/Detail/Edit...). That works great, all the features work seamlessly now. What I'm struggling with is the layout of my Edit / Create forms. I can't find a way to increase the size of the input boxes. I have the following code, for my Model: class customer(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False, verbose_name = u"Créé le") modified_date = models.DateTimeField(auto_now = True, editable = False, verbose_name = u"Modifié le") fk_referrer = models.ForeignKey('customer', on_delete=models.CASCADE, verbose_name='Parrain', blank = True, null=True) surname = models.CharField('Prénom', max_length=200) lastname = models.CharField('Nom', max_length=200) phonenumber = PhoneNumberField('Téléphone', blank = True, null = True) email = models.EmailField('Email',max_length=100, blank = True, null = True) fk_interest = models.ManyToManyField(interests, verbose_name='Interêts', blank=True) comments = models.TextField('Commentaires', max_length=2000, blank=True, null = True) def __str__(self): return (self.surname + " " + self.lastname) I did create a generic view: class CustomerEditView(UpdateView): model = customer fields = "__all__" template_name = 'client/edition.html' success_url = '/client/' And have added the form in edition.html template: <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> … -
Count common ManyToMany members in queryset
Assuming I have such models: class Bar(models.Model): pass # some simple Model goes here class Foo(models.Model): bars = models.ManyToManyField(Bar) And some variable main_object = Foo() with bars filled, how can I make a Queryset so that it's annotated with the number of common bars elements betweeen each entity and main_object? Example: There are three Bar records, with primary keys 1, 2 and 3. main_object has pk=2 as member set in bars. Foo has two records: main_object and another with pk=1 set in bars. In this case, I want an annotation that has the value of 0, since said record has no common Bar foreign keys with main_object. I can imagine something similar to Foo.objects.filter(bars__in=<some_values_here>) but instead of simply checking presence, actually counting it like from django.db.models.Count. Is it even solvable via Querysets or I should resort to manual counting through loops? In practical use, such way of querying can be useful in similarity ranking, but it seems non-trivial for me. -
how to order Django query based on the sum of a specific field grouped by another field?
how to order Django query based on the sum of a specific field grouped by another field? The Model is simply recording goals that players score, every player has many inputs that each refers to a single goal. I'm trying to find out the top 3 scorers with the highest amount of goals scored. Here is my model : class Goal(models.Model): match = models.ForeignKey(Match,on_delete=models.CASCADE) date_time = models.DateTimeField() team = models.ForeignKey("teams.Team",on_delete=models.PROTECT,null=True,blank=True) player = models.ForeignKey('players.PlayerProfile',related_name="goal_maker",on_delete=models.PROTECT,null=True,blank=True) assistant = models.ForeignKey('players.PlayerProfile',related_name="goal_assist",on_delete=models.PROTECT,null=True,blank=True) Now what I want to do is to group it by player field ordering it from the highest player with goals to the lowest one What I have tried I have tried to loop trough all my database entries for this model Goal.objects.all() and check if it is the same player I do +=1 if not I create a new entry, and that is surly not the best way do achieve this.