Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display bootstrap element in django-forms
I want to use an element of a bootstrap template in my django-form: It's html code looks like this: What approach should I take to load this element in my form using django? So far I have tried this: 1.- Define field: CHOICES = [('1', 'First'), ('2', 'Second')] selector = forms.ChoiceField( required=False, label= "Select software products", choices=CHOICES, widget = forms.TextInput( attrs= { 'class': 'choices', 'role': 'combobox', 'data-type': 'select-multiple' } ) ) 2.- Add to layout: self.helper.layout = Layout( Row(Div(Div('selector'), css_class='form-group')) ) The result is a regular input field: In other elements I just put the css class and it works perfectly but I can't figure out how to do it in more complex objects. Thank you in advance!! -
How to run multiple commands in python os.system?
I tried to run this command by os.system, this command should run a virtual environment first then, it will run the Django server: import os os.system(''' .\\match_pyinstaller\match_project\\venv\\Scripts\\activate python .\match_pyinstaller\match_project\manage.py runserver ''') what is happening is that the command runs with no error raised "Process finished with exit code 0" to ensure that the command works properly, I removed the first line that refers to Venv and tried to run the command again and it traced back by "No Module Name ...." which means that it works fine however, the server doesn't open so, why? -
How to edit help_text of a child in the parent class
I made a mixin (same as the parent class) for my brand model, and I want to get the class name of the children and replace it with help_text in the parent class. Is there any solution? class TitleSlugMixin(models.Model): title = models.CharField( _('title'), max_length=255, help_text=_(f'{self.__class__.__name__} title.') ) class Brand(TitleSlugMixin): ... -
Accessing index in Django template under a for loop
#views.py . . . detailedStatement = { 'selectedOption1' : '90 degrees', 'correctAnswer1' : '180 degrees', 'selectedOption2' : 'angle', 'correctAnswer2' : 'side' } #Above dictionary contains 200 elements diction = { 'detailedStatement' : detailedStatement } return render(request, "result.html", diction); So while on an html file I wanted to access the dictionary's every element via a loop. Like every element should be listed in the html table row like following. | Sr | Selected Option | Correct Answer | | 1 | 90 degrees | 180 degrees | | 2 | angle | side | Above table is just a representation of html table not an actual table. But the issue I am facing is... I am not able to access its index in a dynamic way. I wrote a for loop in Django html template but {% for dr in detailedResult.items %} <tr> <td>{{forloop.counter}}</td> <td>{{dr.option.forloop.counter}}</td> <td>{{dr.answer.forloop.counter}}</td> </tr> {% endfor %} I want my code to automatically put 1 after option and answer like option1, answer1; How can we do this? -
Django prefetch only latest object of related model
Consider the following models: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, related_name="books", on_delete=models.CASCADE) title = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) And the following code: queryset = Author.objects.all() for author in queryset: print(author.name) print(author.books.latest("created_at").title) The above causes an N+1 query as expected. I tried fixing it by prefetching the books like so: queryset = Author.objects.prefetch_related('books') However, this does not resolve the N+1 issue. I think the reason is the prefetch does a SELECT * FROM book WHERE author_id IN (1,2,...) which is different from the query performed by the call to .latest(), i.e. SELECT * FROM book WHERE author_id = 1 ORDER BY created_at DESC LIMIT 1. The prefetch does an IN and .latest() does an =. I have also tried the following without success: queryset = Author.objects.prefetch_related(Prefetch('books', queryset=Book.objects.order_by("-created_at"))) What should the prefetch look like in order to avoid N+1 selects when using .latest()? -
Attribute remains after model object is deleted
When a customer adds a product item to the cart, the cart displays the items and cartItems and everything stays how it's supposed to but when someone deletes the actual product from the Product list, items gets deleted too how it's supposed to, but cartItems or the quantity of the products that was added remains after the product doesn't exist, I'm trying to delete that when the Product doesn't exit! The current code throws me this error, list indices must be integers or slices, not str Model class Order(models.Model): ... @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0) Utils def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} #cart prints out this structure '{"15":{"quantity":1}}' print('Cart:', cart) items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False} cartItems = order['get_cart_items'] for i in cart: try: cartItems += cart[i]["quantity"] product = Product.objects.get(id=i) total = (product.final_price * cart[i]["quantity"]) order['get_cart_total'] += total order['get_cart_items'] += cart[i]["quantity"] item = { 'product':{ 'id':product.id, 'name':product.name, 'final_price':product.final_price, 'image_URL':product.image_URL, 'availability':product.availability, }, 'quantity':cart[i]["quantity"], 'get_total':total, } items.append(item) except: pass # clear cartItems if Product does not … -
Is there a way of saving a PDF received as a string to pdf file using ContentFile?
A HttpResponse is providing me with a pdf as a string (according to the developer who set it up it's supposed to come as a "JSON byte array") but when I check the type in python it's a string. How do I save this as a pdf file using the "FileField" model field on a django model? The previous developer to work on this has written simply - file_object=ContentFile( azure_download["Attachment"], azure_download["OriginalFileName"] ), Where the "Attachment" key gives the pdf as a string and the "OriginalFileName" is a string. Is this correct? The reason I ask is when I attempt to view the pdf in the browser (which has been stored in AWS S3) the screen is blank - the console shows the reason is the pdf is corrupted. Does this point to a bad string coming from the api or is there something wrong with the code? -
Django link text too long
In my detail view in my Django app I show links to all attached files in the Post. Problem is, if link is too long it goes beyond border. Is it possible to show only part of link if it's too long or to limit the 'preview', not to edit the link. code: {% for i in post.file_set.all %}<p class="article-content mt-2 mb-1"><strong>Privitak prijave {{ forloop.counter }}: </strong><a href="{{i.file.url}}">{{i.file.name}}</a></p>{% endfor %} -
Sending the data saved in the database in the Django project to an e-mail address
First of all, I'm new to this and I want to do something like this. I want to filter the database records in my project that I created with Django and send them to an e-mail address in a certain format. I have no idea how to do this, can you help me with this? -
How can I transfer my request in the test for this service? [closed]
I need to create my own request, maybe mock. How can i do this? -
Web Sockets failing connection / Django Channels
The problem is, it Used to work.. And then i decided to change my frontend css framework, and then it stopped working. even though the code is the exact same. my asgi.py file from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import apps.conversation.routing as conversation_routing import apps.twikkerprofile.routing as core_routing import apps.feed.routing as feed_routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'twikker.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( conversation_routing.websocket_urlpatterns + core_routing.websocket_urlpatterns + feed_routing.websocket_urlpatterns ) ) }) My routing.py files all follow this pattern: from django.urls import path from apps.feed import consumers websocket_urlpatterns = [ path('ws/tweek/', consumers.TweekConsumer.as_asgi()), path('ws/like/', consumers.LikeConsumer.as_asgi()), ] The websockets declaration in the frontend: const tweekSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + 'tweek/' ); const likeSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + 'like/' ); And the errors I get in the console: Edit: When I start the server, this is what I get System check identified no issues (0 silenced). October 24, 2022 - 11:37:50 Django version 4.1.2, using settings 'twikker.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. But I guess it should be Starting ASGI/Channels, doesnt it? -
How to Django queryset annotate True when all BooleanField of related objects are True else False?
I have a model who looks like this : class Test(models.Model): user = models.ForeignKey('users.CustomUser', models.CASCADE) name = models.CharField(max_length=64) class TestVersion(models.Model): test = models.ForeignKey('Test', models.CASCADE) name = models.CharField(max_length=255) validation_1 = models.BooleanField(default=False, editable=False) validation_2 = models.BooleanField(default=False, editable=False) validation_3 = models.BooleanField(default=False, editable=False) validation_4 = models.BooleanField(default=False, editable=False) Sometimes i have like hundreds of TestVersion linked to a Test. And I want something like : user_test = Test.objects.filter( user=request.user ).annotate( number_of_test=Count('testversion', distinct=True), all_validation_1="True or False ?", # if all testversion_set.all() of the current test are True, return True else False. all_validation_2="True or False ?", # same all_validation_3="True or False ?", # same all_validation_4="True or False ?", # same ).distinct() # I Want for example : test_1 = user_test.first() test_1_validation_1 = test_1.testversion_set.all().count() test_1_validation_1_true = test_1.testversion_set.filter(validation_1=True).count() all_validation_1 = test_1_validation_1 == test_1_validation_true test_1.all_validation_1 == all_validation_1 # True # Or something like : test_1 = user_test.first() all_validation_1 = all(test_1.testversion_set.all().values_list('validation_1', flat=True)) test_1.all_validation_1 == all_validation_1 # True I have not been able to find what techniques were used to achieve this level of accuracy with related objects in annotate method. Any ideas ? Thank's -
Django dj-rest-auth does not set cookie despite JWT_AUTH_REFRESH_COOKIE
I have a simple Django app managing user autentication and registration with dj-rest-auth and JWT. Accorging to the docs, I have set the the app to use JWT with the plugin simple-jwt with settings.py: JWT_AUTH_COOKIE = 'my-app-auth' JWT_AUTH_REFRESH_COOKIE = 'my-refresh-token' Expected behaviour: Cookies should be set on /dj-rest-auth/login/ and /token/refresh Issue: Cookies are set correctly ONLY on /dj-rest-auth/login/, but not on /token/refresh. This issue is not something new, since it is supposed to be solved here and here. So, I also added the suggested middleware. Here my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ] } REST_USE_JWT = True JWT_AUTH_COOKIE = 'my-app-auth' JWT_AUTH_REFRESH_COOKIE = 'my-refresh-token' 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', 'auth_app.middleware.MoveJWTRefreshCookieIntoTheBody' ] and my urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import include, url, re_path from auth_app import views # JWT CONF from rest_framework_simplejwt.views import ( TokenRefreshView, TokenVerifyView, ) from dj_rest_auth.registration.views import VerifyEmailView, RegisterView from dj_rest_auth.views import PasswordResetConfirmView from allauth.account.views import confirm_email urlpatterns = [ path('admin/', admin.site.urls), path('token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('token/refresh/', TokenRefreshView().as_view(), name='token_refresh'), path('api/protected/', views.ProtectedView.as_view(), name='protected_view'), path('api/open/', views.OpenView.as_view(), name='open_view'), # dj-rest-auth common path('dj-rest-auth/', include('dj_rest_auth.urls')), # dj-rest-auth registration path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), path( 'rest-auth/password/reset/confirm/<slug:uidb64>/<slug:token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm' ), ] … -
Django. How to reduce the number of database hits?
Please tell me how can I reduce the number of requests, I will attach the code below: models.py class Post(models.Model): .... @property def views_count(self): return PostViews.objects.filter(post=self).count() class PostViews(models.Model): IPAddres= models.GenericIPAddressField(default="111.222.333") post = models.ForeignKey(Post, on_delete=models.CASCADE,related_name="post_views_count",) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.IPAddres views.py posts = Post.objects.filter(is_toplevel=True, status=Post.ACTIVE).select_related('author').prefetch_related('tags').select_related('category') html {% for post in posts %} .... {{ post.views_count }} {% endfor %} Due to the postview call, the number of hits increases by 10 sql... -
ModuleNotFoundError: No module named 'apotheekMijlbeek_main'
I try to deploy my first Django / Postgres app on Pythonanywhere. I activated the postgres on my account / configured the port / address etc but when I try to run the code I'm getting the ModuleNotFoundError: No module named 'apotheekMijlbeek_main'. In my opinion my structure is like apotheekMijlbeek/apotheekMijlbeek_main and in this folder I'm having the settings.py In the /var/www/stefrenneboog23_pythonanywhere_com_wsgi.py my code is like this : # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/stefrenneboog23/apotheekMijlbeek' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'apotheekMijlbeek_main.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() Really have no idea what I can change more. Thanks a lot already for the review. KR -
Switch to another database in Django
I have a django project that was created on an Oracle database and I want to switch to ANOTHER Oracle database. I have followed this tutorial https://pythonfusion.com/switch-database-django/, but there is a problem that not all models are created initially in Django, some are created using inspectdb on existing tables in other databases . Therefore, when using the migrate --database=new command, I get errors about those tables that already existed before Django was created. Is there a way to migrate only the models and tables necessary for Django to work? (users, auth...) -
Django - Select from JSONField
I have a model with JSONField: class SDReport(models.Model): summary = models.JSONField() summary field data example: { "1": { "stm": { "1": [] }, "non_stm": { "1": ["3419250", "3205437"] } }, "2": { "stm": { "1": [] } } } How can select data (expected result ["3419250", "3205437"], default value - []) from path '1' > non_stm > '1' with ORM? -
How to get timeseries from Django model by date and by foreign key?
I have the following two models: class Station(models.Model): # fields of station class StationReading(models.Model): station = models.ForeignKey(Station) speed = models.FloatField() time = models.DateTimeField() I want to build a timeseries dataset that each row is a unique time field, each column is an existing Station (by id) and the values are speed. My expected output: | Date | Station_1 | Station_2 | etc... |-----------------|-----------|-----------| | < some date 1> | <speed of |<speed of | | | station 1>| station 2>| |-----------------|-----------|-----------| | < some date 2> | <speed of |<speed of | | | station 1>| station 2>| Performance is important here, as I have millions of StationReading objects. Is this possible solely using Django queries? -
Python Django Form "This field is required"
i made a form in django with one field required (imagefield) but when I fill it by selecting an image, once I fill it it considers that the form is not valid and asks to fill it again I don't understand why, here is my code below: view.py: def success(request): return HttpResponse('successfully uploaded') def contact(request, plage_name): name = plage_name plage = Spot.objects.get(name__iexact=name) if request.method == 'POST': form = ContactUsForm(request.FILES) # ajout d’un nouveau formulaire ici if form.is_valid(): print("it's valide") plage.photo = form.cleaned_data['photo'] plage.save() return redirect('success') else: form = ContactUsForm() return render(request, 'pages/Testform.html', {'form': form}) # passe ce formulaire au gabarit form.py class ContactUsForm(forms.Form): photo = forms.ImageField(required=True) html <form action="" method="post" novalidate> {% csrf_token %} {{ form }} <input type="submit" value="Envoyer"> </form> Url.py urlpatterns = [ path('contact-us/<path:plage_name>', views.contact, name='contact'), ] -
Django ORM Get users who have NOT updated their salary information in the last 1 year (Simlpe History )
I want to bring users who have not updated their salary information in the last 1 year. BUT WITH ORM not For Loop. from simple_history.models import HistoricalRecords class User(AbstractUser): ... salary_expectation = models.IntegerField() history = HistoricalRecords(cascade_delete_history=True) ################################################################ User.objects.filter(# MAGIC ) # Get users who have NOT updated their salary information in the last year -
How to send data from the front-end to the back-end using ajax and Dango?
INTRO: I am writing a Django application which needs to send some data from the front-end to a views.py file in the back-end. To do so, I have a button which performs a transaction when clicked. This is what it looks like: <button id="submit_transaction" type="button" class="btn btn-outline-info" onclick="transaction()">Transaction</button> PROBLEM: When clicked, the button triggers a function called transaction() which performs an asynchronous operations, like so: <script> async function transaction(){ // Perform some task // Submit transaction $.ajax({ type: 'POST', data : { 'public_key': public_key, }, success: function(res){ console.log(res); } }); } </script> Inside of this asynchronous function there is an ajax call which collects some data into a variable and then sends it to the back-end via a post request (as suggested here link). However when I click the button the following error pops up: Uncaught (in promise) TypeError: Illegal invocation QUESTION: Do you have any idea of what I am doing wrong? or are you able to suggest a smart and elegant solution to send some data from the front end to the back-end? -
which JavaScript frontend library or framework is best to create a network graph? I use Django framework in backend [closed]
I am working on a project where I fetch followings of a Twitter user using Tweepy, so I want to represent friendship between followings using network graph and want to display this graph in a website; Which is the best JavaScript frontend library or framework to use? and how easy can it be integrated with Django? I am already using Django templates in my project -
Django form throwing errors on display
I have created a POST Django form with several input fields. Many of them are required and they throw the error that they are required on the website render. Also they throw the error above them, even though I specified they threw it in the block underneath. Please help. FORM DEFINITION class Install_Version_Form(forms.Form): project = forms.CharField(widget=forms.TextInput( attrs={'class': 'textInputAddMach', 'placeholder': "project"}), max_length=100, required=True) privacy = forms.ChoiceField(choices=privacy, required=True) iteration = forms.CharField(widget=forms.TextInput( attrs={'class': 'textInputAddMach', 'placeholder': "iteration"}), max_length=100, required=True) machine_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'textInputAddMach', 'placeholder': "machine name"}), max_length=100, required=True) version = forms.CharField(widget=forms.TextInput( attrs={'class': 'textInputAddMach', 'placeholder': "e.g. 0.1"}), max_length=100, required=True) def __init__(self, *args, **kwargs): super(Install_Version_Form, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() FORM VIEW CTX PACKING def installation(request): ctx = { "installVersionForm": None } ctx["installVersionForm"] = Install_Version_Form(request.POST) if request.method == 'POST': form = Install_Version_Form(request.POST) if form.is_valid(): (contact cloud) else: ctx["installVersionForm"] = form return render(request, "installation.html", ctx) HTML TEMPLATE {% block extend_content %} <form action="" method="post"> {% csrf_token %} {{installVersionForm.as_p}} <input type="submit" value="add new version"> </form> <br/> <br/> <br/> {% if installVersionForm.errors %} {% for error in installVersionForm.errors %} <small>{{ error }}</small> {% endfor %} {% endif %} {% if installVersionForm.messages %} {% for message in installVersionForm.messages %} <small>{{ message }}</small> {% endfor %} {% endif … -
AttributeError: 'RelatedManager' object has no attribute 'scheduled_datetime'
I'm trying to use this in order to add a set of facilities to a lead. The trouble is that i need an extra field for the date and time of the tour scheduled for each of the facilities i add to the lead. So when i create a lead and add facilities to the lead i have that extra field where i can enter date and time and access it afterwards as a list of facilities with their tour dates on the leads page. I'm getting the following error every time i try to submit anything using a put request: "AttributeError: 'RelatedManager' object has no attribute 'scheduled_datetime'" models.py class Facility(models.Model): name = models.CharField(max_length=150, null=True, blank=False) main_image = models.ImageField(null=True, blank=True) email = models.EmailField(max_length=150, null=True, blank=True) telephone_number = models.CharField(max_length=30, null=True, blank=True) facility_description = models.TextField(max_length=1000, null=True, blank=True) def __str__(self): return self.Name class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" class LeadFacilityAssociation(models.Model): assigned_facilities = models.ForeignKey(Facility, related_name='leadfacilityassociation') lead = models.ForeignKey(Lead, related_name='leadfacilityassociation') scheduled_datetime = models.DateTimeField(null=True, blank=True) serializers.py class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = serializers.IntegerField(required=False) scheduled_datetime = serializers.DateTimeField(required=False) class Meta: model = Lead fields = ( "id", "assigned_facilities", "scheduled_datetime", "is_owner", ) read_only_fields = ("id") def get_is_owner(self, … -
Getting a JSON object from an API endpoint Instead of rendered media files , Django Rest Framework
I am currently trying to build an API that displays a media file instead of returning a JSON object but am failing miserably. This is how the Call looks like: My Root API: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "modules": "http://127.0.0.1/store/modules/", "builds": "http://127.0.0.1/store/builds/", "cables": "http://127.0.0.1/store/cables/", "junction_boxes": "http://127.0.0.1/store/junction_boxes/", "trackers": "http://127.0.0.1/store/trackers/", } When I make a call to say, the cables endpoint, I get something like this: [ { "id": 1, "tag": "ac_cable_1", "manufacturer": "RANDOM", "model": "output cable", "size": 300.0, "cores": 1, "bending_radius": 12.0, "diameter": 0.0332, "material": "Al", "imp": 249.0, "ohm_km_20": 0.1, "ohm_km_90": 0.132, "reactance": 0.056, "rate": 1.0, "currency": "USD", "architecture": "110", "data_sheets": [ { "id": 1, "data_sheet": "http://127.0.0.1:27038/static/media/store/data_sheets/data_sheets/data_sheet_file.pdf", "cable": 1 } ] }, If I then go to http://127.0.0.1/store/cables/1/data_sheets/ I end up with the following JSON object instead of the actual data sheet: [ { "id": 1, "data_sheet": "/static/media/store/data_sheets/data_sheet_file.pdf", "cable": 1 } ] I expected that once I go to the data_sheets endpoint, the file itself would pop open instead of returning another JSON object which then contains a link that when clicked opens and renders the file on a new page. Is this the default behavior or am I doing something wrong? Serializers.py: class …