Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django Betterforms: how to pass initial values to FilterForm
Doc of django-betterforms: https://github.com/fusionbox/django-betterforms I've tried three different strategies, none works: 1) in the field definition: date_from = DateTimeField(label=_('Date from'), initial='{:%Y-%m-%d}'.format(datetime.date.today()), required=True ) 2) In the form init: def __init__(self, *args, **kwargs): updated_initial = {} updated_initial['date_from'] = '{:%Y-%m-%d}'.format(datetime.date.today()) kwargs.update(initial=updated_initial) super().__init__(*args, **kwargs) 3) In the get_initial of the BrowseView that uses this form: def get_initial(self): initial = super().get_initial() initial['date_from'] = '{:%Y-%m-%d}'.format(datetime.date.today()) return initial None of them works. Any ideas on how to populate the FilterForm of the BrowseView with initial values? -
How to assign value of field of one model to field of another model?
Say, I have a view function that creates a Vacancy object on saving the form, and it has the field company that, if the form is valid, has to be assigned with value of field name, that is on the other model named EmployerProfile, how can I do that? I have company as a foreign key on my model. My models class EmployerProfile(models.Model): name = models.CharField(max_length = 64) description = models.TextField() username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) class Vacancy(models.Model): name = models.CharField(max_length = 64) competences = models.CharField(max_length = 32) salary = models.DecimalField(decimal_places = 2, max_digits = 10) description = models.TextField(null = True) company = models.ForeignKey(EmployerProfile, on_delete = models.CASCADE) featured = models.BooleanField(default = False) My view @login_required(login_url = 'login') def vacancyAddView(request): if request.method == 'POST': form = VacancyAddForm(request.POST) if form.is_valid(): form.save() return redirect('profile') else: form = VacancyAddForm() context = { 'form':form } return render(request, "addVacancy.html", context) My form class VacancyAddForm(forms.ModelForm): class Meta: model = Vacancy fields = [ 'name', 'competences', 'description', 'salary', ] P.S. I have tried adding this piece of code to my view, rigth after form.is_valid(): obj = EmployerProfile.objects.get(username = request.user) form.instance.company = obj.name but it didn't work, it returned the ValueError with text "Vacancy.company" must be a "EmployerProfile" … -
Django Bootstrap Dropdown Menu not working
Building my first Django app from a tutorial, following the instructions pretty much verbatim but my navbar dropdown menu is not working no matter what I try, so unable to log out or change password from the navbar. I am very new to js, but some things I have tried: Experimenting w different browsers (doesn't work for Safari or Chrome) Have looked at similar questions and implemented those techniques but it's still not working (linking to js in the head, making sure to link to js/popper/bootstrap in the correct order, etc.): django bootstrap dropdown not working Have also attempted to create static folders in pages/static/js and pages/static/css but that looks like it may be for more advanced styling than what we're going for here. Bootstrap template not working correctly Django Template file/directory below. Issue is between lines 55 and 68 (div class="collapse navbar-collapse") Thanks in advance for the help. <!-- templates/base.html --> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/\ 1.14.3/ umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAKl8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/\ js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ\ 6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <!-- Bootstrap … -
Factory Boy test with Wagtail fails: TypeError: Field 'id' expected a number but got {}
I'm trying to set up Factory Boy for a Wagtail site. In order for that to work, the _create method must be able to establish a parent-child-relationship between pages. I override the _create method as described in the docs: https://factoryboy.readthedocs.io/en/latest/reference.html#attributes-and-methods. But the addition of the 'parent' key causes the error. Have been looking at it for ages, dug into the source files. I suspect it has to do with the way the model_class method passes the kwargs, but I guess I'm blind for any obvious mistakes by now. Any help would greatly be appreciated! models.py: from wagtail.core.models import Page class HomePage(Page): pass class SubjectPage(Page): pass tests.py: from .factories import HomePageFactory, SubjectPageFactory from django.test import TestCase class TestModels(TestCase): @classmethod def setUpTestData(cls): cls.homepage = HomePageFactory(title='Test page') cls.subjectpage = SubjectPageFactory(parent=cls.homepage) def test_dummy(self): self.assertTrue(True) factories.py: import factory from .models import HomePage, SubjectPage from wagtail.core.models import Page class PageFactory(factory.django.DjangoModelFactory): class Meta: abstract = True @classmethod def _create(cls, model_class, *args, **kwargs): try: parent = kwargs.pop('parent') page = model_class(*args, kwargs) except KeyError: parent = Page.get_first_root_node() page = model_class(*args, **kwargs) parent.add_child(instance=page) return page class HomePageFactory(PageFactory): class Meta: model = HomePage class SubjectPageFactory(PageFactory): class Meta: model = SubjectPage -
[Django} Is there a way for a user to create a group and add other users?
I've tried to find resources on this but it all directs me to groups in admin. Like I want to be able for a user to create a group and add fellow users to that group. This group will then have permissons of editing a "to-do list".