Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering model w/ linkable foreign key as table on referenced model's detail page w/ django-tables2
I have two models -- Sample, and Publication. Each model has a list view and a detail view. I know I can render the sample list (sample_list.html) with {% render_table sam %} and the same with publication list (publication_list.html) with {% render_table publication_table %}. In these respective tables, clicking on a sample cell will take the user to the detail view of that sample (sample_detail.html) and clicking on a title_p cell in the table will take the user to the publication_detail.html page. What I want to do is a) render a list of publications that are related to a specific sample on the sample_detail.html page, and b) on the same page, have the title_p cell -- go to publication_detail.html. a) How do I render (django-tables2) a table on sample_detail.html with publication objects that are related to a specific sample when the sample is a foreign key in the publication model? The only way I have been able to do it is by hardcoding a html table using this approach: {% for p in sample.publication_set.all %} <tr> <td><a href="{% url 'sample-detail' p.sample.pk %}">{{ p.sample }}</a> </td> <td><a href="{#%# url 'publication-detail' p.title_p_id #%#}">{{ p.title_p }}</a> </td> ... Other approaches to table rendering … -
django celery AsyncResult AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for'
I am using django celery(4.2) and I will add some task from my django view, also I want to get the task result async in a separate process, but when I try to get the result, I got some errors. My full steps is as following: django celery config: proj/settings/celery.py import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Nuwa.settings.development') app = Celery('Nuwa') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() proj/settings.py CELERY_BROKER_URL = f'redis://{REDIS["HOST"]}:{REDIS["PORT"]}' CELERY_RESULT_BACKEND = f'redis://{REDIS["HOST"]}:{REDIS["PORT"]}' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' proj/settings/init.py from .celery import app as celery_app __all__ = ('celery_app', ) call celery task in one django view: result = port_scan.delay(target) redis_conn.sadd(celery_task_set_key, result.task_id) in this step, I store the task_id in redis set for future use. get the task result redis_conn = redis.Redis(host=REDIS_HOST, port=REDIS_PORT) celery_tasks = redis_conn.smembers('celery-tasks') for task_id in celery_tasks: print(task_id) celery_result = AsyncResult(task_id) print(celery_result.state) when I try to get the result, it have error: AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' I try some solutions by search google and so, it doesn't work. -
Parenthesis(like) precendence order in django templates
i' ve multiple | used in django templates, and i' d like to know is it somehow possible to force a precendence order (like parenthesis in arithmetics)? I' ve a pretty much complicated data structure where from i' d like to use the date with 8 digits, but the month and day is stored without the leading zero: {% url 'diary' year.0|add_str:month.0|add_str:forloop.counter %} would result only 201847 instead of 20180407 . A correct way would be somehow: year.0|add_str:(month.0|stringformat:'02d')|add_str:(forloop.counter|stringformat:'02d') , but of course the parenthesis does not work here. How can i achieve my goal in the django template language? Of course an easy solution would be to write a filter, but i' d like to know the possible solution in the template language. -
What are DIRS and APP_DIRS in django ? and what is it use for?
I am making a django app and when I was reading about template loaders I saw this: You can enable this loader simply by setting APP_DIRS to True: TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }] what is this doing ? and what are the uses of DIRS? -
tests fail because client's request.user is SimpleLazyObject
The following test code fails because in view_report, request.user is a SimpleLazyObject. How to I prepare the calling client properly to test my views? class Test_views(TestCase): def test_case(self): c = Client() c.login(username=username,password='password') url = reverse('coach:view_report', kwargs={'report_id':13}) c.get(url,follow=True) def view_report(request, report_id): current_user = Coach.objects.get(id=request.user.id) -
How to customize django imagefield input in HTML
I have a django-form with an ImageField that I'm rendering in the HTML template. Originally, using this code, I could successfully upload an image: {% for field in form %} {% if field == form.image %} {{ field.label_tag }} {{ form.image }} But I didn't like django's styling so I customized it using Bootstrap 4. This is the updated HTML: {% for field in form %} {% if field == form.image %} <label class="btn btn-primary" for="my-file-selector"> <input id="my-file-selector" type="file" style="display:none" onchange="$('#upload-file-info').html(this.files[0].name)"> Choose an image </label> <span class='label label-info' id="upload-file-info"></span> Now the styling is correct, but the image won't upload successfully. Or rather, I can choose an image, but when I submit the playlist it won't be entered into the database and I therefore can't have it displayed. How can I use this styling but still successfully upload images? -
Django: How to show validation error message on modal correctly
I'd like to use form on modal. However the validation error message doesn't work as expected. Here is html {% render_entry_form as entry_form %} <form method="POST" enctype="multipart/form-data" novalidate> <div class="modal fade" id="addEntryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> {% csrf_token %} <div class="form-group"> <label>{{ entry_form.0.topic.label }}</label> {{ entry_form.0.topic|add_class:'form-control' }} </div> {{ entry_form.1.management_form }} {% for form in entry_form.1 %} <div class="form-group"> {{ form }} </div> {% endfor %} <div class="form-group"> {% if entry_form.0.description.errors %} <div class="alert alert-danger alert-dismissible"> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> {{ entry_form.0.description.errors }} </div> {% endif %} <label>{{ entry_form.0.description.label }}</label> {{ entry_form.0.description|add_class:'form-control' }} </div> </div> <div class="modal-footer"> <button type="submit" name="entry_form" class="btn btn-primary">Post</button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </form> The validation error message 'This field is required.' is already shown on the modal when appearing the modal. Also when I try to submit an invalid data, the modal is just closed and I cannot see the validation error message. How can I prevent the modal from closing when the data is invalid? Also I have another question. I organize form part as a templatetag because this part is supposed to be used in other views and I organized … -
Django using permissions in template
I would like to use permission for user in my web app written in Django for matches management. For different models I want to add different permission. For example, I put in my template condition {% if perms.refmanager.can_add %}, but here I do not precise which model. Than I assign add permission using admin, I go to the page where I put this condition and it doesn't work. I try also with: {% if perms.refmanager.match.can_add %}, didn't work. Should I specify permission for each model in models.py or there is some defult way already implemented in Django? {% if perms.refmanager.match.can_add %} <button type="button" class="btn btn-sm btn-success"> <span class="fas fa-plus fa-sm"></span> Dodaj mecz </button> {% endif %} -
how can i config django app(2.0.9) to deploy it into google cloud
I have a django application version 2.0.9 I want to publish it in google cloud I converted to carry it several times but not a gimmick, just a web page written on it 502 getaway I think the problem is in main.py and app.yaml files i use python 35 and django==2.0.9 my project arblog my app named blogArabic I'm in trouble and I can not solve the problem Is there any help and thanks -
Tweak Django forms to call a javascript function
I am trying to add some client side encryption on my django based app (Cf original post). Right now, I have a working solution I developed on a single page but I do not know how to call my function, say encrypt(), in django forms. Say I have a form called form_add. I would like the function encrypt() to be called on some of the form's fields before everything is send through the POST. Based on this article, I thought of looping through the fields of the form. However, these two attempts do not work ("SyntaxError: expected expression, got '<'") <form id="add_patient" method="post" action="add-patient/"> {% csrf_token %} <!--added_for_client_side_encryption--> <script type="text/javascript"> {% for field in form_add.visible_fields %} {{ field.label_tag }}encrypt({{ field }}) {% endfor %} </script> <input type="submit" value="Entrer"> </form> 2nd attempt: <form id="add_patient" method="post" action="add-patient/"> {% csrf_token %} <!--added_for_client_side_encryption--> {% for field in form_add.visible_fields %} {{ field.label_tag }}<script type="text/javascript">encrypt({{ field }})</script> {% endfor %} <input type="submit" value="Entrer"> </form> In both cases, my POST still contains the fields in clear. How would you manage to send encrypt() outputs? -
Django template render {{variable}} in place of empty string, if variable not set
My template contains 2 {{var1}} and {{var2}} placeholders. If I only set variable for var1: value1, then {{var2}} is also replaced by empty string. But I want {{var2}} instead of empty string code snippet: var = {var1:value1} tmp = Template(f.read(),start="{{",end="}}") data = tmp.render(var) -
how to set a default value for a model's attribute?
I created a model and then model-form to take input from user . I am trying to set the default value of author to the active user's name, but instead the default value is set to the username of admin. Please take a look at the code. models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime class tweets(models.Model): def curr_user(): for user in User.objects.all(): if user.is_active: return user.get_username z = curr_user() k = datetime.now author = models.CharField(max_length = 50,default=z) date_time = models.DateTimeField(default = k) body = models.TextField() def __str__(self): return self.body forms.py from django import forms from .models import tweets class TweetsForm(forms.ModelForm): class Meta(): model = tweets fields = "__all__" -
How to set the return value of a get request in an unit test?
I am trying to set the return value of a get request in python in order to do a unit test, which tests if the post request is called with the correct arguments. Assume I have the following code to test # main.py import requests from django.contrib.auth.models import User def function_with_get(): client = requests.session() some_data = str(client.get('https://cool_site.com').content) return some_data def function_to_test(data): for user in User.objects.all(): if user.username in data: post_data = dict(data=user.username) else: post_data = dict(data='Not found') client.post('https://not_cool_site.com', data=post_data) #test.py from unittest import mock from unittest import TestCase from main import function_with_get, function_to_test class Testing(TestCase): @mock.patch('main.requests.session') def test_which_fails_because_of_get(self, mock_sess): mock_sess.get[0].return_value.content = 'User1' data = function_with_get() function_to_test(data) assertIn('Not Found', mock_sess.retrun_value.post.call_args_list[1]) This, sadly, does not work and I have also tried to set it without content, however, I get an error AttributeError: 'str' object has no attribute 'content' What would be the correct way to set the return_value of the get request, so that I can test the arguments of the post request? -
Is Django Rest Framework preventing cookies from being sent?
I have a very simple viewset that looks like this: class CurrentUserApi(viewsets.ViewSet): def list(self, request): print(request.session.get("works", None)) request.session["works"] = "it works" return Response({}) which is exposed by: router = routers.DefaultRouter() router.register(r"current-user", CurrentUserApi, base_name="CurrentUser") and: url("^api-v1/", include(router.urls)) My web application runs, the code in the server executes, the session is created in the django_session table but the response from Django Rest Framework doesn't seem to include any cookies: The session works just fine when logging in as an admin to the Django admin tool. I think this is related to CORS, because I'm accessing it from a different domain (the front end will be running on various different dynamic front ends). I'm using django-cors-headers configured this way: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_URLS_REGEX = r'^/api.*$' I don't need the cookie to be available for foo.lvh.me:3000, as that is nothing but static files. I need it only for localhost:8000 (in this example) which is the API endpoint. -
how to append new key and value in a list of dictionaries?
I have a list of dictionaries m = [ {'currency_id':1,'price':20},{'currency_id':2,'price':25},{'currency_id':1,'price':44}] 1 means USD and 2 means Bitcoin. So, i have to check currency id in every dictionary and if price is in USD then i have to convert usd to bitcoin and add a new key,value pair 'bitcoin_price':1.0 or if price is in bitcoin then i have to convert it to usd and append a new key,value pair 'usd_price':33. At last i want list like this m = [ {'currency_id':1,'price':20,'bitcoin_price':1.0},{'currency_id':2,'price':25,'usd_price':33},{'currency_id':1,'price':44,'bitcoin_price':1.0}] I have already tried something but seems like i'm lost. m = [{'a':1,'b':2,'c':3},{'d':1,'f':3,'t':6}] for i,k in enumerate(m): for w in k: if k[w]==1: k['as']=5555 else: k['l']=23 -
mejorar respuesta error django rest framework
django rest framework automatically delivered when a field is not valid, it will be possible to add the wrong value in the same way? current response example: {"partners":[{"phones":{"number":["phone number entered is not valid."]}}]} expected response: {"partners":[{"phones":{"number":["phone number entered is not valid."], "value": 11111111}}]} the idea that I have is not to manually intervene the validations and messages that DRF delivers as I find it is safe for my project. I add your comments, thanks! -
Django : How can I get the selected data of another website to show on my webpage
I am building a website related to market place and I want new trending topics to be listed on one of my webpage.I know google trends is one of the site which supply this information in a nice manner so I want my webpage to show info that available on google trends and automatically update the info when ever google updates the trend section. Also I don't want whole of the information but only some selected part of it. I am blank on this topic so I expect a Deep advice. -
Django fails to import _ssl when deployed to IIS
I am trying to host a Django application (Django 2.1.4, Python 3.6) using IIS on an older windows server (Windows Server 2008 R2 with Service Pack 1). I've successfully deployed it on a testing server (same OS) and it is ready to be deployed to production, but I'm running into issues here. I followed the same configuration steps that I used on the staging server, however now when I try to reach the main site I am given the following error ImportError: DLL load failed: The specified module could not be found. when it tries to import _ssl (full stack trace below). This is a requirement to use Okta authentication as well as to enable email through the site. I have installed all dependencies in a virtual environment and configured IIS to use that environment. I've done this with multiple venvs and a conda environment, all with no luck. If I comment out the parts of the code that use Okta, the app works just fine until I get to a point where it sends an email to a user, at which point I face the same issue. Additionally, if I use Django's development server using manage.py runserver both Okta … -
PointField() Not Working correctly in GeoDjango when running the Testcases
Error Details: ERROR:django.contrib.gis:GDAL_ERROR 10: b"Pointer 'hObject' is NULL in 'GDALGetDescription'.\n" ERROR:django.contrib.gis:GDAL_ERROR 4: b"`POINT(0.0 0.0)' does not exist in the file system,\nand is not recognised as a supported dataset name Trying to set the default value of PointField in django models. location_coordinates = PointField(default='POINT(0.0 0.0)') -
DateField in DRF django
I've a model which have a DateField. class A(model.Model): a = model.DateField() class SerializerA(serializers.ModelSerializer): class Meta: model = A fields = (a,) The payload that I pass have a chance that it might send only year, for eg:- { "a": "1991" } It returns an error saying, "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]." I'm already passing one the format, as mentioned in the error, but still I'm getting an error. Why? -
How to create unit test for database connection in django
Overview: This project's purpose right now is to connect to an ldap server and then, when logged in, the database will fill up with data from an API. The data in inserted into a postgresql database using psycopg2 plugin. The data manipulation is done through list comprehension. My tests are housed in the test.py file in my django app. database.py import urllib3 import certifi import psycopg2 from psycopg2 import extras from datetime import datetime def insert_into_table_epic(data): cur.execute("DELETE from epic;") query = """ INSERT into epic (key, name, status) VALUES %s; """ values = list((item['key'], # key item['fields']['customfield_1'], # name item['fields']['status']['name'] # status ) for item in data['issues']) extras.execute_values(cur, query, values) conn.commit() This slice of code is the function to fill out the database with data from the api. and the function is called in my views.py def charts(request): #view that will insert data into postgres db url_epic = '<api-url>' r_epic = http.request('GET', url_epic, headers=headers) data_epic = json.loads(r_epic.data.decode('utf-8')) f.insert_into_table_epic(data_epic) What I am wondering is what should i write i unit test for? (Specifically for the database) Should i test for a database connection? Should a test insert dummy data to see if it is inserting data correctly? Any help on how … -
How do I extend Django Restless to include custom list endpoints
I am trying to extend my Resource endpoint class to include new GET endpoints which return a list of objects but am unable to figure out how to. I was going through the restless doc https://restless.readthedocs.io/en/latest/tutorial.html and have the standard list and detail methods. def list(self): """ GET request handler for /api/articles/ endpoint. :return: List of articles. """ articles = article_service.get_all_articles() return articles Is there a way to specify url and create multiple list endpoints? Can someone point me to a good resource explaining how to extend Django-restless to custom endpoints. -
JavaScript/Firefox: "Failed to register/update ServiceWorker", when nothing called ServiceWorker is in use
Here's a weird one. I'm developing a Django/Bootstrap 3 web application, and recently I've started receiving this error in the JavaScript console: Failed to register/update a ServiceWorker for scope ‘http://localhost:8000/’: Load failed with status 404 for script ‘http://localhost:8000/service-worker.js’ The funny thing is that I'm not actually attempting to use anything called ServiceWorker or service-worker.js and never have. I don't know what it's supposed to do. I do develop many other websites on localhost:8000 though, so I'm guessing it's some kind of left-overs from a different project. The error does NOT show up when I try browsing in private mode, further implying that this is some kind of browser memory. Still, I've reloaded with Ctrl-Shift-R and Shift-F5, and cleared all cookies for localhost. I've searched both my own code, as well as the entire Python environment for the strings service-worker.js and ServiceWorker but found nothing. I'd really appreciate help with two things: Learn what can cause this sort of thing. Get rid of the error itself. I'm using Firefox 64, Django 2.0.10 (with Django Debug Toolbar 1.9.1) with Bootstrap 3.3.7 on Ubuntu 18.04. (Not even sure how to tag this thing, because I don't know what I'm dealing with.) -
Django DateTimePicker calendar appears at the bottom of page
I am trying to implement datetimepicker to my django project and i am nearly there. My day field is able to pick a week instead of just a day, but the calendar is appearing at the bottom of the page. html: <script> $(function () { $('#id_day').datetimepicker({ format:'DD-MM-YYYY' }); $('#id_day').on('dp.change', function (e) { var value = $("#id_day").val(); var firstDate = moment(value, "DD-MM-YYYY").day(0).format("DD-MM-YYYY"); var lastDate = moment(value, "DD-MM-YYYY").day(6).format("DD-MM-YYYY"); $("#id_day").val(firstDate + " - " + lastDate); }); }); </script> <body> <form method="post" style="margin-left: 16px"> {% csrf_token %} <table> {{ form }} </table> </form> </body> Can't seem to figure out why it is at the bottom of the page. -
Create dynamically a model in the save() method from another model
I want to create a model within the save method of another model, so the one generated dynamically is named with a field from the static model. Model Code: class Car(models.Model): name = models.CharField(max_length=128) def save(self, *args, **kwargs): attrs = { 'piece': models.CharField(max_length=128), '__module__': 'myapp.models' } model = type('%s_piece' % self.name, (models.Model,), attrs) admin.site.register(model) super(Car, self).save(*args, **kwargs) The model is generated but I don't know how to make the migrations or migrate it to the database. I tried to migrate it with: from django.core.management import call_command call_command('makemigrations') call_command('migrate') But I get an error as I'm executing this in an atomic transaction.