Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Haystack Custom Search Form
I've got a basic django-haystack SearchForm working OK, but now I'm trying to create a custom search form that includes a couple of extra fields to filter on. I've followed the Haystack documentation on creating custom forms and views, but when I try to view the form I can only get the error: ValueError at /search/calibration/ The view assetregister.views.calibration_search didn't return an HttpResponse object. It returned None instead. Shouldn't basing this on SearchForm take care of returning a HttpResponse object? forms.py from django import forms from haystack.forms import SearchForm class CalibrationSearch(SearchForm): calibration_due_before = forms.DateField(required=False) calibration_due_after = forms.DateField(required=False) def search(self): #First we need to store SearchQuerySet recieved after / from any other processing that's going on sqs = super(CalibrationSearch, self).search() if not self.is_valid(): return self.no_query_found() #check to see if any date filters used, if so apply filter if self.cleaned_data['calibration_due_before']: sqs = sqs.filter(calibration_date_next__lte=self.cleaned_data['calibration_due_before']) if self.cleaned_data['calibration_due_after']: sqs = sqs.filter(calibration_date_next__gte=self.cleaned_data['calibration_due_after']) return sqs views.py from .forms import CalibrationSearch from haystack.generic_views import SearchView from haystack.query import SearchQuerySet def calibration_search(SearchView): template_name = 'search/search.html' form_class = CalibrationSearch queryset = SearchQuerySet().filter(requires_calibration=True) def get_queryset(self): queryset = super(calibration_search, self).get_queryset() return queryset urls.py from django.conf.urls import include, url from . import views urlpatterns = [ .... url(r'^search/calibration/', views.calibration_search, name='calibration_search'), .... ] -
Why is static content request going to uwsgi?
I'm setting up my Django project to work with uwsgi and nginx. For static content, I have the following in my nginx.conf: location /static { alias /Users/me/mystatic; # your Django project's static files - amend as required } I have set STATIC_ROOT to /Users/me/mystatic and called collectstatic to copy all the static files into that directory. In my uwsgi log, I see GET requests for the static content. Since nginx is supposed to serve the static content, why is the GET request sent to uwsgi? -
Django: load template after AJAX request
I am using Django templates and in a particular one I am loading a couple of divs with content performing two AJAX requests to make things faster. The main template I am talking includes a view at the end, which is actually mostly JS. The thing is this JS is dependant to the data loaded in those AJAX requests, so he scripts are being rendered by the template before the necessary data is in the HTML. A quick scheme: {# main template #} {% block content %} <div id="main">...</div> <div id="load-data-1"></div> <div id="load-data-2"></div> {% endblock %} {% block js }% {% include 'template_with_scripts.html' %} {% endblock %} template_with_scripts.html <script> $.get(url1, function(data) { $('#load-data-1').html(data); }); $.get(url2, function(data) { $('#load-data-2').html(data); }); </script> {% include 'scripts_related_with_ajax_loaded_data.html' %} So what I need to do is to load the scripts after the AJAX requests are done, as explained in this answer. But my question is how to go about loading that scripts_related_with_ajax_loaded_data.html file after the AJAX calls have finished. Should I make a new route and view to return the rendered context as HTML? Seems weird and a bit of an overkill. Is there a tag that just renders whatever template you pass, so I … -
How to implement sso using Django-mama-cas and Django-cas-ng
I want to develop something in Django where 2 applications( app1 , app2) will be at 1 server and in another server for 1 another application(app3). app1 is for user authentication. app2 is for main site. app3 is for chat. for app2 and app3 I want authentication from app1. So I was thinking about implementing sso. After searching I came to know about django-mama-cas, django-cas-ng. But I am in confusion about concept and implementation using those CAS mentioned above. Guide me with example(settings.py, urls.py) to implement/solve my problem. -
Connect host mysql from inside a django docker
I am using ubuntu 16.04. For django development I am using docker. My app is running on docker. But now I want to connect mysql server which is in my host PC. I mean my ubuntu 16.04 machine. When I am trying to connect with IP it says "Can't connect to MySQL server on '192.168.76.196'" -
unsupported operand type(s) for *: 'NoneType' and 'int'
I have a code that receives program guide. class ProgramList(UseSlaveMixin, TvmiddlewareApiView): @method_decorator(auth_required) def get(self, request, params): print params.tariffs channel = self.channel maintenances = self.get_maintances() timestamp_from, timestamp_to = self.get_filters() epg = self.get_epg(channel.epg_channel_id, timestamp_from, timestamp_to) utc_date = datetime.datetime.utcnow() utc_timestamp = int((utc_date - datetime.datetime(1970, 1, 1)).total_seconds()) max_archive_duration_days = channel.max_archive_duration(params) archive_start_time = (utc_timestamp - (max_archive_duration_days * 3600 * 24)) has_npvr_service = False items = {'error': 0, 'programs': []} I try to get result and receive: archive_start_time = (utc_timestamp - (max_archive_duration_days * 3600 * 24)) TypeError: unsupported operand type(s) for *: 'NoneType' and 'int' Thanks in advanced. -
eb init not showing Mumbai region
I want to create an EBS django application using EB CLI, I knew the procedure also as I have already done it for other region(Oregon). Now I want to create another new EBS application for Mumbai region, whenever I do eb init to configure region , it's not showing option for Mumbai region.What is the problem?. Even I tried do change configuration for my existing app using eb init -i there also it's not showing Mumbai region. Following are the options for me: piyush@piyush-ThinkPad ~/abc/xyz $ eb init -i Select a default region 1) us-east-1 : US East (N. Virginia) 2) us-west-1 : US West (N. California) 3) us-west-2 : US West (Oregon) 4) eu-west-1 : EU (Ireland) 5) eu-central-1 : EU (Frankfurt) 6) ap-southeast-1 : Asia Pacific (Singapore) 7) ap-southeast-2 : Asia Pacific (Sydney) 8) ap-northeast-1 : Asia Pacific (Tokyo) 9) ap-northeast-2 : Asia Pacific (Seoul) 10) sa-east-1 : South America (Sao Paulo) 11) cn-north-1 : China (Beijing) (default is 3): -
Django get abstract model value in template
I have abstract models and it displays when item created. How can i get this variable and display in my template? class BaseModel(models.Model): class Meta: abstract = True _created = models.DateTimeField(auto_now_add=True) class Toy(BaseModel): name = models.CharField(max_length=250) views.py toys = Toy.objects.all() index.html {% for k in toys %} {{k.created}} {% endfor %} I tried this one but it doesn't work. -
Using javascript to include tables in html
I want to use javascript to create some color picker in a html page. Until now I was using .hide/.show but I think is better to create only the tables that I need, right? Also I have the tables in another html file, so I use the {% include %} TAG but I don't need to. My html template: ... <div id='color_table'> </div> ... My script-jquery.js: function show_color_tables(num, colors) { for (var i=0; i<num; i++) { //var node = document.createTextNode("{% include 'banner/_colortable.html' with table='"+i+"' color='"+colors+"' %}"); //document.getElementById('color_table').appendChild(node); //document.getElementById('color_table').innerHTML = "<iframe></iframe>"; //document.getElementById('color_table').firstChild.contentWindow.document.write("{% include 'banner/_colortable.html' with table='"+i+"' color='"+colors+"' %}"); var node = "{% include 'banner/_colortable.html' with table='"+i+"' color='"+colors+"' %}"; $('#color_table').html(node); }; }; This writes on the screen: {% include 'banner/_colortable.html' with table='0' color='Tutti' %} but don't import the tables from _colortable.html Thanks in advance -
Getting releated models based on recursive categories?
We set up the following category taxonomy: Category 1 Sub-Category 1 Sub-Category 2 Sub-Sub-Category 1 Category 2 Category 3 Each category has some related products (one-to-many). Now we want to display all products of Category 1 and each of its sub-categories (direct products, products of sub-categories and sub-sub-categories). Any advice how to achieve this? Some kind of recursive query? -
Check rest_framework permissions statically
DRF has permission_classes property on view. Method check_permissions instantiates every class in permission_classes list and calls has_permission(self, request, view) method to check whether user has permission to access this view. All this methods are not static methods. They need instantiated view to check permissions. Is there any way to check permissions statically, without instantiating view? Also, I don't want to copy&paste DRF code to do the same thing. Something like this: def check_permissions(view_class, request): -
Can I add new column to Django Reversion table
Currently I have Django reversion installed to my app for audit use. I am thinking to add a new column to the table to track the changes of the object whether it is Create or Update. Is there any way to track this in the current Django reversion table or is it possible to add new column to the table and update it for any changes to the object? -
Making a copy of an object's initial state before saving
For my Django application, I'm looking to keep a full edit history for all objects. As part of this, I've overridden the model's save() method, part of which is shown below: # Replicate the current version (from the db) with all attributes unchanged new_ver = self.__class__.objects.get(pk=self.pk).save(force_insert=True) # Update the current version in the database with the new attributes super(CodexBaseClass, self).save(*args, force_update=True, **kwargs) The 'self' that's passed to the save() method is the NEW version of the object that's been generated by the form. What this code is attempting to do is (1) Make a copy of the object as it currently appears in the database (ie: copy the data as it was before the form modified it), then force an insert of this data so it's copied as a new row (2) Update the existing row with the new version of the object that's been submitted through the form. The problem is with the first line of the two lines of code - It generates a DoesNotExist exception. The object does exist, so I'm currently thinking that the issue is that the database row it's trying to read is currently locked. So my question is: Is there a way I … -
Django Rest Framework how to custom a nested serializer with multiple objects
I have the following serializer that retrieves pages in a set of books: class PagesDataSerializer(Serializer): books = Book.objects.all() data = PagesSerializer(many=True,data=books) I would like to introduce a filter (query parameter type received in the get request) In order to access self.request content I have to add a custom function I tried something like this: class PagesDataSerializer(Serializer): books = Book.objects.all() data = PagesSerializer(source='get_pages_set', many=True) def get_pages_set(self, obj): selected_books = Book.objects.filter(type=self.request.type) return PagesSerializer(many=True,data=selected_books).data But this doesn't work for some reason (I get empty results).... could anyone enlighten me please ? Thank you very much -
How to make nametests algorithm real?
There is project nametest, where user can make minified and interactive test via fb login, I' like to reproduce this algorithm by my own. As back-end part I wish to use Django. For present I have only primitive model for tests ( name, logo-img ), but I don't exactly know how to make woking algorithm for every unique test. I mean , we always grab fb info, when user log in, but every test uses not same info. How to determine algorithm for every test? -
How to use normal Filter together with SearchFilter on Django Rest Framework?
I'm using DRF(Django Rest Framework). I declared a ModelViewSet, and now I want to add filters on that. class GoodsViewSet(viewsets.ModelViewSet): class Filter(FilterSet): class Meta: model = m.Goods filter_class = Filter filter_backends = (SearchFilter, Filter) search_fields = ['name',] queryset = m.Goods.objects.all() serializer_class = s.GoodsSerializer Seeing that I declared a Filter sub class and applied it with: filter_class = Filter It worked at the beginning, before I add the lines: filter_backends = (SearchFilter, Filter) search_fields = ['name',] Which was told by the doc. And now the search filter is applied while the normal filter_class was skipped. One word, they cannot work together. How to work around this? -
Django `reverse` can't find url in tests
I'm using Django (1.9.8) and DRF (3.4.0). My problem is, when I use SimpleRouter with GenericViewSet like this: router.register(r'', MyViewSet, base_name='my') Django showing warning in console: WARNINGS: ?: (urls.W002) Your URL pattern '^/$' [name='my-list'] has a regex beginning with a '/'. Remove this slash as it is unnecessary. ?: (urls.W002) Your URL pattern '^/(?P<pk>[^/.]+)/$' [name='my-detail'] has a regex beginning with a '/'. Remove this slash as it is unnecessary but it's working without problem. (I want to remove warnings). And when I change my url prefix to: router.register(r'^', MyViewSet, base_name='my') this time Django warning is gone. And I can access to this url from browser. But when I call reverse('my-list') from code it's showing error. E django.core.urlresolvers.NoReverseMatch: Reverse for 'my-list' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['v1/my^/$'] (pls notice that 1 pattern(s) tried: ['v1/my^/$']) How can I fix this? TY. -
Could any one suggest a suitable chat app for django please?
I am looking for a suitable chat app for django, could any one please suggest a working app? -
Docker images of django applications running memcached
I currently have a django app running inside a docker container. My django app also uses memcached to increase performance. I'm planning to spin up more docker images on different servers running the same app and use Nginx as a load_balancer. But I'm wandering how can the caches communicate with each other. For example, if a user updates his profile through one server and accesses it through another, he or she would get the outdated version if it was already cached earlier. I don't think using ip_hash for the load balancing policy can solve the issues because users are expected to access from both computers and mobile devices. -
How can I use django.generic.edit.FormView?
After I click the submit button, want to go result.html page. But, never go to the other page from form page. forms are in 'search.html'. I want to see the result at 'result.html' And I don't know how to code 'form_valid(self,form)' inside... class getForm(FormView): """ Search page view class. """ form_class = SearchForm template_name = 'search.html' success_url = '/results/' def form_valid(self, form): ### form data logic ### # -- When query submitted query_compNum = self.form_class.cleaned_data['search_compNum'] QUERY_CompNum_RESULT = None if query_compNum: QUERY_CompNum_RESULT = MolDataView.model1.objects.filter(NewCompounNumber=query_compNum) return super(getForm, self).form_valid(form), HttpResponseRedirect(reverse('chemdb:results', args=(QUERY_CompNum_RESULT))) -
django sum of inline class price
Here is the related App and Classes. Trying to get the sum of amount of all the components belonging to an invoice and save it in 'sub_total' field of Invoice. An invoice sub_total = sum of amount of all components of the invoice instance. What will be way around? Thanks in advance. from stock.models import Part class Invoice(models.Model): invoice_number = models.CharField(max_length=250) sub_total = models.DecimalField(max_digits=8, decimal_places=2) class Component(models.Model): invoice = models.ForeignKey('Invoice',) stock = models.ForeignKey('stock.Part',) qty = models.SmallPositiveIntegerField() unit_price = models.DecimalField(max_digits=8, decimal_places=2) amount = models.DecimalField(max_digits=8, decimal_places=2) -
Upload file into a folder from my server django/python
I want to know how I can add an upload button to my file input. What I want is to let some users to upload certain file to an specific fodler inside my server (so it can be proccessed by other code) this is what I have: <div class="col-xs-4"> <div class="form-group"> <label class="control-label">A file upload button without icon</label> <input type="file" class="filestyle" data-icon="false"> </div> how do a I program a upload button? Thanks for your time. -
Django REST Framework One to Many related field data insert and filtering
I have two model, Person and Appointment. A Person have many Appointment. models.py class Person(models.Model): name = models.CharField(max_length=50) email = models.EmailField() def __str__(self): return self.name class Appointment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='appointments') date = models.DateField(unique=True) class Meta: ordering = 'date', def __str__(self): return str(self.date) and my serializers.py file is: from rest_framework import serializers from appointment.models import Person, Appointment class AppointmentSerializer(serializers.ModelSerializer): class Meta: model = Appointment fields = ('date',) class PersonSerializer(serializers.ModelSerializer): appointments = AppointmentSerializer(many=True) class Meta: model = Person fields = ('name', 'email', 'appointments',) def create(self, validated_data): appointments_data = validated_data.pop('appointments') person = Person.objects.create(**validated_data) for appointment_data in appointments_data: Appointment.objects.create(person=person, **appointment_data) return person and finally my viewsets is: class PersonViewSet(viewsets.ModelViewSet): serializer_class = PersonSerializer queryset = Person.objects.all() filter_backends = [DjangoFilterBackend] filter_fields = ['name', 'appointments'] This return persons_list as my expectation: [ { "name": "Arif Hasan", "email": "arif@gmail.com", "appointments": [ { "date": "2016-10-10" }, { "date": "2016-10-17" }, { "date": "2016-11-07" } ] }, { "name": "Atanu Shome", "email": "atanu@gmail.com", "appointments": [ { "date": "2016-11-13" } ] } ] But i can't create new appointment here. Can't filter person by date range. -
In Django Rest Framework, how can I view paginated data with TemplateHTMLRenderer?
I'm using Django Rest Framework and I'm trying to convert from the API view to a TemplateHTMLResponse using the doc example. I was able to complete most of it and got the template loaded and passing all the data, however documentation on the HTML side of the process is scarce. The problem I am having is the results not being paginated. I am able to access and iterate over all the data, but I need the pagination for organization. views.py. class BoxViewSet(viewsets.ModelViewSet): queryset = Uploadobject.objects.all().exclude(verified=False) serializer_class = BoxSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsBox) #renderer_classes = (renderers.TemplateHTMLRenderer) def list(self, request): queryset = Uploadobject.objects.all().exclude(verified=False) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, data=request.data) if serializer.is_valid(): serdata = self.get_paginated_response(serializer.data) data= {'objects': queryset, 'serializers': serializer} return Response(data, template_name='restframework/objectlist.html') objectlist.html {% if serializers %} {{ serializers }} {% endif %} {% if objects %} {% for object in objects %} <ul> <li>{{ object.Title }}</li> <li>{{ object.Category }}</li> </ul> {% endfor %} {% else %} <p>No objects.</p> {% endif %} I have tried many things including the ListModelMixin and creating a custom pagination script as recommended by the pagination docs, but nothing seems to pass through. I read that there is way to paginate … -
Django Rest Testing RawPostDataException: You cannot access body after reading from request's data stream
I'm trying to run some API tests using the Django Rest Framework, but I'm running into issues with POSTing a multilevel dictionary. Here's the test: class ExampleTest(APITestCase): def my_test(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + <Token>) data = { "name" : "Fred", "siblings" : [ { "ID" : 1234 }, { "ID": 5678 } ] } response = self.client.post("/siblings/add/", data=data, format="json") self.assertEqual(response.status_code, status.HTTP_200_OK) The test doesn't reach the assert statement, it errors at the response = statement. The error is this: RawPostDataException: You cannot access body after reading from request's data stream Why would this be happening? I have many other tests that also POST data, but the only difference I see between them and this one is that this one has a multilevel dictionary for its POST data. What am I messing up here?