Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter query through an ID in Django
I know this is a common to ask but I'm just confused, what is the best way to filter data from one table to another table, the case is I want to filter the name of category1 and category2 table through an ID based on the image shown below, It's very helpful for me to use this kind of implementation. It same like this Select title ,description, category1_tbl.name, category2_tbl.name from main_tbl....... JOIN TWO TABLES views.py task_tbl.objects.get(category1_id=category1_tbl.objects.get(id)) -
Django showing Zen Poetry every time on running server
vscode-screenshot I am pretty sure everything is in order but it keep showing this poetry upon running the server or refreshing the server (by saving python file). Please help, this is annoying. -
Error accesing reverse manytomany field from user to onetoone related model
Im having trouble with a model classs which has a onetoone relation with the User model, this the conflictive part: class UserInteraction(models.Model): user = models.OneToOneField(User, related_name="interactions", on_delete=models.CASCADE) users_follows = models.ManyToManyField('self', through='UserFollow', blank=True, symmetrical=False, related_name='user_follows') users_likes = models.ManyToManyField('self', through='UserLike', blank=True, symmetrical=False, related_name='user_likes') When I try to get the follows/likes by doing user.interactions.user_follows or user.interactions.user_likes I get the following error: In [18]: u = User.objects.get(id=1) In [19]: u.interactions.users_likes.all() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [19], in <module> ----> 1 u.interactions.users_likes.all() File ~\...\django\db\models\fields\related_descriptors.py:536, in ReverseManyToOneDescriptor.__get__(self, instance, cls) 533 if instance is None: 534 return self --> 536 return self.related_manager_cls(instance) File ~\...\django\db\models\fields\related_descriptors.py:826, in create_forward_many_to_many_manager.<locals>.ManyRelatedManager.__init__(self, instance) 824 self.prefetch_cache_name = rel.field.name 825 self.source_field_name = rel.field.m2m_field_name() --> 826 self.target_field_name = rel.field.m2m_reverse_field_name() 827 self.symmetrical = rel.symmetrical 828 else: File ~\...\django\db\models\fields\related.py:1598, in ManyToManyField._get_m2m_reverse_attr(self, related, attr) 1596 setattr(self, cache_attr, getattr(f, attr)) 1597 break -> 1598 return getattr(self, cache_attr) AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' Here is the follower and like models used for through in the fk: class UserFollow(TimeStampBase): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') followed = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followed') class Meta: constraints = [ models.UniqueConstraint( name="%(app_label)s_%(class)s_unique_relationships", fields=["followed", "follower"], ), models.CheckConstraint( name="%(app_label)s_%(class)s_prevent_self_follow", check=~models.Q(follower=models.F("followed")), ), ] def __str__(self): return f'{self.follower} follows {self.followed}' class UserLike(TimeStampBase): liker = models.ForeignKey(User, on_delete=models.CASCADE, … -
Get full path excluding the file extension in regex from python [duplicate]
To get the absolute file path without extension, e.g. /home/alice/hello.cpp -> /home/alice/hello I came up with re.findall(r'[^\/]+(?=\.)', file_path) but it is not working file_path = "okok/okok.okok.okok/okokok.mp3" so the result should be "okok/okok.okok.okok/okokok" -
Django Tastypie: viewing schema gets 401 Unauthorized error
I've inherited a Django project that used v0.12.1 of django-tastypie to create an API, I have updated it to use v0.14.4, and am trying to get the new site to work the same as the previous. The API Resources use DjangoAuthorization and while I can mostly* read list and details of them OK, if I try to read an api/<model>/schema/ URL I get a "401 Unauthorized" error. I should be able to view the schema whether I'm logged in or not, which was the case on the previous site. I've noticed that the DjangoAuthorization.read_detail() view is called when I try to view a schema, and that the object_list property of the passed-in bundle is None. I'm not sure if this is the cause or, if so, how to get around it. How can I continue to use DjangoAuthorization, allow anyone to view an endpoint's schema, and not change any other permissions? * There seem to be several other issues/differences with just viewing objects' data through the API, but those are probably questions for another time. -
Filtrar a traves de una lista de otro objeto Django Rest
Dado los siguientes modelos Models.Py class PurchaseRequest(models.Model): grupo_aprobador = models.ManyToManyField(settings.AUTH_USER_MODEL) ### Mas campos ### class PurchaseApproval(models.Model): usuario_aprobador = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) purchase_request = models.ForeignKey(PurchaseRequest, on_delete=models.RESTRICT) ### Mas campos ### Views.py class PurchaseApprovalViewSet(viewsets.ModelViewSet): permission_classes = [DjangoModelPermissions] serializer_class = PurchaseApprovalSerializer def get_queryset(self,pk=None): if pk is None: user = self.request.user return self.get_serializer().Meta.model.objects.filter(purchase_request__grupo_aprobador=user) return self.get_serializer().Meta.model.objects.filter(id=pk).first() Intente esto pero no funciono. Lo que quiero hacer es si un usuario, ha sido agregado al grupo aprobador, que a este solo le aparezcan los purchase request a los que el debe aprobar. -
Getting error while running heroku run python manage.py migrate
I am a beginner in heroku and django and I am trying to create an application. While I was importing my database to heroku by running command - heroku run python manage.py migrate I get an error saying - Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 87, in wrapped saved_locale = translation.get_language() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 182, in get_language return _trans.get_language() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 50, in __getattr__ if settings.USE_I18N: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 84, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 71, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 179, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'pp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line … -
Django admin TabularInline group by query
I have a TabularInline class, StockPartInlines in the inline form view I am trying to GROUP based on two fields (container_id, expiration_date) and add an additional field that is a SUM of an existing field. class Stock(models.Model): part = models.ForeignKey(Part, on_delete=models.PROTECT, related_name='stock') container = models.ForeignKey(StorageContainer, on_delete=models.PROTECT, related_name='items', null=True) quantity_change = models.IntegerField(default=0) expiration_date = models.DateField(blank=True, null=True) class PartAdmin(admin.ModelAdmin): inlines = [StockPartInlines] class StockPartInlines(admin.TabularInline): model = Stock fields = ['container', 'expiration_date', 'quantity'] readonly_fields = ['quantity'] def quantity(self, obj): return obj._quantity The equivalent SQL statement would be; SELECT part_id, container_id, expiration_date, SUM(quantity_change) FROM inventory_stock WHERE part_id = part_id GROUP BY container_id, expiration_date; I have tried to get this to work by overriding the 'get_queryset()' method of StockPartInlines def get_queryset(self, request): qs = super(StockPartInlines, self).get_queryset(request) .values('container','expiration_date') .order_by('container') .annotate(_mwa=Sum('quantity_change')) return qs This has been returning an error of 'dict' object has no attribute '_meta', traceback. I believe this is because using .values() in a queryset returns a queryset of dicts rather than a queryset of objects. Is there a different approach I could take to display the results of this query as an inline form in the admin panel? -
Is there a readily available web based GUI file manager
my org is building a web app and a huge part of it requires a web file manager UI for people to upload, view, download, store and manage their uploaded documents. A preview function of docx and pdf is particularly valuable. The UI should preferably feel like a Mac or Windows File explorer, and on mobile, feel like the iOS/Android file manager. It should support multiple uploads and downloads. Our working idea is to setup one folder for each user, using flask to handle the upload this tutorial. For GUI file management, use bootstrap-flask to connect to a bootstrap file manager template, like this one. Another idea floated around is to use a database (MongoDB gridFS/postgres large object) to store the documents directly. Boss thinks storing a file in a DB is more secure than just storing them "openly" in folders. I tend to disagree but I cannot point to any concrete justifications. Additionally, I think listing out a folder's content is easier (and probably there is a flask extension somewhere) than querying a DB and parsing the results for the front-end to consume. We suspect that the great programming community must have developed something similar and that we can … -
Django form selection affect raising another form
I wana make form on add_form.html, where first appear selection of curve type and than the right form.So somehow link them together on one page. For example user choice: Static cyclic and under this form appears CyclicCurveForm. Thanks for help. models.py: class CyclicCurve(models.Model): name = models.CharField(max_length=200, unique=True) K = models.FloatField(max_length=200) n = models.FloatField(max_length=200) comment = models.CharField(max_length=1000) material_id = models.ForeignKey(Material, on_delete=models.CASCADE) def __str__(self): return self.name class EnCurve(models.Model): name = models.CharField(max_length=200, unique=True) Sf = models.FloatField() b = models.FloatField() c = models.FloatField() Ef = models.FloatField() comment = models.CharField(max_length=1000) material_id = models.ForeignKey(Material, on_delete=models.CASCADE) forms.py: class CurveForm(forms.Form): RELEVANCE_CHOICES = ( (1, ("Static cyclic")), (2, ("En fatigue")) ) type = forms.ChoiceField(choices=RELEVANCE_CHOICES, required=True) class CyclicCurveForm(ModelForm): class Meta: model = CyclicCurve exclude = ['material_id'] class EnCurveForm(ModelForm): class Meta: model = EnCurve exclude = ['material_id'] add_form.html: {% extends "main/base.html" %} {% block title %} Create {% endblock %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type=button value="Previous Page" onClick="javascript:history.go(-1);"> <input type="submit" name="Submit"> </form> {% endblock %} views.py: ### CREATE/ADD/EDIT CURVE ### def create_curve(response, material_type_id, material_id): form = CurveForm() if response.method == "POST": form = CurveForm(response.POST) if form.is_valid(): curve_type = form.cleaned_data ..... context = {"form": form, "material_type_id": material_type_id, "material_id": material_id} return render(response, "main/add_update_form.html", context) -
Django form: visibly group or separate fields
I have a form that I'm displaying within a Django app. This form has a number of fields. To make the UI more intuitive, I would like to display the fields not simply one after the other, but instead grouped into sections - be it within a box or by separating the sections with a horizontal line or larger spacing or custom text etc. My main interest is having the subgroups visibly separated from each other. Being able to use some text (basically a label without an attached field) as section devider would be a welcome bonus. How can I achieve this? Current example code: forms.py: from django import forms class MyForm(forms.Form): color1 = forms.CharField() items_color1 = forms.CharField() # some devider here color2 = forms.CharField() items_color2 = forms.CharField() mypage.html: <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit" id="form_field" name="submit_btn"></td> </tr> </table> (I'm pretty new to Django. My previous GUI experience is mainly with PyQt5.) -
Django form DateInput: change date format from mm/dd/yyy to dd/mm/yy
I'm trying to change the default format of the date from mm/dd/YYYY to dd/mm/YYYY, but even adding a custom format (format="%d/%m%/%YYYY") the result doesn't change. date = forms.DateField(initial=timezone.now(), widget=DateInput(attrs={'class': 'datepicker'}, format="%d/%m/%Y"), label="Data", error_messages=MY_DEFAULT_ERRORS) -
Django - AttributeError: 'tuple' object has no attribute 'name'
I am trying to make an e-commerce website where the "AnonymousUser" or Guest user can order and check out items without the need to login or make their accounts. What I want to do is throw the name and email that was entered in check out form to the database. But it always returned blank in the Customer Table. And after making the payment, there was an error that says AttributeError: 'tuple' object has no attribute 'name' Here's the full traceback in Terminal: Internal Server Error: /process_order/ Traceback (most recent call last): File "C:\Users\RolfShin025\Desktop\E-COMMERCE\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\RolfShin025\Desktop\E-COMMERCE\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\RolfShin025\Desktop\E-COMMERCE\WannaCome\store\views.py", line 82, in processOrder customer.name = name AttributeError: 'tuple' object has no attribute 'name' I also have some error in the console that says: `POST http://127.0.0.1:8000/process_order/ 500 (Internal Server Error)` and `Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0` Here's my models.py file: from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = … -
Connection of Vue and Python script - creation of interactive map
I have a frontend based on Vue.js, where users input the coordinates (lat and lang). This Vue js front end is connected with Django with REST API. Now, I know how to add or remove these lat and lang data sets from DB. Separately I have a Python script, which is generating the route (using HereAPI). How can I pass the data from Vue js exactly to the Python variable, coord = [[..., ...],[..., ...]] launch the Python script and then show the output of the script, the map itself back to the frontend? I expect, it could be done with a kind of POST/GET env. variables. Any advice is appreciated. -
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.