Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set Timeout for Django Rest HTTP request
I am using Python 3.5, Django 1.9.5 and Django Rest Framework 3.3.3. I have only few POST apis in my server. How can I set Timeout for each rest http request that if the execution for a request takes more then 3 minutes than it should return timeout in response and should stop execution of that request. Thanks :) -
How get locale date in Django without locale class?
I have existing Django project and I need to get date formatted by locale other than default. I don't want to use locale class because it will have effect on global parameter and it can has unexpected consequences. There is any common way to localize date without locale class or I'm mistaken about how locale is work? -
Django - Edit default values for model in admin
I have three models : one for individuals, one for teams, and one to associate several individuals to one team (and each individual cannot be in more than one team). class Individual(models.Model): name = models.CharField(max_length=50) class Team(models.Model): name = models.CharField(max_length=50) class Team_Individual(models.Model): individual = models.OneToOneField(Individual) team = models.ForeignKey(Team) What I would like to do is populate new teams with, say, 3 "default" individuals, which can them be changed by the admin to existing individuals. So there would be one fake "default" individual, of whom several copies would be there by default when teams are created, whereas real individuals assigned later can only be in one team (or no teams) at a time. I'd like this "default" individual to be editable in the admin, so that the user can choose what to display when showing an empty team (e.g. "Apply for this position", or "Interested ? Call XXXX",etc.). How would I do that with Django's models and admin ? -
Django Session error NoneType
i cannot modify or delete the session i have created. if 'account_success' in request.session: success = request.session['account_success'] del request.session['account_success'] i got this error NoneType' object has no attribute 'dict' -
i want custom json format using django
Django is new for me, i want custom json response. i try to get response from server using android app retrofit. response by server accurate. i need to match json format please help me, thanks i got json format like { "username": "admin", "token": "xxx" } but i want responseCode{ responseCode:xxx, ResponseData: {token:xxx,username:xxx} } code that return json format data class UserLoginSerializer(serializers.ModelSerializer): token = serializers.CharField(allow_blank = True , read_only = True) username = serializers.CharField(required = False , allow_blank=True) #email = serializers.EmailField(label="Email Adress",required = False, allow_blank=True) class Meta: model = User fields = [ 'username', #'email', 'password', 'token', ] extra_kwargs ={"password": {"write_only":True } } def validate(self, data): user_obj = None #email = data.get('email', None) username = data.get("username", None) password = data["password"] if not username: raise ValidationError("A username or email is required to login") user=User.objects.filter( #Q(email=email)| Q(username=username) ).distinct() #user = user.exclude(email=None) if user.exists() and user.count() == 1 : user_obj = user.first() else: raise ValidationError("username not valid.") if user_obj: if not user_obj.check_password(password): raise ValidationError("Incorrect credentials please try again") #token = Token.objects.get_or_create(user=user_obj) token, created = Token.objects.get_or_create(user=user_obj) data["token"] = token.key data["username"] = user_obj return data i tried something like this # responseCode = {} # responseData = {} # responseData['token'] = token.key # responseData['username'] = … -
How to convert php code to python
I don't know php. How to use below code in python. Can you help me with this. $arr = array('id'=>'8291377','token'=>'JIB8bFhuS2z3ivZKkRn9meDX4qg0yYdtO','RechargeTo'=>'7777777','Amount'=>'0','ProviderId'=>'1'); $data_string= $data_string= json_encode($arr); $ch = curl_init('https://xyz.in/api/recharge'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_string))); $result = curl_exec($ch); print_r($result); -
Django tuple index out of range
After request creating I want to show a successful message and redirect it to the main page after countdown finishing. But I receive tuple index out of range, and sometimes it kills all process. requestSentSuccess.html <p class="text-center" id="counter">5</p> <script> setInterval(function() { var div = document.querySelector("#counter"); var count = div.textContent * 1 - 1; div.textContent = count; if (count <= 0) { location.href="{% url 'home' %}"; } }, 1000); </script> Traceback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 859, in emit msg = self.format(record) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 732, in format return fmt.format(record) File "/Users/natigvahabov/Desktop/Django/lib/python2.7/site-packages/django/utils/log.py", line 173, in format if args[1][0] == '2': IndexError: tuple index out of range Logged from file basehttp.py, line 85 -
Insert bulk data django using raw query
I am trying to enter about 1 millions records to PostgreSql since i create table dynamically i don't have any models associated with it so i cant perform bulk_insert of django How is there any method of inserting data in a efficient manner. I am trying using single insert statement but this is very time consuming and too slow -
Iterator() over query objects django
I need to iterate over some query objects from my database and display them on the template, I have model field like price, cost and profit, the idea is to not to parse directly because the list will be to large in real env, so I have started with something like this from __future__ import print_function from django.views.generic import ListView from projects.models import Project from .services import CurrencyConversionService class ProjectStatisticsList(ListView): model = Project template_name = 'statistics/statistics_list.html' def get_context_data(self, **kwargs): context = super(ProjectStatisticsList, self).get_context_data(**kwargs) for context['price_aux'] in Project.objects.all().iterator(): # do the iteration here and later for loop in tempalte pass return context models fields price_aux = models.DecimalField('price aux', max_digits=20, decimal_places=2, default=0, blank=True, null=True) cost_aux = models.DecimalField('cost aux', max_digits=20, decimal_places=2, default=0, blank=True, null=True) profit_aux = models.DecimalField('profit aux', max_digits=20, decimal_places=2, default=0, blank=True, null=True) My problem is that I don't have an idea how can I do this, can someone please help me understand how can I do this, thanks. -
Map physical path of a file to serve path for download
In my AngularJS/Python app, I uploaded a file using dropzone which has a physical path of something like this: D:\uploadedFiles\tmpmj02zkex___5526310795850751687_n.jpg' Now I want to create a link for this file for display and download on the front end. A link that looks something like this: http://127.0.0.1:8000/uploadedFiles/tmpmj02zkex___5526310795850751687_n.jpg What is the best way to achieve this? -
django related_name queries and self not the same object?
I have something like: class Thing(models.Model): pass class SubThing(models.Model): thing = models.ForeignKey(Thing, related_name='subthings') a = models.DecimalField() # some more Decimal fields def __str__(): return str(self.pk) + ' - ' + str(self.a) def save(): setattr(self, 'a', 0) print(self) # outputs 187 - 0 print(self.thing.subthings.all()) # outputs ... 187 - 20 ... # do some calculations on self and siblings Super(SubThing, self).save() I am confused by the output of the code above. I need to recalculate siblings of SubThing when it is saved, under certain conditions. The query self.thing.subthings.all() includes self, and since I couldn't exclude it reliably (.exclude(self) doesn't seem to work, and for a new instance pk is None), I chose to setattr(self, 'a', 0) which would give me the behaviour I need. However, self and the object in self.thing.subthings.all() don't hold the same values, while both have pk=187 according to the output. Are they both the same object and not? Is there some caching happening with related_name that breaks my logic? What am I doing wrong here? -
error in doing changes in open stack horizon
You have offline compression enabled but key "0a65c041a6b9d69baa764b57993373e8" is missing from offline manifest. You may need to run "python manage.py compress". Request Method: GET Request URL: http://10.16.134.91/dashboard/admin/ Django Version: 1.8.17 Exception Type: OfflineGenerationError Exception Value: You have offline compression enabled but key "0a65c041a6b9d69baa764b57993373e8" is missing from offline manifest. You may need to run "python manage.py compress". Exception Location: /usr/local/lib/python2.7/dist-packages/compressor/templatetags/compress.py in render_offline, line 71 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/opt/stack/horizon', '/opt/stack/keystone', '/opt/stack/swift', '/opt/stack/glance', '/opt/stack/neutron', '/opt/stack/nova', '/opt/stack/ironic', '/opt/stack/horizon', '/opt/stack/tempest', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/opt/stack/horizon/openstack_dashboard'] Server time: Thu, 9 Feb 2017 11:34:30 +0000 Error during template rendering I made COMPREE_OFFLINE = False or I tried command python manage.py compress. Still I am getting errors. -
How to check the case of any variable in jinja2/django template?
I need to check the variable's case like if it is in upper case or lower case. Can we do that in Django template ? -
How to get only published articles in aldryn newsblog template
"article_list" has both published and non-published articles i want here only published. *Note: i am working in django cms there is no models or views init. {% for article in article_list %} {% include "aldryn_newsblog/includes/general-article.html" %} {% empty %} <p>{% trans "No items available" %}</p> {% endfor %} -
Django bulk update
How can I enter values in bulk to django to a specific field of a model. Here is my model class CurrencyPriceList(BaseModel): store_item = models.ForeignKey("inventory.StoreItem") currency = models.ForeignKey("projects.Currency") price = models.DecimalField(decimal_places=2, max_digits=15,validators=[MinValueValidator(Decimal('0.00'))]) cost = models.DecimalField(decimal_places=2, max_digits=15,validators=[MinValueValidator(Decimal('0.00'))]) is_deleted = models.BooleanField(default=False) class Meta: db_table = 'currency_price_list' verbose_name = _('currency price list') verbose_name_plural = _('currency price lists') ordering = ('store_item',) class Admin: list_display = ('store_item',) def __unicode__(self): return self.store_item.name Here StoreItem is another model for saving store items class StoreItem(BaseModel): code = models.CharField(max_length=128,unique=True) name = models.CharField(max_length=128) unit = models.ForeignKey("inventory.Unit",null=True,blank=True) category = models.ForeignKey("inventory.Category") sub_category = models.ForeignKey("inventory.SubCategory",null=True,blank=True) color = models.CharField(max_length=128,blank=True,null=True) size = models.CharField(max_length=128,blank=True,null=True) is_deleted = models.BooleanField(default=False) stock_update_date = models.DateField(null=True,blank=True) stock_qty_limit = models.PositiveIntegerField(default=0) is_stock_notif_send = models.BooleanField(default=False) def i(self): stocks = 0 store_item_stock = [] stock_qtys = 0 stocks = StoreItemStock.objects.filter(is_deleted=False,store_item=self) if stocks: stock_qtys = stocks.aggregate(qty=Sum('qty')).get('qty', 0) for stock in stocks: stock_qty = stock.qty booked_qtys = 0 balance = stock_qty booked_items = BookedItem.objects.filter(is_deleted=False,status="pending") booked_item_lists = BookedItemList.objects.filter(is_deleted=False,booked_item=booked_items,store_item=self,warehouse=stock.warehouse) if booked_item_lists: booked_qtys = booked_item_lists.aggregate(qty=Sum('qty')).get('qty', 0) balance = stock_qty - booked_qtys dict = { "warehouse" : stock.warehouse, "stock" : stock.qty, "booked_items" : booked_qtys, "balance" : balance } store_item_stock.append(dict) results = { "total_stock" :stock_qtys, "stocks" : stocks, "store_item_stock" : store_item_stock, } return results class Meta: db_table = 'store_item' verbose_name = _('store item') … -
Using Django and Tornado IOLoops
I'm trying to figure out the best way to integrate my Django app running on a uWSGI server with a Tornado IOLoop, I'm trying to use the queue feature from Tornado, but I don't want to go as far as to switch servers. I understand Django is supposed to be stateless therefore my doubt is where to store the instance of Tornado.IOLoop that is consuming a certain queue. -
Django regex pattern matching
I have the following urlpatterns: url(r'^api/daily-means/$', views.daily_means.as_view(), name='daily_means'), url(r'^api/daily-means/sites/(?P<url>\w+)/$', views.site_daily_means.as_view()), url(r'^api/daily-means/pollutant/(?P<poll>\w+)$/', views.pollutant_daily_means.as_view()), The first two work fine. The last one show work the same as the second one but it does not. Im not that great with regex and urlpatterns but I assume there is something with the second url pattern which is stopping the last one from running. Can anyone else see a reason for this? -
i am having issues with django templates, urls and jquery
when i am using django urls in href tags of navbar the jquery code in the last, doesn't work but when i remove the url and place '#' jquery works fine. I think this has something to do with django urls (probably). Anyways, i just want to solve this issue please tell me why this is happening and how to solve this issue. Below is the base template and url.py and by the way, each url points to a seperate html file. eg. /home/ points to home.html /aboutus/ points to about.html base.html <html> <head> {% load staticfiles %} <meta charset="UTF-8"> <title>{% block title %}{% endblock %} | Vasu Genset Pvt. Ltd.</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://bootswatch.com/paper/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'index/css/index.css' %}"> <link rel="stylesheet" href="{% static 'index/css/products-style.css' %}"> {% block style %}{% endblock %} </head> <body> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="#" >Vasu Genset Pvt. Ltd.</a> <button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#mydropdown"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div id="fh5co-navbar" class="collapse navbar-collapse" id="mydropdown"> <ul class="nav navbar-nav navbar-right" id="navbar-change"> <li><a class="active" href="#">Home</a></li> <li><a href="#">About Us</a></li> <li class="dropdown"> <a href="/productsandservices/" class="dropdown-toggle" data-toggle="dropdown">Products & Services <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a … -
Facebook chatbot keep sending data when server/webhook is down
I am beginner in Django/nodejs and I have a simple chatbot for each. Sometimes, when server is down, facebook just call webhook again and again until server is up (meaning server return http 200). Problem is that since it is being called multiple times, when server is up, it send a lot of message back to user. How shall I stop that? I don't want to annoy user. -
Post object to django view via (ajax) and pass to Django modal object
I am trying to submit new assignments to my api via ajax. I looked around and couldn't find a solution to my problem. Here is where I am submitting to the api with ajax: $('#submitAssignment').click(function () { if(checkModal()){ var assignment = { title: $('#newAssignmentTitle').val(), type: $('#assignmentSelection').val(), date: $('#newAssignmentDate').val(), details: $('#newAssignmentDetails').val() } $.post('/data/api/create-assignment/', {assignment: assignment}, function (data) { }, 'json'); } }); if you print out the assignment you would get: {title: "This is the title", type: "Homework", date: "02/16/2017", details: "This is not fun"} This is my django view that takes in the data: def createAssignment(request): if request.method == 'POST': print(request.POST.get('assignment[title]')) #this prints the title # How can I do the following?: assignment = Assignments() # modal assignment = request.POST.get('assignment') assignment.save() data = {} data['status'] = "Success" return HttpResponse(json.dumps(data), content_type="application/json") else: data = {} data['status'] = "Data must be sent via POST" return HttpResponse(json.dumps(data), content_type="application/json") I can print out parts of the assignment object within the request object but I can't seem to pass it to a new assignment modal. I get the following error which makes me thing that assignment = Assignment() is getting overwritten: AttributeError: 'NoneType' object has no attribute 'save' -
Django QuerySet select related objects
I have searched around but have not found a situation like mine. Assuming the use of Django's User Profile method to extend the default user features, how would a multi-object queryset get mapped a queryset of the related object. For example (in the models): class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) friends = models.ManyToManyField("self", symmetrical=True, blank=True) And inside the view: class Friends(generics.ListAPIView): queryset=User.objects.all() serializer_class = UserSerializer def get_queryset(self): user = self.request.user profile = user.userprofile profiles = profile.friends.all() return profiles #We want this to be a queryset of users I have tried the following but this only works if profiles is of size one. return User.objects.filter(userprofile=profiles) -
Indexing new object with Django & Elasticsearch
I am using elastic search, and I have had to create a function to group my data. It should: Index every time a new model is created. It does index the "title" value, but the "tag" value is not there. I created a manual function "manual_index" and when I run that, the "tag" value does get added to the index. However manual indexing is impractical. How can I get the "tag" value to save every time a new object is created? Search.py class TaskIndex(DocType): title = String() class Meta: index = 'task-index' def manual_index(): TaskIndex.init() es = Elasticsearch() bulk(client=es, actions=(b.indexing() for b in models.Task.objects.all().iterator())) Models.py from itertools import groupby class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) taglevel = models.IntegerField("Tag level", null=True, blank=True) class Item(models.Model): title = models.CharField("Title", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) def get_grouped_tags(self): tag = self.tag.order_by('taglevel') grouped_tags = { tag_level: [ { 'name': tag_of_level.name, 'taglevel': tag_of_level.taglevel, } for tag_of_level in tags_of_level ] for tag_level, tags_of_level in groupby(tag, lambda tag: tag.taglevel) } return grouped_tags def indexing(self): obj = TaskIndex( meta={'id': self.id}, title=self.title, tag=self.get_grouped_tags() obj.save() return obj.to_dict(include_meta=True) -
Django: nest the object I'm serializing into the serializer?
I asked a question on here about nesting a serializer into another serializer: Django: adding two serializers together? which helped greatly. But now I'm looking to nest the object I'm serializing to be nested as well. Example: Here's my current UserSerializer: class UserSerializer(serializers.ModelSerializer): posts = serializers.SerializerMethodField() class Meta: model = User fields = ('__all__') def get_posts(self, user): posts = Posts.objects.get_posts_for_user(user=user) return PostsSerializer(posts, many=True, context=self.context) Here's my PostsSerializer: class PostsSerializer(serializers.ModelSerializer): class Meta: model = Posts fields = ('__all__') Here's what's how it's being serialized: { "name": "Bobby Busche", "email: "Bobby@gmail.com", "posts": [ {"from_user": "me", "message": "Hello World"}, {"from_user": "me", "message": "Bye bye"} ] "username: "ilovemymomma" } But I want the user to be grouped inside the key "user" like this: { "users": { "name": "Bobby Busche", "email": "Bobby@gmail.com", "username": "ilovemymomma" } "posts": [ {"from_user": "me", "message": "Hello World"}, {"from_user": "me", "message": "Bye bye"} ] } I need a bit of guidance on what's the best approach to execute for this. -
How to create a dynamic checkbox from sqlite's data?
I want to create a checkbox form like this: I don't know how to write the html,template and forms. The data are loaded from sqlite. It should have a strategy name. Should I use {% for item in object_list %}? But I don't know how to use it. Thank you. -
Annotating sum while still having access to foreign objects
Let's say that I have a simple shopping cart system with these models: from django.db import models from django.utils import timezone class Product(models.Model): name = models.CharField(max_length=255) # More fields... @property def featured_image(self): try: return self.productimage_set.all()[0] except IndexError: return None def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.FileField(upload_to='products/') # More fields... def __str__(self): return self.product.name class Order(models.Model): created = models.DateTimeField(default=timezone.now) # More fields... def __str__(self): return str(self.pk) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() # More fields... def __str__(self): return 'Order %s: %s of %s' % ( self.order_id, self.quantity, self.product.name, ) When a user places an order, an OrderItem object is created for each product they ordered, which lets me know (1) which product they purchased and (2) how many of that product they purchased. Now, suppose I wanted to show the user which products they have ordered the most of. I'll use this data as an example: Order 1: Product A: 10 Order 2: Product A: 10 Product B: 5 Order 3: Product A: 10 Product B: 5 Product C: 5 This particular user should be shown the products in this order: Product A: 30 total Product B: 10 …