Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having trouble serving image from django rest API using angular
I am currently having an issue rendering an image from my newly created products API using Django REST Framework. I have everything else loading but the images will not load. I am using angular to consume the API data with the following code: myStore.controller("myStoreController",function($scope,$http){ $scope.gems = $http.get("/api/products/").then( function(response){ $scope.gems = response.data }, function(error){ $scope.error = error }); }) Here is the product rest URL code: from django.conf.urls import url,include from rest_framework import routers from products_rest.viewsets import ProductsViewsets router = routers.DefaultRouter() router.register('products',ProductsViewsets,'products') from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^', include(router.urls)) #base router ] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) Lastly, here is the main settings URL for the django app: from django.conf.urls import url,include from django.contrib import admin from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('customerreview_rest.urls', namespace='api')), url(r'^api/',include ('products_rest.urls', namespace='api')), url(r'^', include('GemStore_App.urls',namespace='frontend')), ] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) When I navigate to the URL of the image, I can access the image, but for whatever reason I can't get the image to display to the page. And the API looks like this currently: [ { "name": "Dodecahedron", "price": 30, "description": "Some gems have hidden qualities beyond their lustre, beyond their shine. This … -
How to create a field in MySQL that get data from the callable function in Django?
How can I set a django field that gets data from a function depending on other fields? Let me explain using the following example. class Test(models.Model): def testType(self): return str(self.__class__.__name__) sources = models.CharField(default= testType, max_length=50, null=True, blank=True) In this case, if I go to django front-end interface and hit "add Test", I can see a box for 'sources' to fill out. This is not the way I wanted. I want: 1. a field named 'sources' in the back-end MySQL database, 2. No box for 'sources' to fill out in the "add Test" form, and 3. The 'sources' field will get data as soon as we add a new record. Any suggestion that can help me to solve this issue would be appreciated. -
Django Form transport
I created a file forms.py. I added to it CartTest class that retrieves data from the database to form. I added to the view cart_detail form then added to the template this form. What should I do so that I can show the benefit of your choice Forms.py class CartTest(forms.Form): transport = forms.ModelChoiceField(queryset=Transport.objects.all()) views.py def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={'quantity': item['quantity'], 'update': True}) item['update_size_form'] = CartAddProductForm( initial={'size': item['size'], 'size_update': True} ) form = CartTest(request.POST) if form.is_valid(): cd = form.cleaned_data return render(request, 'cart/detail.html', {'cart': cart, 'form': form}) Html file <div class="container-fluid"> {% for item in cart %} {% with product=item.product %} <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 table-xs"> <table class="table"> <thead> <tr> <th>Zdjęcie</th> <th>Nazwa</th> <th>Rozmiar</th> <th>Ilość</th> <th>Cena</th> </tr> </thead> <tbody> <tr> <th> <a href="{{ product.get_absolute_url }}"> <img src="{{ product.image_url }}" style="max-width: 100px;"> </a> </th> <td>{{product.name}}</td> <td> {% if item.size|length > 2 %} {{ item.size|slice:":2" }} {% else %} {{ item.size|slice:":1"}} {% endif %} </td> <td>{{ item.quantity }}</td> <td>{{item.total_price}} <a href="{% url 'cart:cart_remove' product.id%}" class="visible-xs">Usuń</a> </td> <td class="hidden-xs"><a href="{% url 'cart:cart_remove' product.id%}">Usuń</a></td> </tr> </tbody> </table> </div> {% endwith %} {% endfor %} <div class="col-lg-offset-9 col-lg-3"> <h3>Razem: {{cart.get_total_price}} PLN</h3> <a href="{% url 'orders:order_create' %}"> <h4>Do kasy</h4> </a> … -
Mongoengine, django and firebase user authentication?
I would like use part of firebase and join with mongoengine and django. It's posible this ?. Help me. -
Customizing Django Sitemap Index
I have created a sitemap index in Django that links to three other sitemaps. The default sitemap index template looks like this: <?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {% for location in sitemaps %}<sitemap><loc>{{ location }}</loc></sitemap>{% endfor %} </sitemapindex> Is there a way to also add a <lastmod></lastmod> field? Right now it only shows the URL location when it loops through sitemaps in the for loop. I'm not sure how to also pass the date last modified to display in the template. -
In Django, is it possible for superusers to have different required fields than non-superusers?
I know that superusers and regular users are both just django's User objects, but how can I write a custom user class that requires some fields for plain users and doesn't require those fields for superusers? -
configure react js and python in the same project
I have a project on react js and python (Django). I would like to know what is the best way to configure them. I don't know much about react so any suggestion is welcome -
Django error: Reverse for 'details' with arguments '()' and keyword arguments
Here is part of my django app and I want to create link with get_absolute_url but I get an error: Reverse for 'details' with arguments '()' and keyword arguments '{'slug': 'product'}' not found. 0 pattern(s) tried: [] My model: class PortfolioItem(models.Model): name_item = models.CharField(max_length=120) slug = models.SlugField(unique=True) date_from = models.DateField('date from') date_to = models.DateField('date to') description = models.TextField() author = models.ForeignKey(User) def __str__(self): return self.name_item def get_absolute_url(self): return reverse('lol', kwargs={"slug": self.slug}) Here is my view: class PortfolioDetail(DetailView): model = PortfolioItem template_name = "portfoliodetail.html" Here is my url: urlpatterns = [ url(r'^$', PortfolioList.as_view(), name='home'), url(r'^portfolio/(?P<slug>\w+)/$', PortfolioDetail.as_view(), name='details'), ] Here is an template: <ul> {% for i in portfolioitem_list %} <li><a href="{{ i.get_absolute_url }}">{{ i.name_item }}</a></li> {% endfor %} </ul> -
Nginx cache static files from different aplications
I use WordPress as a home page (mysite.com) and Django for the rest (mysite.com/pages). I have single nginx config file for both of them and its working fine. Moreover, they reside in a single server block. Here are some parts of my configuration: server { ... root /var/www/wordpress; ... location /static/ { alias /home/username/Env/virtenv/mysite/static/; } } With this both WordPress and Django static files are served. Now I want to cache all static files for 7 days in the browser. If I put this in addition: location ~* \.(jpg|jpeg|png|svg|gif|ico|css|js)$ { expires 7d; } then the WordPress static files are properly cached, but Django's static files are not even served. I know this is because the /static/ location is never reached and then Nginx searched Django's files in the root directive which is on server block level and which points to the WordPress location. I can remove the cache location and add expires 7d; in the /static/ location. This will in opposite cache only the static files of Django. But how can I make both static resources to be cached for a week? -
Two Foreign keys issue django
Hi I have this python code for django, and basically i am trying to build it so that every tourobject can have many tourbets but also i want to be able to save a certain winning tourbet as current bet but then django complains that it can't find TourBet class TourObject(models.Model): tourplace = models.ForeignKey(TourPlace, related_name='tourplace', verbose_name="tourplace", default=1) title = models.CharField(max_length=155, blank=True) description = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=False, verbose_name="Status") end_date = models.DateTimeField(blank=True, default=datetime.now) current_bet = models.IntegerField(blank=True, default=0) next_bet = models.IntegerField(blank=True, default=0) no_auction_price = models.IntegerField(blank=True, default=1) objects = models.Manager() def __unicode__(self): return self.title def get_absolute_url(self): return reverse("tourobjects:tourobject", kwargs={"pk": self.pk}) class RelatedTourObject(models.Manager): def get_queryset(self): return super(RelatedTourObject, self).get_queryset().select_related('tourobject').all() class TourBet(models.Model): user = models.ForeignKey(User, related_name='tourbet', verbose_name='User') tourobject = models.ForeignKey(TourObject, related_name='tourobjectbet', verbose_name="tourobjectbet", default=1) date_created = models.DateTimeField(blank=True, default=datetime.now) bet_amount = models.IntegerField(blank=True, default=1) objects = models.Manager() related_tourobject = RelatedTourObject() def __unicode__(self): return str(self.bet_amount) -
Passing Request to Django form Still shows self not defined
I am currently using Python and Django to make a Web Application. As my title states I am trying to pass the request down to one of my form classes so I can use user data. I know there are a lot of questions on this, but I have tried each one of them and it does not allow me to access the user parameter. My Code: Form Class: class CreateEventForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): self.request = request super(CreateEventForm, self).__init__(*args, **kwargs) name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) image = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) description = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'})) location = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) ticket_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) event_owner = forms.ModelChoiceField(queryset=EventOwner.objects.all().filter()) ticket_price = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Event fields = ['name', 'image', 'description', 'category', 'event_owner', 'ticket_name', 'ticket_price', 'location'] My View: class CreateEventView(View): form_class = CreateEventForm template_name = 'create-event.html' def get(self, request): form = self.form_class(request, request.POST) if request.user.is_authenticated: # Now check to make sure the user has created an "Event Organiser" name eo = EventOwner.objects.filter(owner_id=request.user.id) # If there has been an event owner made if eo.count() > 0: return render(request, self.template_name, {'form': form}) # Else send the user to the create event owner else: messages.warning(request, 'You must have an organiser profile setup before creating an … -
call to custom create_user via form fails
I have a form that I am going to be using for user registration and want to use the same create_user function that is defined in my custom user manager, however, when the user data is submitted, the values are going into the database in a way that is not corresponding with what was entered and instead each time, the user email_address is entered as "abstractuser.MyUser.object" instead of what was given to the form. How can I modify this code to pass the correct value to the create_user function and create the user successfully? Thanks. Models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class MyManager(BaseUserManager): def create_superuser(self, email_address, password): superuser = MyUser() superuser.email_address = email_address superuser.set_password(password) superuser.is_staff = True superuser.is_superuser = True superuser.save() def create_user(email_address, password): user = MyUser() user.email_address = email_address user.set_password(password) user.is_staff = True user.is_superuser = False user.save() class MyUser(AbstractBaseUser, PermissionsMixin): email_address = models.EmailField(unique=True, max_length=100) is_staff = models.BooleanField(default=0) object = MyManager() USERNAME_FIELD = 'email_address' def get_short_name(self): return self.email_address Forms.py from django.forms import ModelForm from django import forms from models import MyUser class AuthForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = MyUser fields = ['email_address', 'password'] Views.py … -
please help me in understanding a django based project
link to project is:- https://github.com/amangoeliitb/Photo-Gallery-Web-Application I am trying to understand this django based project. I was not getting why he has created two folders i.e eversnap and assigment. please help. -
Django - User creates User and Profile in same form
Hi have changed my view from this: How to make User able to create own account with OneToOne link to Profile - Django For some reason the profile_form is not saving the 'user' information to the database. I have checked the information in the print(profile_form.user) data and does show the username in the terminal. It is not however saving this foreign key to the database, it just leaves it Null. To this: Views.py class IndexView(View): template_name = 'homepage.html' form = UserCreationForm profile_form = ProfileForm def post(self, request): user_form = self.form(request.POST) profile_form = self.profile_form(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() profile_form.save(commit=False) profile_form.user = user print(profile_form.user) print(profile_form) profile_form.save() return render(request, self.template_name) else: return render(request, self.template_name, {'user_form': self.form, 'profile_form': self.profile_form}) def get(self, request): if self.request.user.is_authenticated(): return render(request, self.template_name) else: return render(request, self.template_name, {'user_form': self.form, 'profile_form': self.profile_form}) Forms.py class ProfileForm(ModelForm): """ A form used to create the profile details of a user. """ class Meta: model = Profile fields = ['organisation', 'occupation', 'location', 'bio'] Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) organisation = models.CharField(max_length=100, blank=True) occupation = models.CharField(max_length=100, blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) -
Field not found on serializer
I'm building a REST API using DRF, and am currently stuck with modeling the endpoint /api/v1/venues/1/packages/. A GET request on this is giving me this error: AttributeError at /api/v1/venues/1/packages/ Got AttributeError when attempting to get a value for field `item_type` on serializer `MenuItemSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `ManyRelatedManager` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'item_type'. Here are the participating models: class MenuItemType(models.Model): class Meta: db_table = 'menu_item_types' name = models.TextField() class MenuItem(models.Model): class Meta: db_table = 'menu_items' name = models.TextField() item_type = models.ForeignKey('MenuItemType', on_delete=models.CASCADE) class PackageItems(models.Model): class Meta: db_table = 'package_items' package = models.ForeignKey('Package', on_delete=models.CASCADE) menu_item = models.ForeignKey('MenuItem', on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=10, decimal_places=2) comments = models.TextField(null=True) class Package(models.Model): class Meta: db_table = 'packages' name = models.TextField() price = models.DecimalField(max_digits=16, decimal_places=2) comments = models.TextField(null=True) venue = models.ForeignKey('Venue', on_delete=models.CASCADE) menu_items = models.ManyToManyField('MenuItem', through='PackageItems') and the serializers: class MenuItemTypeSerializer(serializers.ModelSerializer): class Meta: model = MenuItemType fields = ['id', 'name'] class MenuItemSerializer(serializers.ModelSerializer): item_type = MenuItemTypeSerializer() class Meta: model = MenuItem fields = ['id', 'name', 'item_type'] class PackageItemSerializer(serializers.ModelSerializer): menu_items = MenuItemSerializer() class Meta: model = PackageItems fields = ['id', 'menu_items', 'quantity', 'comments'] class PackageSerializer(serializers.ModelSerializer): menu_items = MenuItemSerializer() class Meta: model … -
Getting field value from django database
I have an staticmethod where I save user (if exists) and calculation. @staticmethod def save_calculation(user, selection, calculation_data): customer = None if calculation_data['firstname'] or calculation_data['lastname']: customer = Customer() customer.title = calculation_data['title'] customer.firstname = calculation_data['firstname'] customer.lastname = calculation_data['lastname'] customer.save() n_calculation = Calculations() n_calculation.user = user n_calculation.category = selection['category_name'] n_calculation.make = selection['make_name'] n_calculation.model = selection['model_name'] n_calculation.purchase_price = selection['purchase_price'] n_calculation.customer = customer n_calculation.save() return {'statusCode': 200, 'calculation': n_calculation, 'customer': customer} And the view, where I want to get the results is as follows : def adviced_price(request): if request.method == 'POST': connector = Adapter(Connector) selection = Selection(request).to_dict() calculation = connector.calculations(request.user, selection, request.POST) if 'statusCode' in calculation and calculation['statusCode'] == 200: customer = '' if 'customer' in calculation: customer = calculation['customer'] price = calculation['calculation']['purchase_price'] # How to get the price context = {"calculation_data": calculation['calculation'], 'customer': customer, 'price': price} return render(request, 'master/result-calculation.html', context) else: return else: return HttpResponse('Not POST') The calculation which I get in the view is as follows : {'statusCode': 200, 'calculation': <Calculations: Calculation for user>, 'customer': None} How can I now get the purchase_price from calculation? I tried with price = calculation['calculation']['purchase_price'] But I get an error : TypeError: 'Calculations' object is not subscriptable Any advice? -
How do I add custom CSS to crispy forms?
I'm trying to create a responsive form for my website with the help of crispy forms.I'm not using bootstrap and I want to add custom CSS to the crispy form to match my whole website. HTML: <form method='POST' action=''>{% csrf_token %} {{ form|crispy }} <input type='submit' value='Sign Up' /> </form> using inspect element it shows: <form method='POST' action=''><input type='hidden' name='csrfmiddlewaretoken' value='GLJMxnnDz1MGNFC46pjoofSlo6JMCD1IXu7X3n7LsRbQfdS38SYHJMs9IAXddcck' /> <div id="div_id_full_name" class="form-group"> <label for="id_full_name" class="control-label "> Full name </label> <div class="controls "> <input class="textinput textInput form-control" id="id_full_name" maxlength="120" name="full_name" type="text" /> </div> </div> <div id="div_id_email" class="form-group"> <label for="id_email" class="control-label requiredField"> Email<span class="asteriskField">*</span> </label> <div class="controls "> <input class="emailinput form-control" id="id_email" maxlength="254" name="email" type="email" required /> </div> </div> <!-- <input class='btn btn-primary' type='submit' value='Sign Up' />--> <input type='submit' value='Sign Up' /> </form> forms.py: from django import forms from .models import SignUp class ContactForm(forms.Form): full_name = forms.CharField(required=False) email = forms.EmailField() message = forms.CharField() class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['full_name', 'email'] models.py: from __future__ import unicode_literals # Create your models here. from django.db import models # Create your models here. class SignUp(models.Model): email = models.EmailField() full_name = models.CharField(max_length=120, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): #Python 3.3 is __str__ return self.email -
Django: How to make an API call just before browser tab close?
I am using Django v1.10 for an application where in need to send an API call just before browser close through crude javascript (don't want to use any library for sake) preferably. I've read about window.unload and window.onbeforeunload. The first one didn't seem to work at all. The second can work but it also gets executed when there is reload or redirection to another page (it works as it should but that is what I don't want). I've tried using SESSION_EXPIRE_AT_BROWSER_CLOSE of Django which works only when a user has totally exit out of the browser (no browser process running). I've also seen answers on the web where people have suggested to open another window/tab of the browser through JS as the tab closes. So in precise words, I want to make an API call just before browser tab close (not in any other situation). Please help! -
Django REST permission does not return 403
I am now creating a testcase on Django REST3.5 Here is my tests.py Problem: It returns 201 instead of 403. I do not want the object be created import os import pytest from rest_framework.test import APIClient from apps.price_list_excel_files.models import PriceListExcelFile def upload_excel(user: str, passwd: str) -> tuple: client = APIClient() client.login(username=user, password=passwd) dir_path = os.path.dirname(os.path.realpath(__file__)) with open(dir_path + '/mixed_case.xlsx', 'rb') as fp: response = client.post( '/api/price-list-excel-files/', {'file': fp}, format='multipart' ) return client, response def test_service_manager_upload_excel(prepare_service_mgrs): client, response = upload_excel("smgr1", "smgr1password") assert 403 == response.status_code assert 0 == PriceListExcelFile.objects.count() models.py: from django.db import models from django.db.models.signals import post_save from apps.commons.models import AbstractModelController from apps.price_list_excel_files.permissions import PriceListExcelFilePermisionMixin from apps.price_list_excel_files.validators import validate_file_extension, validate_head_columns from apps.price_lists.utils import get_xlsx2db class PriceListExcelFile(AbstractModelController, PriceListExcelFilePermisionMixin): """ A table that store the file record in the system Feature from Access Level. View is user be able to download an Excel file Price list Service MGR View Service Staff View """ file = models.FileField(upload_to='./excels', validators=[validate_file_extension, validate_head_columns]) class Meta: ordering = ['-id'] post_save.connect(get_xlsx2db, sender=PriceListExcelFile) permissions.py: from apps.accounting_users.models import AccountingUser from apps.marketing_users.models import MarketingUser from apps.mgmt_users.models import ManagementUser class PriceListExcelFilePermisionMixin: @staticmethod def has_read_permission(request): return True def has_object_read_permission(self, request): return True @staticmethod def has_write_permission(request): import pdb; pdb.set_trace() if request.user.is_anonymous(): return False else: return … -
Python 3.5 - Django 1.8 - after login {{ next }}
I am currently learning Django by reading a popular book for this framework called "Django by example". Currently, I am at the 4th chapter and even though I can managed to follow the instructions, I did not fully understand something. In my login.html template, I am instructed to add the following code: {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <h1>Log-in</h1> {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% else %} <p>Please, use the following form to log-in:</p> {% endif %} <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Log-in"></p> </form> </div> {% endblock %} I am having problems in understanding the {{next}} variable and how it is linked to the other files. The book says : "Notice that we have added a hidden HTML element to submit the value of a variable called next. This variable is first set by the log in view when you pass a next parameter in the request." After that I am instructed to define a new view : @login_required def dashboard(request): return render(request, 'account/dashboard.html', … -
How to use Django to run python scripts?
Sorry for the super basic question. I have a simple python script with a function that takes string inputs, makes a list, and prints out the length of the list. I wanted to see if I could use Django to use this python script function as part of a website, where a webpage takes the input from a form, passes it to the python function, and then returns the output to the web page. Sounds simple enough. My question is this: Is Django meant for this? It seems most Django tutorials are about user admin stuff, templates, and database creation. I can't find an easy to understand solution to what I want to do even after having gone through the Django documentation poll tutorial and several other tutorials. Is this something that should be written in JavaScript if I want to actually carry out what my python script function does? -
Nginx redirects to default page
I am setting up a domain for my Django/Gunicorn/Nginx server. It works fine with IP address instead of domain name in server_name but when I add domain name it redirects to default Ubuntu Nginx page. My Nginx file looks like this: Path : /etc/nginx/sites-available/projectname server { listen 80; server_name example.com; return 301 $scheme://www.example.com$request_uri; } server { listen 80; server_name www.example.com; client_max_body_size 4G; location = /favicon.ico {access_log off; log_not_found off;} location /static/ { root /path/to/static/dir; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://unix:/path/to/gunicorn.sock; } } I have run the command sudo nginx -t and sudo service nginx restart but no effect. Please let me know if I am doing anything wrong. -
Django client does not delete in test
Hi I am now using Django REST3.5.3. I can do CRUD perfectly fine with browsable API. My problem is my test does not pass. tests.py import os from django.test import Client from apps.price_list_excel_files.models import PriceListExcelFile def upload_excel(user: str, passwd: str) -> tuple: client = Client() client.login(username=user, password=passwd) dir_path = os.path.dirname(os.path.realpath(__file__)) with open(dir_path + '/mixed_case.xlsx', 'rb') as fp: response = client.post( '/api/price-list-excel-files/', {'file': fp}, format='multipart' ) return client, response def test_mgmt_user_upload_excel(prepare_mgmt_users): client, response = upload_excel("John", "johnpassword") assert 201 == response.status_code assert 1 == PriceListExcelFile.objects.count() # TODO: Fix this testcase def test_mgmt_user_remove_excel(prepare_mgmt_users): client, response = upload_excel("John", "johnpassword") excel_id = response.data.get('id') url = '/api/price-list-excel-files/' + str(excel_id) + '/' res2 = client.delete(url, data={'format': 'json'}) import pdb; pdb.set_trace() assert 0 == PriceListExcelFile.objects.count() Here is my pdb console: apps/price_list_excel_files/tests.py . >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB set_trace (IO-capturing turned off) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > /Users/el/Code/siam-sbrand/portal/apps/price_list_excel_files/tests.py(37)test_mgmt_user_remove_excel() -> assert 0 == PriceListExcelFile.objects.count() (Pdb) list 32 url = '/api/price-list-excel-files/' + str(excel_id) + '/' 33 res2 = client.delete(url, data={'format': 'json'}) 34 import pdb; 35 pdb.set_trace() 36 37 -> assert 0 == PriceListExcelFile.objects.count() [EOF] (Pdb) res2 *** KeyError: 'content-type' (Pdb) url '/api/price-list-excel-files/2/' (Pdb) res3 = client.delete(url) (Pdb) res3 <Response status_code=404, "application/json"> Am I miss something? -
Starting multiple processes in Celery
I have a problem with configuring Celery for Django. This is how I start django-celery: python manage.py celery worker --autoscale=10,2 Example of a task: @task def test(i): print "ITERATION {} START".format(i) time.sleep(10) print "ITERATION {} END".format(i) return True And I call this task with: for i in range(10): test.delay(i) What I expect to happen is that if I send 10 tasks to queue, 10 processes should open - one for each task. What actually happens is that the random number of processes are started, usually 4 and after these 4 tasks are finished, another 3 start and after they finish, another 3 start. This happens even for tasks that take longer to complete, e.g. 2 minutes. Can someone explain this behavior? How can I start all tasks immediately if autoscale upper limit allows it? Also, though lower limit in autoscale is 2, when server is started, 3 processes run. Why is that? Platform: OpenWRT, Dual-Core processor, 2GB RAM. -
django queryset element can't be changed?
def cumulate(self, dataset): nb = 0 for i in range(dataset.count()): nb += dataset[i]['nb'] dataset[i]['nb'] = 99 print(dataset[i]['nb']) return dataset why this prints original values instead of printing 99 ?