Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - - OSError: dlopen() failed to load a library: cairo / cairo-2 -- Continues to Appear Even After Downloading GTK+ Bundle 3.10.4
After installing WeasyPrint, I am getting this error: "Error in Django: OSError: dlopen() failed to load a library: cairo / cairo-2" Here are all the details: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0420DE40> Traceback (most recent call last): File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File … -
POST a conditional select using django-chosen
I'm a beginner developer and I'm trying to get my form to POST the results of my chosen option to the submitted URL as a list. I have a form that has a selection option the user will select an access level. <form action = "{% url 'submitted' %}" form method = "POST"> {% csrf_token %} <div class="container"> <div class="row"> <div class="col"> {% if showbutton is not None %} <label for="accesslevel"><h3>Access Level</h3></label> <select name ="accesslevelid" class="form-control my_select" id="accesslevelid"> <option value=""> Please select your access level </option> <option value="7"> Facility </option> <option value="5"> Division </option> <option value = "3"> Corporate </option> <option value = "6"> Market </option> <option value = "4"> Group </option> </select> </div> After the access level is selected a chosen.js multiple select box will display, this is handled by the following javascript. $('.chosen-select').chosen({}).change(function (obj, result) { console.debug('changed: %o', arguments); console.log('selected: ' + result.selected); }); $(document).ready(function () { $('#accesslevelid').change(function () { $this = $(this) $('.content_box').each(function () { $select = $('select', this); if ($select.data('id') == $this.val()) { $(this).show(); $select.show().chosen(); } else { $(this).hide(); $('select', this).hide(); } }); }); }); I use the following Django template which follows the select an access level template and is in the same form. {% … -
Why am I unable to do pip install django?
I get this error when I run pip install django: Collecting django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\shing_~1\appdata\local\temp\2\pip-build-eljct4\django\setup.py", line 32, in <module> version = __import__('django').get_version() File "django\__init__.py", line 1, in <module> from django.utils.version import get_version File "django\utils\version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ----------------------------------------- Command "python setup.py egg_info" failed with error code 1 in c:\users\shing_~1\appdata\local\temp\2\pip-build-eljct4\django\ This is the first time I've gotten any error using pip install. What am I doing wrong? -
reseting the password using django authentication
when I try to use Django's built-in password reset system. it does not take my templates into account. Moreover, when I click the reset password button then it takes me to the Django admin reset page(photo). My the file map my urls.py:- from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"^login/$", auth_views.LoginView.as_view(template_name = "accounts/login.html"),name='login'), url(r"^logout/$", auth_views.LogoutView.as_view(template_name='thanks.html'), name="logout"), url(r"^signup/$", views.SignUpView, name="signup"), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'), url(r'^password_reset/$', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html'), name='password_reset'), url(r'^password_reset/done/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^reset/done/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] The Templates:- password_reset_form.html {% extends 'reg_base.html' %} {% load bootstrap3 %} {% block body_block %} <h3 class="display-1">Forgot password</h3> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-primary" type="submit">Submit</button> </form> {% endblock %} password_reset_confirm.html {% extends 'reg_base.html' %} {% load bootstrap3 %} {% block body_block %} {% if validlink %} <h3 class="display-2 text-center">Change password</h3> <form class="form-control" method="post"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-default" type="submit">Change password</button> </form> {% else %} <p class="lead"> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} {% endblock %} -
Redirect the output of custom Django command to the browser
I have created a custom command which takes a positional and a named optional argument. It does many checks, downloads a file, unzips it and populates the database with the unzipped data. To make the things more convenient for the users I created a simple form and created a view: from django.views.generic.edit import FormView from django.core import management from .forms import DownloadForm class DownloadFormView(FormView): template_name = 'frontend/download.html' form_class = DownloadForm success_url = '.' def form_valid(self, form): country = form.cleaned_data['country'][:3] levels = int(form.cleaned_data['country'][-1:]) management.call_command('download_shapefile', country, levels=levels) return super(DownloadView, self).form_valid(form) That works fine and now I want to provide feedback to the user, as the command might run for a while. Is there any possibility to redirect the command output (or make it available) to the template and display it in the browser? In my command I use: self.stdout.write(self.style.SUCCESS('some success message')) self.stdout.write(self.style.WARNING('some warning message')) to output messages and don't print directly with the print method. -
Django : execute command collectstatic raise UnicodeDecodeError4
In this link enter link description here Is my error, but I not have solution .please help me. -
Querying, reading from a JSONField in PostgreSQL using Django
I am new to Django.. I have a requirement where I need to store a person's name and a they're blood pressure readings. I have made up a Django application and I can store this information information in PostgreSQL. My question is how can read the specific JSONField out to the console? I want to retrieve all JSON data. Here is my models.py file: from django.contrib.postgres.fields import JSONField from django.db import models class ABPM(models.Model): name = models.CharField(max_length=128, null=False, blank=True) bpData = JSONField(null=True) def __str__(self): return self.name JSON data stored in Postgre Database: bpData // field name jsonb // datatype {"sbpReading":["sbp",117],"dbpReading":["dbp",75],"mapReading":["map",98],"hrReading":["hr",73]} I want to print out all values to the console using Django Database API based on the persons name? The following CMDS do not work: ABPM.objects.all() // only returns names ABPM.objects.filter(name='some persons name..', bpData__contains={'sbpReadings', 'sbpReadings', 'mapReadings', 'hrReadings'}) Any help would be great.. -
convert php web application installed in usb to django web app
For my work i need to convert php to django. I know Django well, but php i don't have any experience. can you help me if you know some technologies to convert easier, and for your information our custumor give us the old web php application in the usb ^^ Thank you -
Template rendering is wrong, category shows 2 times
So I am trying to render my models in a template but just one tiny thing shows more times than I expect. I just want category name to show one time for many lectures. I just cant figure where to modify the template code. <ul> {% for a in categories %} {% for c in lectures %} {% if a == c.course_category %} <li><strong>{{ a.course_category }}</strong></li> {% endif %} {% if a == c.course_category %} <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% if c.link %} <li>{{ c.link }}</li> {% endif %} {% if c.file %} <li><a href='{{ MEDIA_URL }}{{ c.file.url }}'>download</a></li> {% endif %} {% endif %} {% endfor %} <hr/> {% endfor %} </ul> -
Is it possible to have django apps in their own docker container and manage/interact with them?
Is it possible to have each app in a django project in its own docker container? this way 1- All the dependencies of the app is contained to itself and there wont be any dependency conflicts between two apps. 2- In our project we are discussing a use case where apps should deployed in containers(primary and backup) such that when the primary goes down the backup takes over .. basically implementing High availability(HA) of an app. I know that this may not exactly be a use case that Django was built to solve, but if it is doable in Django then i would like to do it using django as we have already created lot of apps using django and changing the architecture for the sake of HA would be a lot of work. Note: I understand that the whole project can be deployed in a container and HA can be implemented.. but i'm more interested distributing apps in containers. -
Gunicorn queue wait time
My setup is nginx => gunicorn => django. I am using gunicorn with sync workers. Can I find out how long requests take till they find an available gunicorn worker? I will use this measure to find out if I have too little workers and thus increase the count, does that make sense? I have the RAM available, as currently I am only using 50% of it, but if they aren't queued up I will use the RAM for something else. Can I somehow tell nginx or gunicorn master to annotate the wait time in queue? -
Django : how to display inline admin in the "child" admin of a OneToOne relation?
I have two models related via OneToOne field : class Appendix(Model): name = models.CharField(max_length=300) class Main(Model): name = models.CharField(max_length=300) appendix = models.OneToOneField(Appendix, on_delete=models.CASCADE, related_name='main') I'm trying to make Appendix editable from inside the Main django admin. However since Main is considered the "child" this doesn't seem possible with the current Django inline. This was brought up in a comment to this similar question but there is no answer beyond "change ownership of the key field". I've considered switching the ownership of the foreign key but this would complicate much of the rest of my code (in that all other operation I want to do seem easier with it this way). Is there a way around this? -
Django project creation error
PS C:\Users\shubham\Desktop> django-admin startproject ecom Traceback (most recent call last): File "C:\Python36\Scripts\django-admin-script.py", line 11, in load_entry_point('django==2.0.1', 'console_scripts', 'django-admin')() File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management\commands\startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management\templates.py", line 117, in handle django.setup() File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django__init__.py", line 16, in setup from django.urls import set_script_prefix File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\urls__init__.py", line 1, in from .base import ( File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\urls\exceptions.py", line 1, in from django.http import Http404 File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\http__init__.py", line 5, in from django.http.response import ( File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\http\response.py", line 13, in from django.core.serializers.json import DjangoJSONEncoder File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\serializers__init__.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\serializers\base.py", line 201 def save(self, save_m2m: object = True, using: object = None, kwargs: object) -> object: ^ SyntaxError: non-default argument follows default argument -
django get list of objects from query set
I have a model which has a CharField named as answer , it has only four options which it saves as a,b,c,d .Now in My views i want to write a query that can return the list of these options..I have tried the code below Here b is the list of ld for which we want the list. platform = get_object_or_404(Platform, user=request.user, test_key=article) b = json.loads(platform.list) ans = list(Upload.objects.filter(id__in=b).values_list('answer',flat=True)) Now this gives me the output as [(u'a',), (u'b',), (u'c',), (u'b',), (u'c',), (u'b',), (u'c',)] bu i can't use this list . I want the output as [a,b,c,b,c,b,c] kindly tell me how to get the list of objects -
Celery doesn't see tasks when django DEBUG is set to False
I've got a Django application with Celery. Tasks are described in tasks.py files with @shared_task in different apps, each has its own AppConfig and is being installed (added to INSTALLED_APP) correctly. Everything worked fine until I turned DEBUG off. Celery started to fail due to tasks of unregistered type. With the DEBUG variable Celery can see all of my tasks and work correctly. What can cause such a bug? -
How acess and modify SearchQuerySet(WayStack)?
I having some issues with waystacks. when i nitialize with my model that giving me a list with type SearchQuerySet: def sqs_query(self, sqs): q = self.request.QUERY_PARAMS.get('q', '') results = sqs.filter(content=q) pdb.set_trace() return results def get_queryset(self): sqs = self.sqs_query(self.sqs_models(SearchQuerySet())) return sqs (pdb) type(results) <class 'haystack.query.SearchQuerySet'> I can acess the position 0: (pdb) results[0] <SearchResult: article.article (pk=u'5')> But i can't assign: (pdb) results[0] = results[1] *** TypeError: 'SearchQuerySet' object does not support item assignment I need to modify the positions of the list. -
Bootstrap datetime picker in django modelform for one input
I need to use datetime picker in my django app. After I used it as it is described everywhere the result is incorrect - it doesn't work. Calendar shows on top of the page and doesn't populate the target field at all. forms.py: class addOrderForm(ModelForm): class Meta: model = Orders fields = [ 'shipvia', 'customer', 'employee', 'orderdate', 'freight', 'shipname', 'shipaddress', 'shipcity', 'shipregion', 'shippostalcode', 'shipcountry' ] DATEPICKER = { 'type': 'text', 'class': 'form-control', 'id': 'datetimepicker1' } widgets = { 'orderdate': forms.DateInput(attrs=DATEPICKER) } views.py: def addOrder(request): OrderDetailsFormSet = inlineformset_factory(Orders, OrderDetails, fields=('product', 'unitprice', 'quantity' , 'discount'), can_delete=False, extra=3) order=Orders() if request.method == 'POST': f = addOrderForm(request.POST, instance=order) if f.is_valid(): order = f.save(commit=False) if fs.is_valid(): fs = OrderDetailsFormSet(request.POST,instance=order) order.save() fs.save() return HttpResponse('success') else: f = addOrderForm(instance=order) fs = OrderDetailsFormSet(instance=order) return render(request, 'orders/addOrder.html', context = {'fs': fs,'f':f,'order':order}) orders/addOrder.html: <form action="/orders/addOrder/" method="post"> {% csrf_token %} <table> <div class="container"> <div class="row"> <div class='col-sm-6'> <div class="form-group"> <div class='input-group date' id='datetimepicker1'> {{ f.as_table }} <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> <script type="text/javascript"> $(function () { $('#datetimepicker1').datetimepicker({ inline: true, sideBySide: true, format: 'YYYY-MM-DD', }); }); </script> </div> </div> </table> I have tested few modifications and when django form has been moved under spans then all text input … -
How can you add environment variables in a Jenkins Multibranch Pipeline
I am working on a Django project, I have integrated it withJenkins Multibranch Pipeline. I cannot inject environment variables by the Multibrach Pipeline option even after installing the Environment Injector plugin. I have evironment variables like DB_PASSWORD that must be included in the envvars. Any insight will be highly appreciated. -
Django geting error when loading static files?
I have the code below to load static files, but I keep getting a TemplateSyntaxError. Does anyone know how I can fix this issue? Template: {% load staticfiles %} <a href=""><img class="logo" alt="" src='{% static "images/logo.png"%}' width="110"></a> Settings: INSTALLED_APPS = [ ..., 'django.contrib.staticfiles', ] STATIC_URL = '/public/' STATIC_ROOT = os.path.join(BASE_DIR, "public") URLS: urlpatterns = [ ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Error I get: Invalid block tag on ...: 'static', expected 'endblock'. Did you forget to register or load this tag? -
customicing django admin interface
As you know the backend, admin site shows the models, that includes by default Users and then the others that you may have added in the admin.py file. You can also see that the Users interface has filtering controls, namely a search text field on the top, and filtering variables on a panel on the right. That comes by default for Users. But you can get those controls too for your own models by doing something like this: In your model add: class Admin: list_display = ('post', 'name', 'created_at') list_filter = ('keyword', 'name', 'created_at') ordering = ('created_at', ) search_fields = ('trackword', ) so those, list_display, list_filter, search_fields will be your filtering controls. However, I have done that and I get none of them in the Admin backend. I surely am missing something I should have added, but I have followed the instructions of a book and I do as they say. I am using the latest django, 2.01 thanks -
Google charts, pushing data to column chart dynamically
That is how chart looks like The question is to how add data to that chart dynamically, cause currently, it is static? Here is code of charts.js: google.charts.setOnLoadCallback(drawChart); function drawChart(secondChartData) { var chartData = [["Timeout duration", "Timeout score", "Debrief duration", "Debrief score"]]; var data = google.visualization.arrayToDataTable([ ["Text", "Value", { role: "style" }, { role: "interval" }, { role: "interval" } ], ["Timeout duration", 28.50, "#50c4ec", 22, 35], ["Timeout score", 10, "#016380", 6, 17], ["Debrief duration", 50, "#50c4ec", 42, 58], ["Debrief score", 30, "#016380", 22, 38] ]); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2, 3, 4]); var options = { backgroundColor: { fill:'transparent' }, colors: ['#50c4ec', '#016380', '#5fcec7', '#016380'], title: 'Data', titleTextStyle: { fontSize: 15, bold: true, }, bar: { groupWidth: "90%" }, interval: { 'style':'boxes', 'color': '#000000' }, legend: { position: "none" }, vAxis: { gridlines: { count: 0 } } }; var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values")); chart.draw(view, options); } By the way project is in Django framework -
Django: ForeignKey on_delete SET_DEFAULT behavior
Let me please consider the following two models: class Policy(models.Model): name = models.SlugField(max_length=256, blank = False, unique = True) def default_policy(): return Policy.objects.get(name='default').pk class Item(models.Model): policy = models.ForeignKey('Policy', on_delete=models.SET_DEFAULT, default=default_policy) Everything works as expected except the one operation. I still can do the following without any exceptions: p = Policy.objects.get(name='default') p.delete() And this produces orphaned Items which were referring to "default" Policy object. Unfortunately, this operation leads to integrity issue in database, because there are Items which policy_id column now refers to missed record of Policy table. How could I prevent this from happening? Deleting "default" Policy when no Items refer to it is acceptable to me. -
Django reverse lazy url. Need to add to url some filters
I have reverse_lazy('main:rooms'). Need to add filter after url. Example rooms/?status=free How to add my additional url parametrs to reverse_lazy? -
Django 2.0 static no autocomplete in PyCharm 2017.2.4
Autocomplete is not working for static files for me with Django 2.0. I'm using static files in my project with the current structure project -app_1 -templates --base.html -static --bootstrap ---bootstrap.min.cs ---bootstrap.min.js Here's the HTML code where autocomplete doesn't work. Am I doing something wrong? The files are linked properly and I'm getting the bootstrap design, the problem is that the autocomplete isn't working. -
Json Ajax Response from Django Application
I have a Django app that the views.py sends a json data to a javascript function on my html. The problem is that I can not access the elements of the data. I tryied to use JsonParse but not sucess, for instance when I do var other = JSON.parse(data_doc_pers['data_doc_pers']); document.getElementById("text_conf4").innerHTML = other['doc_nome']; I receive the following response: [object Object] what I am doing wrong??? Here is my code Views.py ... json_string = json.dumps({'type_numeric':type_numeric,'type_prop':type_prop,'name':name,'Vinculo':Vinculo,'doc_nome':doc_nome}) return JsonResponse({'data_doc_pers':json_string}) HTML $.get('{% url "page" %}',{'var':var}, function (data_doc_pers) { var other = JSON.parse(data_doc_pers['data_doc_pers']); document.getElementById("text_conf4").innerHTML = other['doc_nome']; });