Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django rest GET query params serializer
I want to receive get query and filter dataset with query params (if present). I'm currently using dumb method listed below. I don't like the fact it's not checking that dates is actually could be parsed. Is there some cool pythonic way to do it without writing a bunch of boilerplate code? class TrackList(APIView): @token_required def get(self, request, pk, **kwargs): # read query params date_from = self.request.query_params.get('date_from') date_to = self.request.query_params.get('date_to') # if present then filter if date_from and date_to: points = Track.objects.filter(user_id=pk, date__range=[date_from, date_to]) # otherwise don't filter else: points = Track.objects.filter(user_id=pk) points.order_by('date') serializer = TrackListSerializer(points, many=True) return Response(serializer.data, status=status.HTTP_200_OK) UPD: The question is not actually about dateutil.parser, it is about general query params parser. Maybe I should use Django rest serializers? -
Django: Having troubles with mocking a variable
After reading some tutorials on mocking, I thought it would be easy, but I guess I don't understand the basics since I keep having an error. services.models file (services is the app) @classmethod def build_current_menu_for_till(cls, till): service = cls.objects.current_for(till) if service: return service.build_menu() return {} I want to mock my service variable to be None, and test that the return value is an empty dict. here is what I did: services.tests file @patch('services.models.Service.build_current_menu_for_till.service') def test_build_current_menu_for_till(self, mocked_service): mocked_service.return_value = None till = TillFactory() # won't be used actually self.assertEqual(Service.build_current_menu_for_till(till), {}) When running the test, error: AttributeError: <bound method Service.build_current_menu_for_till of <class 'services.models.Service'>> does not have the attribute 'service What's wrong? Thanks. -
ChineseWords python format UnicodeEncodeError , but in django OK
demo code like this: #_*_ coding: utf-8 _*_ a = u'北京' b = u'地图' c = '{0} {1}'.format(a, b) when i write this in python file(test.py), and then run 'python test.py'. it will raise Exception like: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) but, when i run a Django, django methon run demo code, it will be ok。 django run demo code python version and python path is totally same. python version: 2.7.9 -
Django doesn't update the ImageField path
I am trying to upload a profile picture when model instance is being created. I want my profile picture to be stored in a folder, that is named according to the instance id, hence once the picture is uploaded I need to create a new dir and move the picture there. I followed this, which suggests overriding the default save() method in the model, and this, that proposes to use post_save signal to save the new file twice. My current code looks as follows: class Emp(models.Model): photo = models.ImageField("Photo", blank=True, null=True, default='default_avatar.png') def save(self, *args, **kwargs): # Call standard save super(Emp, self).save(*args, **kwargs) if self.photo.path: initial_path = self.photo.path new_path = os.path.join(settings.MEDIA_ROOT, 'profile_picture_of_emp_{0}/{1}'.format(self.pk, os.path.basename(initial_path))) # Create dir if necessary and move file if not os.path.exists(os.path.dirname(new_path)): os.makedirs(os.path.dirname(new_path)) os.rename(initial_path, new_path) # Save changes super(Emp, self).save(*args, **kwargs) So this actually moves the file and creates new_path correctly, however, the self.photo.path stills refers to the old location and I can't figure out a way to update this new path. The same happens with post_save signal as it doesn't update the path of moved file. Any suggestions? Thanks!