Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle Multiple Requests from Django App?
I have a requirement, where only one instance of the Django application is supposed to be running on a remote server. The user will make a request to the service and the application will process batch data and return back output. In this particular scenario, I have been asked to handle multiple requests in a queue from inside the Django application which is slightly odd. If I have to move forward with this approach, what would be the best way to implement the queue. Also if there is an option to use some kind of a queue outside the application, what would be the best approach for it? Thanks in advance -
Azure web app deployed to tmp folder instead of wwwroot
I have been deploying my Django Python Web app on Azure App Service for a few hundred times now. Recently, i made a small change in the html file and push it but the deployment went differently. Instead of deploying the app in home/site/wwwroot/, Oryx deployed it to a tmp folder. (See the screenshot) I'm confused over why this happened. I didn't change ANY settings or configuration and my web app ended up in a tmp folder. Anyone knows what happened here and how to fix this? -
django rendering pdf file that is stored in database to the template
how to render pdf file that is stored in the database in the templates Django cv = models.FileField(blank=True, null=True,validators=[validate_file_extension]) docs = models.FileField(blank=True, null=True,validators=[validate_file_extension]) -
Django : initialize database without migrations
Sorry, I'm pretty novice on Django. I have some little notice already, but completly lack of experience. So the questions sound silly, but I could not find it exactly in this general form. So... Let's say, I have some Django project already done by someone. Now I have two situations : I have the latest version of project code. But I have nothing about database : neither database, nor migrations. To give some example, the code was on some Git, but the database and migrations files were on some server and this server is lost. I'd like to understand if I could still initialize the project from zero ? Get the new server with empty database. I clone git code of project. Launch manage.py makemigrations manage.py migrate and I'll get new database initialized by our models files ? Is it correct ? Are there some pitfalls about it ? the second situation is similar, but not exactly. Now I have some database-dump and also some migrations. But probably not all them. So I do not know how much my code is different from dump and migrations. I saw already the questions about similar situations. It seems that globally the solution … -
Is it possible to apply if-else in django base.html?
My all pages are inheriting from base.html file. However I want my about page to be slightly different. Majority of the pages are having <main role="main" class="container"> <div class="row"> <div class="col-md-8"> <div> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} {% block content %}{% endblock %} </div> <div class="col-md-4"> <div class="content-section"> <h3>Our Sidebar</h3> <p class='text-muted'>You can put any information here you'd like. <ul class="list-group"> <li class="list-group-item list-group-item-light">Latest Posts</li> <li class="list-group-item list-group-item-light">Announcements</li> <li class="list-group-item list-group-item-light">Calendars</li> <li class="list-group-item list-group-item-light">etc</li> </ul> </p> </div> </div> </div> </main> But about page I want the above code of block like <main role="main" class="container"> <div> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} {% block content %}{% endblock %} </div> </main> So is there a way the second block of code is only executed when the page is "about.html" else the first block should be executed. I can do these changes if I do not inherit about from base.html, but then I will be repeating a lot of lines of code. That is … -
Django project file is empty on github
enter image description hereWhen I am committing my Django project on Github, each time my website (Django project file) is not pushing in my repository. Please help me how can I push it on my Github repository. -
Why am I keep getting an empty query set in shell when I use Django model managers?
Blockquote class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): ................... objects = models.Manager() published = PublishedManager() And when I try in the shell : Post.published.filter(title__startswith=“Who”) <QuerySet []> Blockquote -
Django Generate Custom ID base on Selected Fields
I want to generate a custom transaction ID when new record comes into database base on selected Forms fields. The format should be 2020/John-UK/1012/001, 2020/John-Uk/1012/002, Where 2020 is the season, John is the supplier name, UK is location, 1012 is the date, 001 is count for the day. The count should always start with 001 and increase base on supplier, location and date. Example if the same supplier brings goods the following day from same location the ID should be 2020/John-UK/1112/001 If from different location and same date the ID will be 2020/John-US/1112/001 models.py class Goods_Supply(BaseModel): transaction_id = models.CharField(max_length=50, default="_", blank=True) supplier_name = models.ForeignKey(adminModels.Supplier, on_delete=models.CASCADE, null=True, blank=True) season = models.ForeignKey( adminModels.Season, on_delete=models.CASCADE, blank=True, null=True) location = models.ForeignKey( adminModels.Location, on_delete=models.CASCADE, blank=True, null=True) transaction_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) quantity = models.IntegerField(blank=True, default=0, null=True) def __str__(self): return self. transaction_id forms.py class GoodSupplyForms(ModelForm): class Meta: model = Models.Goods_Supply fields = ["transaction_id", "supplier_name", "season", " location", "transaction_date”, “quantity”] goods_supply.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.core.paginator import Paginator import CMCADMIN.models as adminModels from SS.models import Goods_Supply from SS.forms import GoodSupplyForms from django.urls import reverse def get_post_handler(request): if request.method == 'GET': return get(request) else: return post(request) def … -
When deploying Django to Heroku: ModuleNotFoundError: No module named 'env'
When deploying Django to Heroku, I get a ModuleNotFoundError: No module named 'env' error. Anyone know why it is looking for that module? Here is my requirements.txt: asgiref==3.2.3 certifi==2020.12.5 chardet==3.0.4 dj-database-url==0.5.0 Django==1.11 django-forms-bootstrap==3.1.0 gunicorn==20.0.4 idna==2.10 Pillow==5.3.0 psycopg2==2.8.6 pytz==2020.4 requests==2.25.0 sqlparse==0.4.1 stripe==2.55.1 urllib3==1.26.2 whitenoise==5.2.0 -
i want to show discount price when a product has discount price
i have this Order model: class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() disc_price = models.IntegerField(null=True, blank=True) date = models.DateField(datetime.datetime.today, null=True) status = models.CharField( max_length=100, blank=True, null=True, default="Unpaid", unique=True) order_status = models.CharField( max_length=100, choices=CHOICES, null=True, blank=True, default="In Review") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) def save(self, *args, **kwargs): order = Order.objects.all() if order.disc_price: self.total = self.quantity * self.disc_price else: self.total = self.quantity * self.price return super().save(self, *args, **kwargs) Here I have disc_price i want like this. Like if a product has disc_price the save function will be like this return self.disc_price * self.quantity I tried above but it is not working can someone help ! -
Django API keeps loading and throws timeout error when 'statsmodels.api' package is imported
In the urls.py from django.contrib import admin from django.urls import path import pandas as pd import statsmodels.api as sm urlpatterns = [path('admin/',admin.site.urls),] When I comment out the 'import statsmodels.api as sm' line, the API is working fine and shows the django home page but when I include the statsmodels package it keeps on loading and throws timeout error. Please suggests what is going wrong. The packages are installed properly in the django environment. Additional information: Deployed this django API (installed apache2 and mod_wsgi with this django) in the Ubuntu EC2 instance and calling the django API from the local computer using Public IPv4 DNS. (Followed this site to deploy the django and apache - https://studygyaan.com/django/how-to-setup-django-applications-with-apache-and-mod-wsgi-on-ubuntu) -
Why There is default values in Django admin ManyToManyField?
I have a model, named Tag that is defined like this: class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300, null=True, blank=True) child_id = models.ManyToManyField('Tag',default=None, blank=True, null=True) def __str__(self): return str(self.id) When I want to add a new tag, there are default values child_id like this: Why ? -
Add dynamically form fields dependencies in js
I am developing an app in django. I would like to use http://emranahmed.github.io/Form-Field-Dependency/ in my forms. Let's say this is my example html: <div class="form-group"> <label for="exampleInput1">Text Box</label> <input type="email" name="checkEmpty" class="form-control" id="exampleInput1" placeholder=""> </div> <div class="form-group" id="divToHide" > <label for="exampleInput2">This will show if select yes in</label> <input type="email" class="form-control" id="exampleInput2" placeholder=""> </div> <div class="form-group"> <select name="cars" id="cars"> <option value="yes">yes</option> <option value="no">no</option> </select> </div> this is my css: [data-depends]{ display:none } an this is my js: <script src="{% static 'js/form-field-dependency.js' %}"></script> jQuery(function ($) { $('[data-depends]').formFieldDependency(); }); $.fn.formFieldDependency({ 'rules': { '#divToHide' : { '#exampleInput1' : {'type' : '!empty'}, '#cars' : {'type' : 'equal', 'value':['yes']}, } } }); Everything works as I expected. But I wonder if you can add dependencies dynamically. According to the documentation you can also add dependencies like that: <div class="form-group" id="change" data-depends="[{'#cars':{'type' : 'equal', 'value':['yes']}}]"> <label for="change">This will show if sth</label> <input type="email" class="form-control" placeholder="" > </div> So I thought that I can create a js function to add 'data-depends' attribute to a particular element. But it doesn't work. This is my code: var elem = document.getElementById("change"); elem.setAttribute('data-depends', "[{'#cars':{'type':'equal', 'value':['yes']}}]") Has anyone tried to do something similar? Best regards -
I am unable to update an item in Django
Individuals user of my appplication have their Bar Information created immediately after creating their Bars. I want to enable them to be able to update their bar information but It keeps returning the error "Select a valid choice. That choice is not one of the available choices." I am not sure of what that means and this kind of error is weird to me. views.py def UpdateUserBar(request): user = request.user.id user_email = request.user.email bar = Bar.objects.get(user_id=user) form = UpdateBar(request.FILES, instance=bar) if request.method == 'POST': form = UpdateBar(request.POST, request.FILES, instance=bar) if form.is_valid(): form.save() return redirect('/updatebar') messages.success(request, 'Bar Information Updated successfully') # else: # return redirect('/dashboard') # messages.error(request, 'Only Post method is accepted') else: try: pass except Exception as e: messages.error(request, "Unknown error"+ str(e)) return redirect(request.path) else: form = UpdateBar(instance=bar) context = {"form":form, "user_email":user_email, "bar":bar} return render(request, "dashboard/super/landlord/update_bar.html", context) Note: If i use the second else block code which was commented, it only redirects me to the dashboard and shows no error, so I am not able to know the cause of the error. models.py class Bar(models.Model): status = ( ("open", "open"), ("closed", "closed"), ("pending", "pending"), ) user_id = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) address = models.CharField(max_length=100) opening_time = models.TimeField() closing_time = … -
VSCode custom code formatting and auto indention for language(Django-Template indention)
I did a lot of search to find a away to create or override and existing extension of vscode to do indention for django-template but nothing is out there and no success in creation too. the best answer still using this settings: "files.associations": { "**/*.html": "html", "**/templates/**/*.html": "django-html", } "[django-html]": { "editor.defaultFormatter": "HookyQR.beautify", } "beautify.language": { "html": ["django-html"] }, and this extensions: Dajngo (Baptiste Darthenay) & beautify. but there is no indention for django-template language and only the HTML tags will be indented. I tried to override the Djagno extension to make it possible, and yeah it would insert some indention but after saving the code, Beautify will automatically format the code and delete that indention, so the result always is like this: <ul class="navbar-nav nav-flex-icons {% if LANGUAGE_BIDI %} mr-auto {% endif %}"> {% get_available_languages as languages %} {% for lang_code, lang_name in languages %} {% if lang_code != LANGUAGE_CODE %} {% language lang_code %} <li class="nav-item"> <a class="nav-link lang-setter" data-lang-code="{{ lang_code }}"> {{ lang_code|language_name_local }} </a> </li> {% endlanguage %} {% endif %} {% endfor %} </ul> the ugly template. -
How to row-reorder using server rendering in datatables.js?
I've stuck on this problem. I investigated datatables.js manuel too much but I cannot find a proper way for this problem. I am using datatables.js plugin with django. I want to use row-reordering in datatables.js with server rendering. I have codes as following: let table = $('#datatables').DataTable({ "aaSorting": [], "serverSide": true, "ajax": { "url": '/customers/drawDt', // "type": "GET" }, "columns": [ { "data": "id" }, { "data": "hesapKodu" }, { "data": "unvan" }, { "data": "ad" }, { "data": "soyad" }, { "data": "aktifPasif" }, ], rowReorder: { dataSrc: "id" }, }); def drawDatatable(request): draw = int(request.GET.get('draw')) length = int(request.GET.get('length')) start = int(request.GET.get('start')) customer_column_titles = [i.name for i in Customer._meta.get_fields()] queryset = Customer.objects.all() total = queryset.count() count = queryset.count() data = [i.to_dict_json() for i in queryset] response = { 'data':data, 'draw':draw, 'recordsTotal': total, 'recordsFiltered': count } return JsonResponse(response) I can use all datatable's attributes that I want, except row-reordering. When I try to use row-reorder using drag and drop, it send a request to server - get server datas and use them like there is no row-reordering. Can anyone help me, please? -
How do I assign a static file to an initial forms.FileField?
I'm trying to initialise a django form FileField with a file from my static directories. I am using a ClearableFleInput widget for the field data_file = forms.FileField( #validators=FileExtensionValidator(allowed_extensions=['xlsx','csv']), label = "Timeseries Data File", widget=forms.ClearableFileInput() ) Within the view I'm trying to set the initial form data as follows: initial_data['data_file'] = open(settings.STATIC_ROOT + '/path/to/data_file.csv','r+') ctx['form'] = EntryForm(initial=initial_data) return ctx All my other initial data items load but not the filefield. Can I do this and if so, how? -
mod_wsgi [wsgi:error] 500 Internal Server Error [ModuleNotFoundError: No module named 'lncRNA' ]
I am trying to deploy a very basic Django application (lncRNA) in our web server.Below is my system version information: [yxu@localhost lncRNA]$ httpd -v Server version: Apache/2.4.6 (CentOS) Server built: Nov 16 2020 16:18:20 [yxu@localhost lncRNA]$ cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core) [yxu@localhost lncRNA]$ which python3 /usr/local/miniconda3/bin/python3 [yxu@localhost lncRNA]$ which mod_wsgi-express /usr/local/miniconda3/bin/mod_wsgi-express The root directory of my lncRNA webpage is /var/www/html/lncRNA I can start my django server directly with python manage.py runserver, and I can also get my page http://127.0.0.1:8000/. But when I use mod_wsgi-express start-server wsgi.py --port 8080 or configure Apache also gets theI get the 500 Internal Server Errorfollowing error Log: [Wed Dec 16 16:42:30.358252 2020] [mpm_prefork:notice] [pid 27037] AH00170: caught SIGWINCH, shutting down gracefully [Wed Dec 16 16:42:31.459802 2020] [core:notice] [pid 28101] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0 [Wed Dec 16 16:42:31.461239 2020] [suexec:notice] [pid 28101] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Wed Dec 16 16:42:31.496036 2020] [lbmethod_heartbeat:notice] [pid 28101] AH02282: No slotmem from mod_heartmonitor [Wed Dec 16 16:42:31.522556 2020] [mpm_prefork:notice] [pid 28101] AH00163: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/5.4.16 mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Wed Dec 16 16:42:31.522581 2020] [core:notice] [pid 28101] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Wed Dec 16 16:42:51.869513 2020] … -
Issues with Django form select field that queries the ORM when there is no migrated database?
I have a Django form which can be simplified to: class QuestionAnswerForm(ModelForm): class Meta: model = QuestionAnswer exclude = [...] widgets = { "link": Select( choices=[(None, "[none]"), ("summary", "Summary")] + [ (question.question_no, question.question_no) for question in Question.objects.all() ] ), ... } The choices for the link field are retrieved from a database query. However, this does not work when building a new environment where the database has not yet been migrated. It would make sense to migrate the database, but running python manage.py migrate results in a stack trace ending in: django.db.utils.ProgrammingError: relation "decision_tree_question" does not exist LINE 1: ..._tree_question"."display_answers_vertically" FROM "decision_... It seems that running this causes Django to attempt to populate this form field with the results of a database query before migrating the database! Amending the form to not include the database query fixes this issue: class QuestionAnswerForm(ModelForm): class Meta: model = QuestionAnswer exclude = [...] widgets = { "link": Select( choices=[(None, "[none]"), ("summary", "Summary")] ), ... } but I obviously want this. Am I getting the choices from the database correctly? Is there a better way to achieve the same thing without causing this issue? -
When i add the order from AdminPanel in django i got this error
Error:AttributeError at /admin/store/order/add/ 'bool' object has no attribute 'utcoffset' This is my models.py class Order(models.Model): o_id=models.AutoField(primary_key=True) o_date=models.DateTimeField(default=True) o_address=models.CharField(max_length=250,null=True) o_amount=models.FloatField() user=models.ForeignKey(User, on_delete=models.SET_NULL,null=True,blank=True) -
save django model queryset into another model
I have two Django models class Invoice(models.Model): id = models.IntegerField() is_converted = models.BooleanField(default=False) this model keeps the information about invoices and quotations and another model containing items details of particular invoice/quotation class Items(models.Model): document = models.Foreignkey(Invoice, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) name = models.CharField(max_length=50) now I want to convert the quotation record from model Invoice to Sales Invoice I have copied the data from the Invoice model row into another row (as I want to keep the Quotation record also) My problem is copying items from the Item model of quotation record into a newly generated invoice record. I've tried this quotation_items = Items.objects.filter(document=id) this returns normal queryset <QuerySet [<items: items object (238)>, <items: items object (240)>, <items: items object (241)>]> Now I want to save these records into the Items model for the converted invoices. Is there any way of saving querysets into Django models? -
Trouble with send form (nginx+django+ajax), upstream prematurely closed connection
I have problems using the send form on my website. I am using nginx + django + ajax. The form worked fine for more than a year, but suddenly it stopped working and now when a try submit the form i get nothing. In the nginx error log i see "upstream prematurely closed connection while reading response header from upstream". Here is the code: Ajax: $('#send_form').submit(function (e) { e.preventDefault(); $.ajax({ type: 'get', url: '/send', data: $(this).serialize(), success: function () { alert('form was submitted'); } }); }); Django from django.views.generic import View from django.http import HttpResponse from django.core.mail import send_mail from django.template.loader import render_to_string from django.conf import settings class Send(View): def get(self, request, *args, **kwargs): print(request.GET) message = render_to_string('email.html', {'data': request.GET}) send_mail( 'New message on site xxxxx.ru, message, settings.DEFAULT_FROM_EMAIL, [settings.EMAIL_DEFAULT_TO], fail_silently=False, ) return HttpResponse(status=200) Nginx: events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 150; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/sites-enabled/*.conf; server_names_hash_bucket_size 64; server { listen 80; server_name xxxxx.ru; location /static/ … -
Compare data faster in Django
I have a model with phone_number and I'm comparing this phone number with phone_number column uploaded in csv file from user. I'm fetching all data from DB, converting Django-query to Pandas Dataframe and comparing. This works, but takes too much time - Especially fetching and conversion of data to the Dataframe takes a lot of time. Is there a way to make this processing faster? For example comparing without conversion or so? BTW.main_dataframe (user's csv) doesn't need to be strictly Dataframe. Or maybe finding values in DB instead of fetching all DB data? def process(self): main_dataframe = pd.read_csv(self.save_path + "/" + self.file_name, encoding='cp932', dtype={self.main_col: object}) # loading csv file main_dataframe = self.cleaner(main_dataframe) # cleaning data from errors all_hikanshou_db = pd.DataFrame(list(Hikanshou.objects.all().values())) # getting data from DB(postgress) and converting it to DF m1 = main_dataframe[self.main_col].isin(main_dataframe['phone_number']) # comapring main_dataframe['compared_phone_number'] = main_dataframe[self.main_col].where(m1) main_dataframe.to_csv("abc.csv", index=False, encoding="cp932") -
Django - Q lookup search is slow for over a million records in MySQL
I have a Django application which involves a search in the database table and filters out all the results and data. models.py class TableData(models.Model): field1 = models.CharField(max_length=254, unique=True, null=False) field2 = models.CharField(max_length=254) field3 = models.CharField(max_length=254) field4 = models.CharField(max_length=254) field5 = models.CharField(max_length=50) field6 = models.CharField(max_length=10) field7 = models.CharField(max_length=10, null=False, default='200') slug = models.SlugField(max_length = 254, unique=True) search_qs = models.CharField(max_length=254, default='N/A') views.py def search(request): searchquery = request.GET.get("q") if searchquery: all_queryset_list = TableData.objects.all() queryset_list = all_queryset_list.filter(Q(search_qs__icontains=searchquery)) paginator = Paginator(queryset_list, 25) page = request.GET.get('page') searchres = paginator.get_page(page) res_count = queryset_list.count() context = { 'searchres': searchres, 'res_count': res_count, } return render(request, 'results.html', context) Here everything works fine as expected, but the searched results takes too much of time for the table having over a million records. How can I optimize the query to get the results faster ? Really appreciate for anyone who can help me this. -
How to do filtering in DateTime as null in Django rest framework?
I just want to build the filtering API with Django rest framework. One field is datetime2. I want to filter the records that have NULL value as datetime2. Here is my models.py ruleend = models.DateTimeField(db_column='RuleEnd', blank=True, null=True) Here is my serializer.py class ProductPriceSerializer(serializers.ModelSerializer): class Meta: model = ProductPrice fields = ['pricingruleid', 'productkey', 'productcode', 'customerid', 'customerchain', 'productpriceusd', 'rulestart', 'ruleend', 'creatorupn', 'created', 'customername', 'productdescription'] Here is views.py class ProductPriceViewSet(viewsets.ModelViewSet): serializer_class = ProductPriceSerializer pagination_class = pagination.PageNumberPagination filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_fields = ['customerid', 'customername', 'productkey', 'productdescription', 'ruleend', 'rulestart'] ordering_fields = ['customerid', 'productkey', 'rulestart'] def get_queryset(self): self.pagination_class.page_size_query_param = 'page_size' return ProductPrice.objects.all() urls.py path('productprice/', ProductPriceViewSet.as_view({'get':'list','post':'create'}), name="product-price"), This makes me implement pagination, filtering and sorting very easy. But I have one problem. I need to filter the records that have the null value in ruleend. What is the valid date/time of null? Or should I add something to my backend?