Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom list per user
I'm starting with Django and I can't find a solution to a project I intend to do. To contextualize, I will use a (custom)user model and another model that I will call here "posts". The idea is that a user (USER_A) who has a specific permission can access a page(so far without problems) and that on this page he could select a user (USER_B) among users who are within a specific group(in a dropdown or something like this). After that, a list would appear with existing posts and USER_A would have an option(a checkbox maybe?) to turn that post on or off for the USER_B. Each user would have a list of active posts and a post could be active for more than one user at the same time, and if I disabled it for a particular user, it wouldn't interfere with another user's list of active posts. Can anyone give me a help with this? Thanks!! -
Getting current object id from a queryset in my view Django
I need to save into the DB the current object being accessed by a user. I have a queryset where a user has several orders eg orders 1,2,3,4,5. Order 1 has its own detail. eg order name, order id etc. I need to access this order id of object 1 and save it in a separate table. How do I go about this? Model class Orders(models.Model): id = models.AutoField(primary_key=True) order_name = models.CharField(max_length=50) class WorkonOrder(models.Model): id=models.AutoField(primary_key=True) order_id = models.ForeignKey(Orders, on_delete=models.DO_NOTHING, related_name='order_id') updatedtime = models.DateTimefield(auto_now_add= True) Views.py def workedonOrder(request): #get currently logged in user logedinuser= Writer.objects.get(user=request.user.id) #get currently accessed order id -
Show more comments using ajax with Django button
With Django I made a Show more comments button using ajax. This system works, but the problem is that there are form fields in the comments I brought in this way, and when I click the more button, csrf_token does not appear in this comment field. As such, I get a csrf_token error when I submit the form. I leave my codes below. To solve this problem, I ran the form with the get method, but as such, the function in the views directs me to the page with JsonResponse. Another solution was to give the header information csrf_token, but that didn't solve the problem either. blog_detail.html <script> $(document).ready(function(){ $('#load_form').submit(function(e){ e.preventDefault(); var limit = $(this).attr('limit') var page = document.getElementById('pagination') var blog_comment_list = $('#blog-comment-list') var serializedData = $(this).serialize(); $.ajax({ type:'GET', url: "{% url 'load-more-comments' %}", data : serializedData, success: function(response){ blog_comment_list.html(response.comment_html) if (page.value >= limit){ $('#submit_button').hide() } page.value = parseInt(page.value)+1 }, }) }) }) </script> <div id="blog-comment-list"> {% include 'front_end/blog/comment/partial-comment.html' %} </div> <form method="GET" id="load_form" limit="{{num_pages}}"> <input type="hidden" name="pk" value="{{details.id}}"> <input type="hidden" name="page" value="2" id="pagination"> <input type="submit" name="load" value="Load More" id="submit_button"> </form> partial-comment-html <div class="media-holder mt-5"> <h3 class="title mb-3">All Comments</h3> {% for item in comments %} <div class="infinite-container"> <div class="media mb-5"> … -
UWSGI application
http :8000 --socket /tmp/my_gless.sock dont work for me but I dont know why. when I run in terminal: uwsgi --http :8000 --socket /tmp/my_gless.sock --module my_gless.wsgi:application or uwsgi --http :8000 --socket /tmp/my_gless.sock --wsgi-file /home/krzyzak21/venv/my_gless/my_gless/wsgi.py its works but i have it in uwsgi.ini file [uwsgi] # variables projectname = my_gless base = /home/krzyzak21/venv chdir = %(base)/%(projectname) # configuration master = true virtualenv = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings module = %(projectname).wsgi:application socket = /tmp/%(projectname).sock logto = /tmp/%(projectname).log chmod-socket = 666 I have VPS server with root and i create sudo user krzyzak21 then logging in user terminal in VSCode, now I'm working in /home/krzyzak21/ where I'm create virtual venv and install in this django 3, python 3 newest pip etc. My tree file: home/krzyzak21/venv/ : bin lib my_gless │ ├── config │ │ ├── my_gless_nginx.conf │ │ └── uwsgi.ini │ ├── logs │ │ └── error.log │ ├── manage.py │ ├── media │ │ └── a.png │ ├── my_gless │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-38.pyc │ │ │ ├── pro.cpython-38.pyc │ │ │ ├── settings.cpython-38.pyc │ │ │ ├── urls.cpython-38.pyc │ │ │ └── wsgi.cpython-38.pyc │ │ ├── settings.py │ │ ├── … -
Django users and superusers not preserved in my dockerized app
I am developing a Django app using Docker, and postgreSQL as my database. I build my docker image and everything is working fine except that my superuser and my users are not being preserved if I run: sudo docker-compose down sudo docker-compose up -d If right after I run sudo docker-compose up I go to my localhost in the browser I obtain an error and the output of docker-compose logs looks as follows : db_1 | The files belonging to this database system will be owned by user "postgres". db_1 | This user must also own the server process. db_1 | db_1 | The database cluster will be initialized with locale "en_US.utf8". db_1 | The default database encoding has accordingly been set to "UTF8". db_1 | The default text search configuration will be set to "english". db_1 | db_1 | Data page checksums are disabled. db_1 | db_1 | fixing permissions on existing directory /var/lib/postgresql/data ... ok db_1 | creating subdirectories ... ok db_1 | selecting dynamic shared memory implementation ... posix db_1 | selecting default max_connections ... 100 db_1 | selecting default shared_buffers ... 128MB db_1 | selecting default time zone ... Etc/UTC db_1 | creating configuration files ... … -
How to autofill a field with concatenated other fields Django
This is the first time that I ask a question here, so sorry if it's not perfect. I'm working in django on last version. I would like to auto generate a field (KEY (which will be used in dialogflow)) value when I submit my form with the concatenation of other fields as KEY = 'SENT_' + search_categories + '_' + '001' and I would like that the '001' will be auto incremented too. I can't show more code because I'm not sure that it's legally cause I'm working in a private firm but I think that I can show the key declarion in my django model. key = models.CharField(max_length=30, blank=False, null=False, unique=True) I hope that you'll can help me ! Thank you very much ! -
How to add a table in Django Cryspy forms?
I would like to add a table to a Django crispy form. I am trying to add the following html code to my create_bill.html or forms.py but I keep encountering some syntax errors. what is the correct way to add the following html code and remove the title for each lines: <div class="card-block table-border-style"> <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th class="center">Item</th> <th>Description</th> <th class="center">Qty</th> <th class="right">Unit Price</th> <th>Account</th> <th>Tax Rate</th> <th class="right">Amount GBP</th> </tr> </thead> </table> </div> </div> forms.py class BillForm(forms.ModelForm): bill_title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Title'})) vendor = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Vendor'})) bill_date = forms.DateField(widget=forms.DateInput(attrs={'placeholder': 'Bill Date'})) due_date = forms.DateField(widget=forms.DateInput(attrs={'placeholder': 'Due Date'})) reference = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Reference'})) class Meta: model = Bill fields = ['vendor','bill_date','due_date','reference'] def __init__(self, *args, **kwargs): super(BillForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.layout = Layout( Row( Column('vendor', css_class='form-group col-md-2 mb-0'), Column('bill_title', css_class='form-group col-md-2 mb-0'), Column('bill_date', css_class='form-group col-md-2 mb-0'), Column('due_date', css_class='form-group col-md-2 mb-0'), Column('reference', css_class='form-group col-md-2 mb-0'), css_class='form-row' ), Fieldset('Add lines',Formset('lines')), Row( css_class='form-row' ), Div( HTML("<br>"), ButtonHolder(Submit('submit', 'save')), ) ) create_bill.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} -
Can I create a website with personal accounts/myPages/login system using Python?
If so, how? I am planning to create a website where if the users submit some kind of information in their my pages, then it will be displayed in an organized calendar in my manager account for the website. Thanks a lot! -
jquery Datatables pluggin not loading with Django but loading if opened straight from browser
I have a jquery pluggin to add functionalities to html table (DataTables). This is part of a frontend for a django application, and comes from a template (sb2 admin from startboostrap). I have installed the template & tested that it works, if I just open their index.html & visit the tables.html files, it all works fine. In the initial template, the loading of the scripts is done like (assuming the dir structure): <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="vendor/datatables/jquery.dataTables.min.js"></script> <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script> <!-- Page level custom scripts --> <script src="js/demo/datatables-demo.js"></script> In django, I have setup a /static folder & use manage.py collectstatic like a good boy, so the loading of the script is slightly modified, like so: <script src="{% static 'vendor/jquery/jquery.min.js'%}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js'%}"></script> <!-- Core plugin JavaScript--> <script src="{% static 'vendor/jquery-easing/jquery.easing.min.js'%}"></script> <!-- Custom scripts for all pages--> <script src="{% static 'js/sb-admin-2.min.js'%}"></script> <!-- Page level plugins --> <script src="{% static 'vendor/chart.js/Chart.min.js'%}"></script> <!-- Page level custom scripts --> <script src="{% static 'js/demo/chart-area-demo.js'%}"></script> <script src="{% static 'js/demo/chart-pie-demo.js'%}"></script> <!-- Page level custom scripts --> <script src="{% static 'js/demo/datatables-demo.js'%}"></script> I know it … -
Pylint does not raise errors anymore after Django was configured
I installed pylint_django and it was asking me to configure django so I did, but after that I don't get any errors anymore, it seems the linter stopped working. The current interpreter selected is from a virtual env in the project root. Here is my settings. { "python.defaultInterpreterPath": "C:\\Users\\me\\AppData\\Local\\Programs\\Python\\Python38\\python.exe", "python.linting.pylintEnabled": true, "python.linting.pylintArgs": [ "--load-plugins=pylint_django", "--django-settings-module=backend.settings", "--disable=C0111", "--disable=C0303", "--disable=C0103" ], } -
Django ORM query returning wrong result using Q
I have the following query using Django ORM: fixtures = Fixture.objects.annotate(oc=Count('odds__id')).filter((Q(odds__result=4) | Q(oc__lt=10)), date__year__gte=2016).distinct() Where it should retrieve all the fixtures with an odds object having result set to 4 OR where the count of odds objects is lower than 10. When I execute this query it returns 34 fixtures objects, but when executing: fixtures = Fixture.objects.annotate(oc=Count('odds__id')).filter(oc__lt=10, date__year__gte=2016).distinct() It returns +30k of fixture objects. How can I get the first query to return the same amount of objects (or at least closer to 30k objects) as the second query? And why is this OR clause not working properly? -
iterate throuh multiple queryset in django
my queryset output comes in this way [<QuerySet [<Video: paid work>]>, <QuerySet [<Video: paid>, <Video: free>]>] how I can loop throut it in template? {% for item in object_list %} {{item.name}} {% endfor %} this is not showing anything -
Array from nested serializer is undefined. REDUX, DRF
I am having trouble displaying the data from a nested serializer. I can get and see the data via Redux and see that it is in my props, but when I try to map it to my React component or the local state it says that it is undefined. I have been at this for a while and I am sure it is a minor issue but it is extremely frustrating. Business Serializer: from rest_framework import serializers from .models import Business from django.apps import apps as django_apps from django.conf import settings def get_job_model(): return django_apps.get_model(settings.JOB_MODEL, require_ready=False) Job = get_job_model() # Job Serializer class JobSerializer(serializers.ModelSerializer): class Meta: model = Job fields = "__all__" class CreateBusinessSerializer(serializers.ModelSerializer): jobs = None class Meta: model = Business # fields = '__all__' exclude = ['owner', 'geolocation'] class GetBusinessSerializer(serializers.ModelSerializer): jobs = JobSerializer(many=True, read_only=True) class Meta: model = Business # fields = '__all__' exclude = ['owner', 'geolocation'] class AllBusiness(serializers.ModelSerializer): class Meta: model = Business fields = ['business', 'address'] Business Page Component (abbreviated): import React, {Component} from 'react'; import {businessDetail, getBusiness} from "../../../actions/business"; import {connect} from 'react-redux'; import store from "../../../store"; import {NOT_HOME} from "../../../actions/types"; import {Link} from "react-router-dom"; class BusinessPage extends Component { constructor(props) { super(props); this.state = … -
Headache on getting data with aggregate queryset
I have been having difficulties for a while to make joints and aggregations between my models. For my project, I need to retrieve data in order to display them in a table. In my application, a situation (over a certain period of time), includes a "dataserie". These "dataserie" contain "instantdata" (value at a date). Each "dataserie" can have a different "source" (a source from which the "instantdata" received comes). I would like to display for a given situation (sent via the url /situation/int:primary_key), the list of the sources of the situation (thus going through the "dataserie"), and the last "instantdata" date sent by the source , in order to determine the "active" date of each source. For example, for my situation 1, I would like to have a table of this type : Source Last received date Source Program1 02/02/2021 08:00:14 Source Program2 02/02/2021 07:30:14 My model file and view file are here : https://paste.ee/p/P8M4T Would it be even possible with query set ? Or should i use tempaltes tags in my template do to this kind of stuff ? here are some sources i've tried to understand and implement : https://docs.djangoproject.com/en/3.1/topics/db/aggregation/ https://hakibenita.com/how-to-use-grouping-sets-in-django https://hakibenita.com/django-group-by-sql#how-to-sort-a-queryset-with-group-by https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest -
Check if sending to webhook URL is successful
I have this portion of sending data through webhooks in my models.py for webhook in webhooks: requests.post(webhook.url, json=message): The whole process fails whenever the sending of data is not successful, for some reasons like the given URL is not a valid webhook URL. Is there any way I can avoid the breaking of the process, or check if the sending of data is successful or not? -
Update field without rest API
I have a model.py class UserPaymentInformation(models.Model): ... awaiting_confirmation = models.BooleanField(default=False) I want to make awaiting_confirmation = True in code. But forbid awaiting_confirmation update via RestAPI call. views.py class UserPaymentInformationUpdateAPIView(generics.UpdateAPIView): permission_classes = (IsAuthenticatedDriver,) serializer_class = UserPaymentInformationUpdateSerializer queryset = serializer_class.Meta.model.objects.all() def update(self, request, *args, **kwargs): partial = kwargs.pop("partial", False) instance = self.serializer_class.Meta.model.objects.get( user=self.request.user ) self.mark_user_as_new() # awaiting_confirmation = True # I WANT SOMETHING LIKE THIS serializer = self.get_serializer( instance, data=request.data, partial=partial ) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response({"result": serializer.data}) serializers.py class UserPaymentInformationUpdateSerializer(serializers.ModelSerializer): class Meta: model = UserPaymentInformation fields = ("id", "full_name", "card_number", "account_number", "bik", "awaiting_confirmation") How can I fix update method? -
Postgres-Heroku not migrating data
I have created an app with Django / Postgres / React, deployed to Heroku. It has data which I am now trying to update. If I for example, make a change to the navbar or add some text etc, I can push the changes to GitHub, and then push the changes to Heroku, and all works fine. However, I am not managing to change the data, which I created in seeds files, The data is split into 4 Django "Apps": Movies Genres Comments JWT-AUTH (Users) Here is what I did, I added all my data using the Django Admin panel. I then saved this data into seeds.json files in each App. I dropped database Deleted all migration files except init.py Created database Loaded all the seeds data Makemigrations Migrate All works in localhost, I can see all the new data. But when I try to deploy to production, it only shows old data. If I make changes to styles etc it does deploy them, but not the data. Any ideas for me? DATABASES = {} if str(os.getenv('ENVIRONMENT')) == 'development': DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'movies-db', 'HOST': 'localhost', 'PORT': 5432 } else: DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) -
How to change app name in google login netlify
I have web applications on netlify https://compassionate-galileo-xxxxx.netlify.app. I connected google authorization to it. Set up a backend on django and everything is fine. But for some reason, instead of the name of my application installed in https://console.cloud.google.com/. My domain is displayed instead of the set name. . -
Can't close Django message alerts
I know this is something silly but I just can't seem to fix it. I'm displaying alerts onto a Django template, and would like the user to remove the alert by pressing the 'X' icon that is displayed when it pops up. My issue is that clicking the 'X' icon doesn't work. the alert messages also do not show when redirected to the home page, however when navigating to a product page all the alerts that have been generated for that page will show up at once. Here is my base template which shows the messages: <body> <div class="mt-5 pt-4"> {% if messages %} {% for message in messages %} <div class="messages {{ message.tags }} fade show" role="alert"> {{ message }} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <!-- <span aria-hidden="true">&times;</span> --> </button> </div> {% endfor %} {% endif %} </div> </body> And my messages are created in the views.py file when a point in a statement is reached, e.g.: order_item.save() messages.success(request, 'This item quantity was updated.') order.items.add(order_item) messages.success(request, 'This item was added to your cart.') And here is an example of the alert when it pops up. Thanks. -
How to create a 2 way sync cronjob in django from localdb to salesforce and salesforce to localdb
Please explain it in detail via example or share some tutorial to do so.I have an ecommerce application for which backend is salesforce.I have to create a 2 way sync cronjob to update the salesforce from localdb and vice-versa. -
How to filter and sort a queryset with two forms
django noob here... I am making a bookshop, and I would like customers to filter books by category, and then have the option to sort this queryset by things like price etc.. The issue I am having is that when I sort/order my queryset the categories filter is removed. Pagination also resets the queryset when I go to the next page. Do I maybe need to pass the new queryset in the URL? def bookshop(request): filter_form = FilterForm() bookresults = Book.objects.all() query_name = '' my_filter = Q() # CATEGORIES FORM if "category" in request.GET: form = CategoryForm(request.GET) if form.is_valid(): queries = form.cleaned_data queries = {k: v for k, v in queries.items() if v is not False} queries = dict.fromkeys(queries, True) query_name = '' for query in queries.keys(): query = '\'' + query.title().replace('_', ' ') + '\', ' query_name += query for query in queries: my_filter |= Q(**{query:queries[query]}) bookresults = Book.objects.filter(my_filter) else: form = CategoryForm() # FILTER FORM if "filter" in request.GET: filter_form = FilterForm(request.GET) if filter_form.is_valid(): if filter_form.cleaned_data['filter_method'] == 'low_to_high': bookresults = Book.objects.filter(my_filter).order_by('price') if filter_form.cleaned_data['filter_method'] == 'high_to_low': bookresults = Book.objects.filter(my_filter).order_by('-price') if filter_form.cleaned_data['filter_method'] == 'recent': bookresults = Book.objects.filter(my_filter).order_by('-pub_date') else: filter_form = FilterForm() # PAGINATION page = request.GET.get('page', 1) paginator = Paginator(bookresults, … -
Python/Django - Use only first colum in list [duplicate]
I want to reference my Fiat currencies in another .py file of my django app but I only need the first colume of a list I have defined. At my models.py I have the following: FIAT_CURRENCY = [('EUR', 'Euro'), ('GBP', 'British Pound'), ('HKD', 'Hong Kong Dollar'), ('RUB', 'Russian Ruble'), ('USD', 'United States Dollar')] But at my tasks.py I would only need this: currencies = ['EUR', 'GBP', 'HKD', 'RUB', 'USD'] How can I only use FIAT_CURRENCY for both? Can I just use the first colume of the list? Thanks in advance. -
How can display the video after uploaded in the video element using JavaScript ajax
I working on uploading video with progress bar using ajax and I need to display the video after upload it in the video element, instead of image. I using the Django backend, I take the form from Django forms I take this tutorial from YouTube. How I can display the video file which I chosen in the source in the video element The Html (Template) <video src="<!--here I need to display the video-->" autoplay> </video> <!-- Form --> {% if request.user.is_authenticated %} <br> <br> <br> <div id="alert-box"></div> <div id="image-box"> </div> <br> <form id="upload-form" action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{V_form.as_p}} <button class="btn btn-primary btn-block mt-5" name="submit_v_form"> <i class="icon-upload icon-white " name="submit_v_form"></i> Upload </button> </form> {% endif %} <br> <br> <div id="progress-box" class="d-none">progress</div> <div id="cancel-box" class="d-none"> <button id="cancel-btn" class="btn btn-danger">Cancel</button> </div> </div> <hr> </div> </div> </section> </article> The JavaScript file const uploadForm = document.getElementById('upload-form') const input = document.getElementById('id_video') console.log(input) const alertBox = document.getElementById('alert-box') const imageBox = document.getElementById('image-box') const progressBox = document.getElementById('progress-box') const canceleBox = document.getElementById('cancel-box') const canceleBtn = document.getElementById('cancel-btn') const csrf = document.getElementsByName('csrfmiddlewaretoken') // whenever choose th file something happen input.addEventListener('change', ()=>{ progressBox.classList.remove('d-none') canceleBox.classList.remove('d-none') const img_data = input.files[0] const url = URL.createObjectURL(img_data) console.log(img_data) const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('video', … -
AttributeError( AttributeError: Generic detail view 'class' must be called with either an object pk or a slug in the URLconf
I really need some help here, please. I think my code is right but when i call python manage-py runserver an error appears. • models.py from django.db import models from django.urls import reverse class Product(models.Model): title = models.CharField(max_length=255) image = models.URLField(max_length=255) price = models.DecimalField(max_digits=12, decimal_places=2) product_id = models.SlugField(max_length=255, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("api:detail", kwargs={"product_id": self.product_id}) views.py from django.views.generic import ListView, DetailView from .models import Product class ProductListView(ListView): model = Product class ProductDetailView(DetailView): model = Product urls.py from django.urls import path from .views import ProductListView, ProductDetailView app_name = "api" urlpatterns = [ path('', ProductListView.as_view(), name='list'), path('<slug:product_id>/', ProductDetailView.as_view(), name='detail'), ] error log in get_object raise AttributeError( AttributeError: Generic detail view ProductDetailView must be called with either an object pk or a slug in the URLconf. -
django- How to input only yy-mm in "DateField"
If I only input yy-mm at the ios front, how do I get it without "dd"? now user/models.py user_birth = models.DateField(null=True) enter image description here