Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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']; }); -
Inject media to every Django admin page
I would like to inject a media to every page of the django admin interface. How to do this? -
How to modify attributes of the Wagtail form input fields?
I'm looking at wagtail hello-world form example: class FormField(AbstractFormField): page = ParentalKey('FormPage', related_name='form_fields') class FormPage(AbstractEmailForm): landing_page_template = 'blog/form_page.html' intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FormSubmissionsPanel(), FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] If given the template like this: {% for field in form %} {{ field }} {% endfor %} It will render HTML similar to the following: <input type="text" name="label1" value="Default Label1" required maxlength="255" id="id_label1" /> <input type="url" name="label2" value="http://Label2.net" id="id_label2" /> <textarea name="label3" required rows="10" id="id_label3" cols="40"> How can I modify/add extra attributes to the rendered input fields? For instance: How to add class="form-control"? How to change rows="5" in the textarea input? Is there any other convenient way apart from javascript madness? -
using pusher with django: Unknown Auth_Key
I'm trying to make a chat application using django and pusher. using this script: <script> //initiate puhser with your application key var pusher = new Pusher('b9b5369a1ca201d9eb84_APP_KEY'); //subscribe to the channel you want to listen to var my_channel = pusher.subscribe('a_channel'); //wait for an event to be triggered in that channel my_channel.bind("an_event", function (data) { // declare a variable new_message to hold the new chat messages var new_message = `<li class="left clearfix"><span class="chat-img pull-left"> <img src="http://placehold.it/50/55C1E7/fff&text=`+ data.name + `" alt="User Avatar" class="img-circle"> </span> <div class="chat-body clearfix"> <div class="header"> <strong class="primary-font">`+ data.name + `</strong> <small class="pull-right text-muted"> </div> <p> `+ data.message + ` </p> </div> </li>`; //append the new message to the ul holding the chat messages $('#chat').append(new_message); }); //wait until the DOM is fully ready $(document).ready(function () { //add event listener to the chat button click $("#btn-chat").click(function () { //get the currently typed message var message = $('#btn-input').val(); $.post({ url: '/ajax/chatroom/', data: { 'message': message }, success: function (data) { $('#btn-input').val(''); } }); }) }) </script> and this is the error im getting: Internal Server Error: /ajax/chatroom/ Traceback (most recent call last): File "C:\Users\Hosein\Desktop\Django_Proj_Visual\Django_proj\Django_proj\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Hosein\Desktop\Django_Proj_Visual\Django_proj\Django_proj\env\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "C:\Users\Hosein\Desktop\Django_Proj_Visual\Django_proj\Django_proj\env\lib\site-packages\django\core\handlers\base.py", … -
Best security practices for React + Django
I'm currently working on a project that uses Django API server and a NodeJS server running React. In development we're running Django on port 8000 and NodeJS on port 8080, and currently React is responsible for rendering the page and interacting with Django API, which provides data for React. In order for React to call Django APIs, we've enabled CORS in Django since they're on different ports. My question is the following: Is it safe to allow all CORS in production? If not using the templates system by Django, is the site still protected against CSRF by defaults? If not, how to prevent CSRF in such settings (React+Django)? -
Web Socket Implementation issue using django channels and javascripts
I used web Socket for Client and server communication using java script and django channels. using below code var socket = new WebSocket('ws://192.168.11.154:8002/users/'); console.log("Web Socket Function invoke") socket.onopen = function open() { console.log('WebSockets connection created.'); }; socket.onmessage = function message(event) {console.log("Web Socket Message Received") }; but i got tunnel proxy error some times web socket connection handshake timout. -
<Group: staff> is not JSON serializable use `model_to_dict`
I have a util method, I want to return the user's dictionary data: def getUserInfo(request): user = request.user user_dict = model_to_dict(user) return the user_dict But user if has groups property, which can set permissions to the group. There the model_to_dict can not convert it. is not JSON serializable How to solve this issue? -
How to make html table in django template download all data
I don't know whether you have come across this issue before. Somehow I don't know why my next or previous button for my table is not doing anything. The result still remains the same allthrough and there is no changes. For example when I search so many genes, lets say up to 100 pages, when I click next page the result is the same as the previous all through the 100 pages. Please help me out. <table id="example1" border="1" style="background-color:#FFFFCC" width="0%" cellpadding="3" cellspacing="3"> <thead> <tbody> <tr> <th width="210px"> header1</th> <th width="600px"> header2 </th> </tr> </thead> </tbody> </table> <table class="table table-bordered table-striped "> <thead> <tbody> <td width="200px" "{{result.object.get_absolute_url}}">{{result.object.item1}}</td> <td width="450px">{{result.object.item2}}</td> {% if result.object.item1 %} <td width="250px"><em> D </em></td> {% endif %} </tbody> </thead> </table> -
from models import Category, Product
Problem with "from models import Category, Product"... def ProductList(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', { 'category': category, 'categories': categories, 'products': products }) -
Why are these aggregates not respecting dates in a generic date view?
I am using a MonthArchiveView to retrieve the sums of durations for a specific user grouped by projects for the month. To do this I override get_queryset def get_queryset(self): entries = Entry.objects.filter(user=self.request.user).values( 'project__name' ).annotate( total_duration=Sum('duration'), billable_duration=Sum( Case( When(billable=True, then='duration'), output_field=DurationField(), ) ), unbillable_duration=Sum( Case( When(billable=False, then='duration'), output_field=DurationField(), ) ) ) This works correctly. However I want to get the totals as well so I call the method again to get the queryset and apply aggragationss to it: def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) qs = self.get_dated_queryset() context_data['total_duration'] = qs.aggregate(Sum('total_duration'))['total_duration__sum'] context_data['billable_duration'] = qs.aggregate(Sum('billable_duration'))['billable_duration__sum'] context_data['unbillable_duration'] = qs.aggregate(Sum('unbillable_duration'))['unbillable_duration__sum'] return context_data Unfortunately in this case the month filter is not respected and the aggregates with no date restrictions is returned. -
Django channels with redis setup on heroku leaking memory
I followed the somewhat outdated guide here: https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django And successfully setup django app with channels: > cat requirements.txt .. Django==1.10.6 asgi-redis==1.4.3 asgiref==1.1.2 channels==1.1.8 django-redis-cache==1.7.1 daphne==1.4.2 .. > cat Procfile web: daphne Landia.asgi:channel_layer --port $PORT --bind 0.0.0.0 worker: python manage.py runworker CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, "ROUTING": "Landia.routing.channel_routing", }, } The problem being is that the redis memory consumption starts at 2M, and gradually, very slowly, over 48 hours or so grows to 50MB when the provisioned space is exhausted and my server essentially starts throwing 5XX. It can be fixed by flushing redis. I assuming the channels/redis are not discarding the replies it sends out. Any ideas how to fix, or at least debug this problem? -
Another way to query JSONField in postgresql django
I have made Django project with the database on PostgreSQL. I have one column data which is a JSONField() object. Now for querying in the data JSON blob, the docs show only one way. Say some rows have the key as 'Salary' in data so according to docs if I want to retrieve the row with salary as something then the way is: TableName.objects.filter(data__Salary__gte = 15000) Now the problem is that I want to make it user specific like the user will tell the key and pass it to the function and I want something like this: keyValue = 'Salary' TableName.objects.filter(data__keyValue__gte = 15000) But this does not work for obvious reasons as there is no column of keyValue in data. Is there any other way of doing it?