Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a Wagtail "ChoiceBlock" with dynamic choices rather than a hardcoded list
We have a setup with a Blog model that has a manytomany relation for BlogPageCategory, and we have a "recent blog posts" streamfield block that lets you specify whether to show cards for X latest blog posts, or X latest blog posts from a specific category. As such, we started with the following code: from wagtail.core import blocks class RecentBlogEntries(blocks.StructBlock): title = blocks.CharBlock( required=True, ) category_filter = blocks.ChoiceBlock( label='Filter by Category', required=False, choices=[ ('all', 'All'), ('First Category', 'First Category'), ('...',. '...'), ], ) ... But hardcoding the categories is kind of silly, and being able to pick them from "what the list is, right now, based on the CMS data for BlogPageCategory" would be far more convenient. However, the following code (of course) turns into an equally hardcoded migration: from wagtail.core import blocks from ... import BlogPageCategory class RecentBlogEntries(blocks.StructBlock): title = blocks.CharBlock( required=True, ) choices = [ (cat.name, cat.name) for cat in BlogPageCategory.objects.all()] choices.sort() choices.insert(0, ('all', 'All')) category_filter = blocks.ChoiceBlock( label='Filter by Category', required=False, choices=choices, ) ... Is there any way to make this a dynamic value instead of a list that is fixed by makemigrations? -
How to use post_save signal with custom user model extended with AbstractBaseUser
There are two apps in my ecommerce website and i have been following a particular tutorial on youtube. In the course, the guy used django-allauth package for login purposes. I followed the course along but I created custom user model exending AbstracBaseUser class in account app. I created another app called product where I handled all the ecommerce logics. Here's the code: models.py (account) class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, gstin_no, phone_no, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") if not first_name: raise ValueError("Users must have First Name") if not last_name: raise ValueError("Users must have Last Name") if not gstin_no: raise ValueError("Users must have a valid GSTIN Number") if not phone_no: raise ValueError("Users must have a valid Phone Number") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, gstin_no=gstin_no, phone_no=phone_no, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, gstin_no, phone_no, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, first_name=first_name, last_name=last_name, gstin_no=gstin_no, phone_no=phone_no, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', … -
Template tags not rendering in HTML
I am building a skeleton django website, but can't manage to get the template tags to render for what I thought would be a simple test. Currently, the template tags just appear as text (i.e. it just says '{{ test }} and end' when I look at the website. I am sure the problem is obvious, but I am not very experienced with django. I am not running into any errors though, so if there is any debugging advice that would be helpful. Please let me know if I have missed any key information. views.py from django.shortcuts import render from .models import Forms def home(request): return render(request, 'kb/home.html', {'test': 'begining'}) home.html <html> <head> <title>Kinbank</title> </head> <body> <p>Hi there!</p> <p>{{ test }} and end </p> </body> </html> urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.home, name='home'), ] -
Python django.How can I enter the text selected by the user with a drop-down element in the name_znat field
There is an html form with dropdown elements: <form method = "POST" action = "{% url 'create_group_handler'%}"> <select name = "select"> <! - Add an identifier here instead of using 'name' -> <option value = "value1"> Value 1 </ option> <option value = "value2" selected> Value 2 </ option> <option value = "value3"> Value 3 </ option> </ select> </ form> And there is a Python django model: Znat Class (models.Model): name_znat = models.CharField ('Name znat', max_length = 200) Suppose that the user selects a drop-down element with the text "Value 2". How can I enter the text selected by the user with a drop-down element in the name_znat field -
Django channels freezes
I'm trying to create a Django Channels consumer which receives some data in real time from a RabbitMQ queue and then sends this data to a frontend, in order to let users have real-time data. Here is my basic consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='Test') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume( queue='Test', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') await self.send({ "type": "websocket.accept" }) await channel.start_consuming() async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) And here is my Javascript code: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ wsStart = 'wss://' } socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("message", e) } socket.onerror = function(e){ console.log("message", e) } socket.onclose = function(e){ console.log("message", e) } </script> The problem with this code is that, altough in my console i will see the queue waiting for data, on my HTML page i won't see any … -
Check the instance of a Mocked method called once
My function looks for a Actor object in the database and calls its do_something() method with a passed argument. from my_app.models import Actor def my_function(id, stuff): actor = Actor.objects.get(id=id) return actor.do_something(stuff) I want my unit test to check two things : 1. my_function finds the Actor I want. 2. my_function calls the actor's do_something method as expected. from unittest import mock from django.test import TestCase from my_app.models import Actor from my_app.views import my_function class ViewsTestCase(TestCase): @classmethod def setUpTestData(cls): self.actor = Actor.objects.create(id=42, name='John') def test_my_function(self): with mock.patch.object(Actor, 'do_something') as mock_do: my_function(id=42, stuff='a-short-string') mock_do.assert_called_once_with('a-short-string') This works to make sure my_function called do_something like I wanted but I don't know how to be sure it found the Actor I asked him to find. This test would pass even if my_function found the wrong actor. Is there any way to check that ? -
Django Admin: How to set the background-color for a datafield
I have a choice datafield and in the admin page I want to highlight its value with a background-color: YES = green NO = red I can set the background-color for a function field (see also image): fields = ['_kw', 'status'] readonly_fields = ['_kw'] def _kw(self, obj): return mark_safe('<span class="{}">{}</span>'.format(obj.status, obj.kw)) class Media: css = { 'all': ('myapp/admin.css',) } But I dont know how to achieve this with a datafield. Any ideas? If possible, I dont want to customize the admin-template or use a 3rd party app. my admin page -
Django-xhtml2pdf and static css files
So I've encountred a problem with Django and the xhtml2pdf module. I am trying to create PDFs from my pdf.html template which contains UNICODE characters which get displayed as ■■■■ in the PDF files. I tried to use CSS in the html file directly or in a separate file but no matter what i try i can't seem to figure it out. My PDF.html file: {% load static %} <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style> {% include "pdfstylefonts.css" %} </style> <link rel='stylesheet' href="{% static 'pdfstyle.css' %}"/> </head> <body> <h1>árvíztűrő tükörfúrógép</h1> </body> </html> My PDFSTYLEFONTS.CSS {% load static %} @font-face { font-family: "Calibri"; src: url({% static "fonts/calibri.ttf" %}); } @font-face { font-family: "Calibri"; src: url({% static "fonts/calibrib.ttf" %}); font-weight: bold; } @font-face { font-family: "Calibri"; src: url({% static "fonts/calibrii.ttf" %}); font-style: italic, oblique; } @font-face { font-family: "Calibri"; src: url({% static "fonts/calibriz.ttf" %}); font-weight: bold; font-style: italic, oblique; } My PDFSTYLE.CSS h1 { color: blue; } *, html { font-family: "Calibri"; font-size:11pt; color: red; } My View from views.py def pdf_view(request): adat = get_object_or_404(Egyenleg,user=request.user) template = get_template('pdf.html') context = {'Data':adat} html = template.render(context) pdf = render_to_pdf('pdf.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "PDF%s.pdf" %("12341231") content = … -
How to fetch parent child hierarchy using django rest-framework
I am new to Django rest-framework. I am writing an API to fetch details in a parent-child hierarchy. Following is my code; models.py class ConfigAttributes(models.Model): attr_set_name = models.CharField(max_length=32) product_type = models.CharField(max_length=32) class ProductInfo(models.Model): config_attr = models.ForeignKey(ConfigAttributes, on_delete=models.CASCADE) product_name = models.CharField(max_length=32) class AttributeDetails(models.Model): product_info = models.ForeignKey(ProductInfo, on_delete=models.CASCADE) attribute_name = models.CharField(max_length=32) serializers.py class ConfigAttributesSerializer(serializers.ModelSerializer): class Meta: model = ConfigAttributes fields = ['id', 'attr_set_name', 'product_type'] class ProductInfoSerializer(serializers.ModelSerializer): class Meta: model = ProductInfo fields = ['id', 'product_name', 'config_attr_id'] class AttributeDetailsSerializer(serializers.ModelSerializer): class Meta: model = AttributeDetails fields = ['id', 'attribute_name', 'product_info_id'] views.py class ConfigAttributesViewSet(viewsets.ModelViewSet): queryset = ConfigAttributes.objects.all() serializer_class = ConfigAttributesSerializer class ProductInfoViewSet(viewsets.ModelViewSet): queryset = ProductInfo.objects.all() serializer_class = ProductInfoSerializer class AttributeDetailsViewSet(viewsets.ModelViewSet): queryset = AttributeDetails.objects.all() serializer_class = AttributeDetailsSerializer and app/urls.py router = routers.DefaultRouter() router.register('config', ConfigAttributesViewSet) router.register('product', ProductInfoViewSet) router.register('attr', AttributeDetailsViewSet) urlpatterns = [ path('', include(router.urls)), ] When I call the API, my required hierarchy and output is; [ { "attr_set_name" : "abc", "product_type" : "efg", "product_info" : { "product_name" : "hij", "attribute_details" : { "attribute_name" : "klm" } } } ] What are the changes need to done in the files to get the above output in hierarchy (I am using Postman to check my APIs). Thank you for the help. -
Export csv from Django Detail View
I am trying to export data from a browser in a Django detailview. The DetailView is of the model OsmoClient, and the data I would like to export is in the model FinancialData, which is linked to OsmoClient by foreignkey. models.py class OsmoClient(models.Model): created = models.DateTimeField(auto_now_add=True) client_code = models.CharField(max_length=250, blank=True) osmo_client_ref = models.CharField(max_length=250, blank=True) def __str__(self): return self.client_code def get_absolute_url(self): #used to create a unique URL page for each object return reverse('osmoclient-detail',args=[str(self.id)]) def get_fields(self): #Needed so that we can iterate over the fields in the html view, rather than typing them out. return [(field.verbose_name, field.value_from_object(self)) for field in self.__class__._meta.fields] class FinancialData(models.Model): osmo_client = models.ForeignKey(OsmoClient, on_delete=models.CASCADE) bank_balance = models.IntegerField() sales_balance = models.IntegerField() daily_movement_in_sales = models.IntegerField() trade_debtors_balance = models.IntegerField() trade_creditors_balance = models.IntegerField() date_created = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = "Financial Data" unique_together = ['osmo_client', 'date_created'] #Needed so that each client can only have one set of financial data per day ordering = ['osmo_client'] def __str__(self): return str(self.osmo_client) + str(self.date_created) def get_absolute_url(self): #Used to generate a unique URL page for each object return reverse('financialdata-detail', args=[str(self.id)]) def get_fields(self): #Needed so that we can iterate over the fields in the html view, rather than typing them out. return [(field.verbose_name, field.value_from_object(self)) for field in … -
Django get_context_data overrides get_object
Django 3 Python 3.8 In a class based detail view, why does the get_context_data function override the get_object? I have a Detail view in which I want to look at an item {{ object }} but I also want to add a list to the template. I created a get_context_data and returned {"fields": [1,2]} however when I went to the template, I could run {% for x in fields %} {{ x }} {% endfor %} but now {{ object }} returned blank! How can I use both the get_object and the get_context_data or should i put the object in the context? Thanks -
How to send an email using django and ajax
Hello I'm working on a Django contact form that enables a user to send an email, previously the email was being sent but the page was reloading so decided to use ajax Here's my javascript code, the ajax code $('.menu').click(function(){ $('.toggle').toggleClass('active'); }) $(document).on('submit', '#contact_form', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/contact', data:{ from_email:$('#id_from_email').val(), subject:$('#div_id_subject').val(), message:$('#div_id_message').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ alert("Message sent succsessfuly") } }) }) }); This is my views, getting the data and sending email if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST or None) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] reply_to=[from_email] msg_mail = str(message) + " " + str(from_email) try: send_mail( subject, message, from_email, ['kimkidati@gmail.com'], reply_to, ) except BadHeaderError: return HttpResponse('Invalid header found.') messages.add_message(request, messages.SUCCESS, 'Email sent successfully.') return render(request, "contact.html", {'form': form,}) My template, here is my django form where i collect the user message and email <h1>Contact Us</h1> {% if message %} {% for message in messages %} <p class="text-black mt-5 pt-5">{{message}}</p> {% endfor %} {% endif %} <form id="contact_form" method="POST" data-url='/contact'> {% csrf_token %} <p>{{form|crispy}}</p> <div class="form-actions mb-5"> <button class="btn btn-primary btn-sm" type="submit">Send Message</button> </div> </form> </div> ``` **Also had an issue with the email which does not specify who … -
MySQL connection pooling in Python2.7 doesn't work as expected. Facing issue with close() function of connection pool
I have taken the python sample code for MySQL Connection pool and tried to execute it with django framework. I'm able to execute the queries and retrieve the data if I don't close the cursor and connection object. When I call close() function connection object it's failing with following error, Please help me to solve this. ProgrammingError at /settings 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Method: GET Request URL: http://sample.app.com/settings Django Version: 1.11.5 Exception Type: ProgrammingError Exception Value: 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Exception Location: venv/local/lib/python2.7/site-packages/mysql/connector/connection.py in _auth_switch_request, line 256 Python Executable: venv/bin/python2 Python Version: 2.7.17 The code which I'm using, Coding in bold are creating the issue. If don't close connection, its working fine. when i close it doesn't work and throws an error. db_pool.py import mysql.connector.pooling dbconfig = { "host":"127.0.0.1", "port":"3306", "user":"root", "password":"root", "database":"test", } class MySQLPool(object): """ create a pool when connect mysql. """ def __init__(self, host="127.0.0.1", port="3306", user="root", password="root", database="test", pool_name="mypool", pool_size=3): res = {} self._host = host self._port = port self._user = user self._password = password self._database = database res["host"] = self._host res["port"] = self._port res["user"] = self._user res["password"] = self._password res["database"] = self._database self.dbconfig = … -
Django AJAX not updated after POST was called
I have this fat GET request in ajax . Is this GET request in some way q bad practice considering the looping of elements? let pages = 0; $.ajax({ url: '/posts/', method: 'GET', dataType: 'json', success: function (data) { let totalObjects = Object.keys(data.posts).length.toString(); # check how much pages should be displayed based on data length let rows = ''; data.posts.forEach(post => { rows += '<tr class="postTable" style="display: none;">' + '<th scope="row"><input type="checkbox" aria-label="Checkbox" style="display: none"></row>' + '<td class="tm-product-name"><a href="' + '/posts/' + post.slug + '/edit/">' + post.title + ' </a></td>' + '<td class="text-center">145</td>' + '<td class="text-center">' + post.total_likes + '</td>' + '<td>' + post.created_at + '</td>' + '<td><i class="fas fa-trash-alt tm-trash-icon" id="delete-icon" data-id="'+ post.slug + '"></i></td>' + '</tr>'; }); $('tbody').append(rows); let current_page = ''; let tables = document.getElementsByClassName('postTable'); $('#pagination-test').twbsPagination({ totalPages: pages, visiblePages: 5, onPageClick: function (event, page) { console.log('ALARMM'); current_page = page; console.log('PAGE Changed'); console.log('Page: ' + current_page); switch (current_page) { # here i'm looping all the elements via switch case for pagination. } }, }); } }); ajax POST $(document).on('click','tr[class="postTable"] td i[id="delete-icon"]' ,function () { let action = confirm('Are you sure you want to delete this post?'); let slug = $(this).attr('data-id'); console.log(slug); let url = '/posts/' + slug + … -
GAE production + Django + Gunicorn Error: HaltServer 'Worker failed to boot.' 3
I run my Django project on localhost by 'python manage.py runserver' - it works. I deploy it on Google App Engine - on xxx.appspot.com it print 502 Bad Gateway/by Ngnix and raise followed: gunicorn.errors.HaltServer: Traceback (most recent call last): File "/env/bin/gunicorn", line 10, in <module> sys.exit(run()) File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 228, in run super().run() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 229, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 342, in halt self.stop() File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 380, in stop and not self.cfg.reuse_port File "/env/lib/python3.7/site-packages/gunicorn/config.py", line 201, in reuse_port @property File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 242, in handle_chld self.reap_workers() File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Python 37 Django 2.1.14 I`m first time with Django&GAE, pleese help -
How to create a child object in Serializer Django Rest?
I have a task, I need to return this json object here: { "id": "99999999", "point": "11111111", "name": "some name", "quantity": { "needed": "10", "done": "2", }, } I must have the quantity field as a child object, but in the Django model quantity_needed and quantity_done must not be child objects. Here is the code: # model.py class NeedModel(models.Model): article = models.ForeignKey(ArticleModel, on_delete=models.CASCADE) point = models.ForeignKey(PointModel, verbose_name="Hospital", on_delete=models.CASCADE) quantity_needed = models.PositiveIntegerField(default=0) quantity_done = models.PositiveIntegerField(default=0) I tried to change this using the to_representation method, here's what my code looks like: # serializer.py class NeedsSerializer(ModelSerializer): class Meta: model = NeedModel fields = ('id', 'point') def to_representation(self, instance): data = super(NeedsSerializer, self).to_representation(instance) data['name'] = instance.article.name data['quantity'] = { 'needed': instance.quantity_needed, 'done': instance.quantity_done, }, return data But as a result, I get a quantity field with a list that contains the object. How to get rid of this list? { "id": 6, "point": 4, "name": "Бинт гіпсовий 20см х2,7м", "quantity": [ { "needed": 12, "done": 0 } ], }, -
Django rest framework model is not visible in admin site
I'm working on a simple DRF API and I can't seem to access one of my many models from the admin site, although I can access some models from the same Application, please help! project/app/models.py looks something like this: class ImportantModel(models.Model): name = # character field relation1 = # foreign key relation2 = # foreign key ... class Contact(models.Model): information = # character field ... The problem is I can see the Contact model(and multiple other models) from the admin site(http://localhost:8000/admin/) but ImportantModel is not showing. Thank you in advance. -
Django Model inheritance: model child class creating extra rows in model parent class data-table
I am trying to apply basic model inheritance based on the Django documentation. The end goal is to access the shared id of the Exam and Date models in the get_date_info view, which is called after the get_exam_info view. Perhaps there is a better way to do this than model inheritance, but this seemed the most straight forward to me. Here is the relevant Model code: class Exam(models.Model): instructor_first_name = models.CharField(max_length=30) instructor_last_name = models.CharField(max_length=30) department = models.CharField(max_length=30, null=True) course_name = models.CharField(max_length=30, null=True) course_number = models.IntegerField(null=True) section_number = models.IntegerField(null=True) num_students = models.IntegerField(null=True) calculator = models.CharField(max_length=30, blank=True) notes = models.CharField(max_length=30, blank=True) computer_exam = models.BooleanField(default=False) scantron = models.BooleanField(default=False) timed = models.BooleanField(default=False) dictionary = models.BooleanField(default=False) comment = models.CharField(max_length=300, blank=True) class Date(Exam): start_date = models.DateField() end_date = models.DateField() late_start_date = models.DateField(blank=True, null=True) late_end_date = models.DateField(blank=True, null=True) Here is the relevant view code: def get_exam_info(request): if request.method == 'POST': exam_form = ExamForm(request.POST) if exam_form.is_valid(): exam_form.save() date_form = DateForm() return render(request, 'date_info.html', {'date_form': date_form}) else: exam_form = ExamForm() return render(request, 'exam_info.html', {'exam_form': exam_form}) def get_date_info(request): exam_request = Exam.objects.all() if request.method == 'POST': date_instance = Date() date_form = DateForm(request.POST, instance=date_instance) if date_form.is_valid(): date_form.save() current_user_id = date_instance.exam_ptr_id print(current_user_id) return HttpResponseRedirect('/') else: date_form = DateForm() return render(request, 'date_info.html', {'date_form': date_form}) … -
django-serializers error inside a virtualenvironment
I am trying to install the django serializers-module inside a virutal environment. It gives me an error and I don't know how to get around it. I have tried on 2 computers and a vps and get the same error. It works outside of the virtual environment but not inside. This is what gets the error: mkdir test-pi; cd test-pi/; virtualenv -p python3 .; source bin/activate; pip install django-serializers; This is the error ERROR: Command errored out with exit status 1: command: /home/owner2/Dev/BELove/src/belove/test-pi/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-o2kpa85w/django-serializers/setup.py'"'"'; __file__='"'"'/tmp/pip-install-o2kpa85w/django-serializers/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-o2kpa85w/django-serializers/pip-egg-info cwd: /tmp/pip-install-o2kpa85w/django-serializers/ Complete output (6 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-o2kpa85w/django-serializers/setup.py", line 56 print "You probably want to also tag the version now:" ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("You probably want to also tag the version now:")? ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django 2.0: Display a Select widget as HTML in the List View table
I have a Django 2.0 app. One class in the admin interface ("list" view, not "change"!) needs a column with a select dropdown with numbers from 1:10, and a Submit button. From the docs I understood that I should use a "Select" widget and define a form. I am curious if it's possible to do with just admin.py and my model, without involving forms.py, templates, etc. So I tried this: class MyClassAdmin(SuperAdmin): list_display = ["inline_mycolumn", "other_field1", "etc"] def mycolumn(self, my_object): from django import forms MY_CHOICES= [tuple([x,x]) for x in range(1,11)] return mark_safe(forms.Select(choices=MY_CHOICES)) .....the rest of the class code.... This below of course does not render the widget as select dropdown, in the source of the table it comes as: <th class="field-column"><a href="/admin/<myapp>/<my_model_name>/<record id>/change/"><django.forms.widgets.select object="" at="" 0x7f4fea267828=""></django.forms.widgets.select></a></th> and the cell stays empty. The rest of the table is rendered as it should. And without mark_safe it just prints the object's name in the cell: format_html (I had to try!) gives 'Select' object has no attribute 'format' Maybe there's a way to cast that widget object into HTML representation with just admin.py code? Thanks -
Azure Nginx splitted frontend and backend - proxy
Need some help with Microsoft Azure and Docker and Nginx. I got an website where backend and frontend are splitted (django and react) with docker. They are working on Microsoft Azure Virtual machine and they are working without nginx but now i am trying to use nginx to proxy urls to the right ports. With below links i can access two parts of my website and i want to change it to: mywebsite.northeurope.cloudapp.azure.com:8000 < this is backend of my website mywebsite.northeurope.cloudapp.azure.com:3000 < this is frontend of my website And below are the options which i would like to have mywebsite.northeurope.cloudapp.azure.com\back < this is backend of my website mywebsite.northeurope.cloudapp.azure.com\front < this is frontend of my website Below are my files: docker-compose version: '3' services: db: image: postgres:9.6-alpine environment: POSTGRES_DB: db POSTGRES_USER: me POSTGRES_PASSWORD: mypassword volumes: - ./data/postgres:/var/lib/postgresql/data my_django_web: image: my_image_backend build: ./backend/django_dashboard command: > bash -c " source ./env.sh && gunicorn django_dashboard.wsgi:application --bind 0.0.0.0:8000 --chdir ./backend/django_dashboard/" volumes: - .:/code expose: - 8000 depends_on: - db restart: "on-failure" nginx: build: ./nginx ports: - 1337:80 depends_on: - my_django_web frontend: image: my_image_frontend build: ./frontend/dashboard volumes: - ./frontend/dashboard:/code/frontend/dashboard ports: - "3000:3000" Dockerfile for nginx that changes my website from localhost:8000 to localhost:1337 FROM nginx:1.17.4-alpine RUN … -
How to set default value to None for Django choices form field
The below Django form works, but for the life of me I can't figure out how to make the ModelChoiceField for operator blank or set to None by default. I would like the user to have the option of just leaving this choices field set to None. This autopopulates with the first user in the user list. Model class Build(models.Model): PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE) author = models.ForeignKey(get_user_model(),related_name='+',on_delete=models.CASCADE,blank=True, null= True,) plannedAuthor = models.ForeignKey(CustomUser,related_name='+',blank=True, null= True, on_delete=models.CASCADE) status = models.CharField(max_length=100,blank=True,) operator = models.ForeignKey(CustomUser,related_name='+',blank=True, null= True, on_delete=models.CASCADE, default=None) View class queuedBuild_CreateView(LoginRequiredMixin,CreateView): model = Build form_class = queuedBuild_Creation_Form template_name = 'addQueuedBuild.html' login_url = 'login' success_url = reverse_lazy('equipmentdashboard') def get_form(self, form_class=None): form = super().get_form(form_class) customer = self.request.user.PSScustomer form.fields['operator'].choices = [(item.id, item.first_name) for item in CustomUser.objects.filter(isDevice=False, PSScustomer = customer)] return form Form class queuedBuild_Creation_Form(forms.ModelForm): buildDescrip = forms.ModelChoiceField(initial='Your name') def __init__(self, *args, **kwargs): super(queuedBuild_Creation_Form, self).__init__(*args, **kwargs) self.fields['status'].required = True class Meta: model = Build fields = ['status', 'operator',] -
Not able to start `django` project in local as well as in docker
I am using Docker to deploy Python2.7 application with Django1.8. I am facing some issue from last two days and I found error as below. Error: root@64f8c580dd0a:/code# python manage.py runserver read completed! read completed! Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/site-packages/imagekit/__init__.py", line 2, in <module> from . import conf File "/usr/local/lib/python2.7/site-packages/imagekit/conf.py", line 1, in <module> from appconf import AppConf File "/usr/local/lib/python2.7/site-packages/appconf/__init__.py", line 1, in <module> from .base import AppConf # noqa File "/usr/local/lib/python2.7/site-packages/appconf/base.py", line 107 class AppConf(metaclass=AppConfMetaClass): ^ SyntaxError: invalid syntax uwsgi configuration: [uwsgi] wsgi-file = /code/config/wsgi.py callable = application uid = nginx gid = nginx socket = /tmp/uwsgi.sock chown-socket = nginx:nginx chmod-socket = 664 master = true cheaper = 5 processes = 15 vacuum = true I have installed below dependencies: Babel==2.8.0 beautifulsoup4==4.4.1 boto==2.38.0 boto3==1.4.4 botocore==1.5.95 cffi==1.14.0 contextlib2==0.6.0.post1 copyleaks==2.5.1 cryptography==2.8 dce-lti-py==0.7.4 Django==1.8 django-admin-honeypot==1.0.0 django-allauth==0.31.0 django-appconf==1.0.4 django-ckeditor==5.2.2 django-colorful==1.0.1 django-common-helpers==0.9.2 django-cors-headers==1.0.0 django-cron==0.5.0 django-debug-toolbar==1.6 django-environ==0.4.3 django-extensions==1.5.0 django-filter==1.1.0 django-hosts==2.0 django-imagekit==4.0.1 … -
django-elasticsearch-dsl with a nested field
I'm trying to use django-elasticsearch-dsl with AWS ElasticSearch service 7.4 and I'm trying to implement a NestedField. I cannot get the queries to work on the nested field So my model is defined as class MyModel (models.Model): name = models.CharField(max_length=101) ... my_other_model = models.ManyToManyField( 'MyOtherModel', blank=True, ) my_third_model = models.ManyToManyField( 'MyThirdModel', blank=True, ) class MyOtherModel(models.Model): name = models.CharField(max_length=101) class MyThirdModel(models.Model): name = models.CharField(max_length=101) My ES document is defined @search_index.document class MyModelDocument(Document): name = fields.TextField() my_other_model = fields.NestedField(properties={ 'name': fields.TextField() }) my_third_model = fields.NestedField(properties={ 'name': fields.TextField() }) I then try to search on this s = MyModelDocument.search() This works s.query( 'nested', path='my_other_model', query=Q('match', my_other_model__name='ABC') ) BUT I need to search a list, so I'm trying the following, but it returns nothing s.query( 'nested', path='my_other_model', query=Q('terms', my_other_model__name=['ABC','DEF']) ) How to I achieve this? -
How to make a query to get column difference between two followed rows
I'm trying to get the difference between a row column and the next row column. For example: pk | hour | ts ----+-------+---- 1 | 10:30 | 0 2 | 10:50 | 20 3 | 11:00 | 10 Where ts is the difference between hour column between next element and current I don't want to get all objects and then do this using python because in production there will be a lot of rows and I heard it becomes inefficient. So I've tried several ways. Option 1 - Using raw sql with LAG: Computer.objects.raw(''' SELECT id, hostname, date, date - LAG (date) OVER (ORDER BY date) AS lagged FROM hub_computer ''') When accessing an element, it gives the following error: Traceback (most recent call last): File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near "(": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1461, in __getitem__ return list(self)[k] File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1421, in __iter__ self._fetch_all() File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1408, in _fetch_all …