Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
send HTTP request using AngularJS to another domain
I've been developing an API using django-rest-framework. However, when i run virtual web server on localhost and try and send a request to api i get this error XMLHttpRequest cannot load http://127.0.0.1:8000/users?format=json. No ' Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. After a quick search i realized, that the problem is that i send request to a different domain ( different port in my situation ) and i can fix it by installing some new app. However, i don't want to do it in django, but rather by edditing the way i make a request. That's how i do it now: Geonix.controller('mainController', function($scope, $http) { var config = { headers: {'Content-Type': 'application/json; charset=utf-8'}}; $http.get('http://127.0.0.1:8000/users?format=json', config).success(function(data) { $scope.users = data; }); }); Is there a way to get a right response without changing anything in back-end ? Note, that on actual server api and web page will be running on different ports as well, thus the problem will stay. -
Absolute path error when building wheel
OVERVIEW I'm trying to learn how to build wheels on my windows dev box so hopefully I'll have a nice way to deploy django websites on linux boxes. But right now I'm stuck with a little error. Here's my setup.py: from setuptools import setup, find_packages setup(name='pkg', version="1.0", packages=find_packages(), data_files=[('/etc/nginx/sites-available', ['foo.conf'])] ) When i try to do >python setup.py bdist_wheel I'm getting this error: raise ValueError, "path '%s' cannot be absolute" % pathname It seems the way I'm using data_files is not supported. QUESTION What's the right way to deploy config files using wheels & setup.py? -
How to include all categories in one blog view
I have 8 categories on my blog. I created view that will show only posts from choosen category. It works but i must create new view to every category. How can i include all categories in one view? My models: class Category(models.Model): name = models.CharField(max_length=100) icon = models.ImageField(upload_to='icons', blank=True) class Post(models.Model): author = models.CharField(max_length=25, blank=True, null=True) title = models.CharField(max_length=200) text = models.TextField() categories = models.ManyToManyField(Category, verbose_name='Categories') published_date = models.DateTimeField( default=timezone.now) It is my view: def sport(request): posts = Post.objects.filter(categories__name__exact="sport").order_by('-published_date') return render(request, 'blog/post_list.html', {'posts': posts}) You see, this view is only to category 'sport', to category 'politics' i have another view etc. In my template simple for loop: {% for post in posts %} {{ post.title }} {% endfor %} line in url url(r'^sport$', views.sport, name='sport'), -
Django error: NoReverseMatch
I'm using Django 1.10 and python 3.4 The precise error is NoReverseMatch at /movies/movie/Twilight/ Reverse for 'movie-details' with arguments '(8,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['movies/movie/(?P<movie_id>\\d+)|(?P<movie_name>[a-zA-Z\\ ]+)/$'] The error is caused by this line: {% url 'moviesrating:movie-details' movie.id %} in template moviesrating/select_movie.html In file moviesrating/urls.py, which is correctly included in the main urls file, there are those lines: app_name = 'moviesrating' urlpatterns = [ url(r'^movie/(?P<movie_id>\d+)|(?P<movie_name>[a-zA-Z\ ]+)/$', view_movie, name = 'movie-details'), ] which refers to function view_movie in moviesrating/views.py: def view_movie(request, movie_id, movie_name): if movie_id: movie = get_object_or_404(Movie, pk = movie_id) elif movie_name: try: movie = get_object_or_404(Movie, name = movie_name) except MultipleObjectsReturned: # There are two movies named 'Twilight' movies = get_list_or_404(Movie, name = movie_name) return render(request, "moviesrating/select_movie.html", {'movies': movies}) else: movie = None return render(request, "moviesrating/movie.html", {'movie': movie}) The purpose of the url /movies/movie/... is to show a movie found by name or by id, the url pattern comes from this need. The point is that the error shows that even if it doesn't find the reverse match it finds the right pattern so I thought the pattern didn't match. Then I tried to change the line to: {% url 'moviesrating:movie-details' movie.id %} {% url 'moviesrating:movie-details' … -
Rate Limiting for Search Engine Python
I built a search engine where users can search and then receive results. Right now, users are freely using the site, with or without a free/paid account, but I would like to introduce two things: Rate-Limiting Freemium model User without a free account or not logged in can only search x times/day for free, a logged-in free user can only search y times/day for free, and paid users who are logged in can search how many times per month or year they're paying for. How do I implement this in a way that fool proof (i.e. no NYTimes style private-browsing workarounds or log-in/log-out double-dipping)? I'm using python/MySQL on Django with ubuntu if that helps. -
How can I override the submit-line.html Django template to add extra button?
I would like to add an extra button into the submit line row in my Django admin but need help understanding how to extend this template as it doesn't seem to be as easy to do as the other templates. In submit_line.html I see the following {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" />{% endif %} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" />{% endif %} {% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" />{% endif %} Say I want to add an "Export" button in this row, my thinking would be that I would put, {% if show_export %}<input type="button" value="{% trans 'Export' %}" name="_export" />{% endif %} Is this correct, and if not, what is the right way to do this? How do I then register the tag so that it actually creates a button and becomes visible on the admin? -
Django - How do I dynamically populate a formwizard form's fields from a database
def get_form_initial(self, step): if 'project_id' in self.kwargs: if step == 'project': project_id = self.kwargs['project_id'] project = Project.objects.get(pro_id=project_id) from django.forms.models import model_to_dict project_dict = model_to_dict(project) return project_dict elif step == 'task': project_id = self.kwargs['project_id'] tasks = Task.objects.filter(project=project_id) print "tasks: %s " % tasks pp.pprint(self.__dict__) tasks_dict = model_to_dict(tasks) return tasks_dict else: print self.kwargs else: return self.initial_dict.get(step, {}) The first form is not a FormSet and is easily populated on the first step, project, but the second step is a FormSet. How do I retrieve the Task forms in the FormSet and populate the FormSet in the wizard step with the forms and their respective fields? tasks: [<Task: Task object>, <Task: Task object>] { 'args': (), 'condition_dict': { }, 'form_list': OrderedDict([(u'project', <class 'proposed_project_details.forms.Project_Form'>), (u'task', <class 'django.forms.formsets.Task_FormFormSet'>), (u'resources', <class 'django.forms.formsets.Resources_Required_FormFormSet'>), (u'deliverable', <class 'django.forms.formsets.DeliverableFormFormSet'>), (u'staffing', <class 'django.forms.formsets.Staffing_FormFormSet'>)]), 'head': <bound method OrderWizard.get of <OrderWizard: forms: OrderedDict([(u'project', <class 'proposed_project_details.forms.Project_Form'>), (u'task', <class 'django.forms.formsets.Task_FormFormSet'>), (u'resources', <class 'django.forms.formsets.Resources_Required_FormFormSet'>), (u'deliverable', <class 'django.forms.formsets.DeliverableFormFormSet'>), (u'staffing', <class 'django.forms.formsets.Staffing_FormFormSet'>)])>>, 'initial_dict': { }, 'instance_dict': { }, 'kwargs': { 'project_id': u'6'}, 'prefix': 'order_wizard', 'request': <WSGIRequest: POST '/projects/edit/6'>, 'steps': <StepsHelper for <OrderWizard: forms: OrderedDict([(u'project', <class 'proposed_project_details.forms.Project_Form'>), (u'task', <class 'django.forms.formsets.Task_FormFormSet'>), (u'resources', <class 'django.forms.formsets.Resources_Required_FormFormSet'>), (u'deliverable', <class 'django.forms.formsets.DeliverableFormFormSet'>), (u'staffing', <class 'django.forms.formsets.Staffing_FormFormSet'>)])> (steps: [u'project', u'task', u'resources', u'deliverable', u'staffing'])>, 'storage': <formtools.wizard.storage.session.SessionStorage object at … -
Passing extra kwargs to subclass of ModelFormSet
I want to have a general BaseModelFormSet that populates the formset with and empty QuerySet class Empty_Model_FormSet(forms.BaseModelFormSet): def __init__(self, *args, **kwargs): model = kwargs.pop('model') print model super(Empty_Model_FormSet, self).__init__(*args, **kwargs) # this ensures that the formset is loaded with no data from our model self.queryset = model.objects.none() TaskFormSet = modelformset_factory( Task, fields=['t_name', 'start_date', 'end_date'], formset=Empty_Model_FormSet(model=Task)) ResourceFormSet = modelformset_factory( Resources_Required, fields=['res_details', 'res_justification', 'res_task'], formset=BaseFormSet) StaffingFormSet = modelformset_factory( Task_Joins_User, form=Staffing_Form, formset=Empty_Model_FormSet(model=Task_Joins_User)) DeliverableFormSet = modelformset_factory( Deliverable, fields=['deli_description'], formset=Empty_Model_FormSet(model=Deliverable)) but passing formset=Empty_Model_FormSet(model=Deliverable) for example, gives me an error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases How do I pass the model to the Empty_Model_FormSet so that I don't have to create three Empty_[Model]_FormSet classes to pass to each of my modelset_factory's? -
Connect to aws database with django and sqlite
My company has a mysql server with AWS, and we are using Django. This question is so that I can run our code on my localhost, not for production. I'll be using sqlite in my laptop, but will need to get the data from the aws mysql server. I have the db_host, db_username, db_passwd, db_database info which is for a MySQLdb.connect(). We couldn't figure out how to get mysql on my computer - too many path errors and too difficult to go into here -, and so we decided to use sqlite in the code. Problem is, I have no idea how to get the info from aws, into my load_items.py file. Here is the code structured for aws: _DB_HOST = "xx" _DB_USERNAME = "xx" _DB_PASSWD = "xx" _DB_DATABASE = "xx" db = MySQLdb.connect(host=_DB_HOST, user=_DB_USERNAME, passwd=_DB_PASSWD, db=_DB_DATABASE,use_unicode=True, charset="utf8") cursor = db.cursor() Naturally im getting a mysql library not loaded error, since mysql server isnt running/not present. How am I able to take the data from the AWS MySQL server so that I can run it in my non-production code? -
Nginx pass blocked referrers
I all time receiving bot spam, so I block bots using this. I'm very surprized but I still receive emails from Django, that requests pass Nginx. Amount of email decreased from thousands per hour to tens per hour but from same referrers. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'www.elong.com'. You may need to add 'www.elong.com' to ALLOWED_HOSTS. My blacklist looks: map $http_referer $bad_referer { hostnames; default 0; # Put regexes for undesired referers here "*.cn" 1; "~bitauto.com" 1; "~hunantv.com" 1; ... "~com.cn" 1; "~sogou.com" 1; "~sina.com.cn" 1; "~weibo.com" 1; ... "~114la.com" 1; "~quer.com" 1; "~elong.com" 1; "~yninfo.com" 1; "~news.cn" 1; "~126.com" 1; "~pcpop.com" 1; } If I make curl everything works: curl --referer http://www.qunar.com my-host.com curl: (52) Empty reply from server curl --referer sina.com.cn my-host.com curl: (52) Empty reply from server -
Django and mysql fetching yesterday's login count
I am using Django and rest-auth. I already have a working code to fetch today's and yesterday's login counts in my Django application as follows: def get_analytics(request): total_users = User.objects.all().count() total_users_games = User.objects.filter(username__startswith='yg_').count() # Number of users who dogged in once to our system today today_login_count= User.objects.filter(last_login__startswith=timezone.now().date()).count() today_login_count_memoryGames= User.objects.filter(last_login__startswith=timezone.now().date(), username__startswith='yg_').count() yesterday_login_count = User.objects.filter(last_login__startswith=timezone.now().date() - timezone.timedelta(days=1)).count() yesterday_login_count_memoryGames = User.objects.filter(last_login__startswith=timezone.now().date() - timezone.timedelta(days=1), username__startswith='yg_').count() There are usernames starting with 'yg' and few starting with 'yg_' responsible for two different frontends. Today's login count is correct, I crosschecked from database. However I am not sure about yesterday's login count, it looks like the number which I get is not correct (i.e. today's login count will be tomorrow: yesterday's login count, so these numbers should be same). I suspect the code for yesterday's login count gives me those users who did login yesterday and not today, where as what I want is all the users who logged in yesterday. I ran following query with yesterday's date and got 4 results and that's actually what yesterday_login_count_memoryGames = User.objects.filter(last_login__startswith=timezone.now().date() - timezone.timedelta(days=1), username__startswith='yg_').count() gives me. select username, last_login from auth_user where username like '%yg\_%' and last_login like '%2016-09-06%'; I am cross checking in my database with following sql … -
Django ManyToMany Field with field name values
model.py class MedtechProductCategory(models.Model): name = models.CharField(max_length=128, null=False, blank=False) type = models.CharField(choices=type_choices_for_tag, max_length=512) class Meta: db_table = 'medtech_product_category' class ProductsInfo(models.Model): deal_active = models.BooleanField(default=True) category = models.ManyToManyField(MedtechProductCategory, related_name='product_info_category') class Meta: db_table = 'products_info' def getTags(self): return self.category.values_list() admin.py class ProductsInfoAdmin(admin.ModelAdmin): filter_horizontal = ('category',) admin.site.register(ProductsInfo, ProductsInfoAdmin) So i want to show the name of the category field in the filter search and want to save them as objects while doing save. How to customise it to show the name of the manytomany field and on save save the objects of the manytomany field -
django rest framework manually display 404 page
So I have typical generic view: class FooListAPIView(generics.ListAPIView): serializer_class = FooSerializer lookup_fields = ('area_id', 'category_id', ) def get_queryset(self): area = Area.objects.get(pk=self.kwargs.get('area_id')) area_tree = area.get_tree(parent=area) #returns queryset category = Category.objects.get(pk=self.kwargs.get('category_id')) queryset = Foo.objects.filter(area__in=area_tree, category=category) return queryset def get_object(self): queryset = self.get_queryset() queryset = self.filter_queryset(queryset) filter = {} for field in self.lookup_fields: filter[field] = self.kwargs[field] return get_object_or_404(queryset, **filter) My problem is, if i try get area or category objects, which doesn't exist, browser throws me error: Area matching query does not exist. How can I make it so, that when Area matching query does not exist, I get standard rest framework 404 response? -
django-tinymce widget not outputting correct error message
I just set up django-tinymce and made some changes to my form to do it. However, now my form is no longer outputting the correct error message. My form: TITLE_LENGTH_ERROR = "This title is too long, please make it 200 characters or less." TITLE_EMPTY_ERROR = "You’ll have to add a title." TEXT_EMPTY_ERROR = "Please enter some text." NO_CATEGORY_ERROR = "Please select a category." NO_CITY_ERROR = "Please select a city." class ArticleForm(ModelForm): text = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) class Meta: model = Article fields = ['title', 'text', 'categories', 'city'] widgets = {'title': forms.TextInput(attrs={ 'placeholder': 'Enter a descriptive title'}), 'categories': forms.CheckboxSelectMultiple(choices=Category.CATEGORY_CHOICES), 'city': forms.RadioSelect(choices=City.CITY_CHOICES), } error_messages = { 'title': { 'max_length': TITLE_LENGTH_ERROR, 'required': TITLE_EMPTY_ERROR, }, 'text': { 'required': TEXT_EMPTY_ERROR, }, 'categories': { 'required': NO_CATEGORY_ERROR, }, 'city': { 'required': NO_CITY_ERROR, } } The test: from articles.models import Article, Category, City from articles.forms import ( ArticleForm, TITLE_LENGTH_ERROR, TITLE_EMPTY_ERROR, TEXT_EMPTY_ERROR, NO_CATEGORY_ERROR, NO_CITY_ERROR, ) class ArticleFormTest(TestCase): def setUp(self): self.user = User.objects.create(username='testuser') self.user.set_password('12345') self.user.save() self.client.login(username='testuser', password='12345') def test_form_validation_for_blank_inputs(self): form = ArticleForm(data={'title': '', 'text': '', 'categories': '', 'city': '', 'author': self.user}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors['text'], [TEXT_EMPTY_ERROR] ) The traceback: (venv) Robins-MacBook-Pro:togethere robin$ python manage.py test articles/ Creating test database for alias 'default'... .F.................... ====================================================================== FAIL: test_form_validation_for_blank_inputs (articles.tests.test_forms.ArticleFormTest) ---------------------------------------------------------------------- Traceback (most … -
Django. Complex annotations require an alias. What is alias here?
I'm trying to get the maximun & minimum value of a model with this query: max_min_price = MyModel.objects.annotate(Min('price', Max('price'))) But I get the error: Complex annotations require an alias I'm not sure what an alias means here and the docs are not clear in my opinion. Any advice will help. -
Django admin admin_order_field with other table
How to sort by custom field in Django admin. My database's tables are without any ForeignKey, django framework design by related ship. This model define: class UserBaseInfo(BaseModel): STATUS = [(0, 'not pass'), (1, 'pass')] SEX = [(0, 'unset'), (1, 'male'), (2, 'female')] parent_id = models.IntegerField(max_length=11, default=0) level_id = models.IntegerField(max_length=11, default=1) phone = models.BigIntegerField(max_length=15, null=True, blank=True, default=None) nickname = models.CharField(max_length=100) sex = models.IntegerField(null=False, blank=False, default=1, choices=SEX) country = models.CharField(max_length=100, null=True, blank=True) province = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) headimgurl = models.CharField(max_length=255, null=True, blank=True) status = models.IntegerField(max_length=3, default=0) updated_time = models.BigIntegerField(max_length=18, null=True, blank=True) class Meta: db_table = 'user_base_info' ordering = ('-created_time', '-updated_time') def save(self, force_insert=False, force_update=False, using=None, update_fields=None): initial = False if not self.id: initial = True super(UserBaseInfo, self).save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields) if initial: Wallet(user_id=self.id, money=1000).save() class Wallet(models.Model): user_id = models.BigIntegerField(max_length=18, primary_key=True, null=False, blank=False, verbose_name=_('UserId')) money = models.FloatField(null=False, blank=False) class Meta: db_table = 'wallet' This admin class UserBaseInfoAdmin(CSVAdmin): list_display = ('nickname', 'avatar', 'level_id', 'parent', 'income', 'sex', 'country', 'province', 'city') list_filter = ('nickname', 'level_id', 'sex', ('created_time', DateFieldListFilter), ('updated_time', DateFieldListFilter)) search_fields = ('nickname', 'level_id', 'sex', 'created_time', 'updated_time') list_display_links = ('level_id',) readonly_fields = ('nickname', 'level_id', 'sex', 'country', 'province', 'city', 'headimgurl', 'language', 'openid', 'privilege', 'created_time', 'updated_time') list_per_page = 20 list_max_show_all = 20 def … -
using python reserved keyword as variable name
im trying to send sms using a webservice , this is what webservice document suggest : response = client.service.SendSMS( fromNum = '09999999' , toNum = '0666666666666', messageContent = 'test', messageType = 'normal', user = 'myusername', pass = '123456' , ) to be fair they dont have document for python only php/asp so i've converted this from their php sample but as unlike me some may know pass is a reserved keyword of python so i cant have variable name pass becuz i get syntax error ! is there a way around trhis or i should switch to another webservice ? i wish we could put variable names in quotation mark or something -
Select2 filter values disappear when search returns no results
I am using a serverside implementation of DataTables with yadcf and select2 for added functionality. The data used to populate the table is acquired via an Ajax request to a Django view, as is the data for the select2 autocomplete functionality; but from a separate Django view. My issue is as follows. If a search query would return no results, the values in the select2 search fields will disappear and cannot be reset in DataTables - you must instead refresh the page. The values in non-select2 fields remain visible and can be reset. The filter types within problematic columns are multi_select with a select type of select2. Filter types within non-problematic columns are range_date and range_date using bootstrap-datetimepicker as datepicker type. Below are my select2 column parameters. { "column_number": 3, "filter_type": "multi_select", "select_type": "select2", "select_type_options": { dropdownCssClass : 'bigdrop', multiple: true, minimumInputLength: 1, ajax: { url: '{% url 'ffTestApp:searchData' 'product' %}', delay: 250, dataType: 'json', data: function (params) { return { q: params.term, v: yadcf.exGetColumnFilterVal(table,4), s: yadcf.exGetColumnFilterVal(table,5) }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.items }; }, }, escapeMarkup: function (markup) { return markup; }, templateResult: function(data) { return data.id; }, templateSelection: … -
django: build admin-like checkbox returning queryset of selected items
sorry if title doesn't make lots of sense. What I would like to have is this: Right now I have a model overview view looks pretty much like this but I am wondering how should I implement the circled part. Ideally it would be just like in admin, your selection results in a queryset containing those item you selected. I know probably some javascript magic could do this job but since it is already in admin, I am wondering if there is a more django-ish way to achieve it? Thanks -
Accessing model instances associated with a forms.ModelMultipleChoiceField from the templates
I'd like to create a form that would allow a visitor to pick one or several instances of a Model which roughly looks like this: class Package(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to="foo") I have for that created a Form that looks like this: class PackageSelectionForm(forms.Form): packages = forms.ModelMultipleChoiceField(queryset=Package.objects.all(), widget=forms.CheckboxSelectMultiple()) Now, I'd like to display the image associated with each Package instance in the HTML form in their respective label tags (or near), but I can't manage to find a way to access the instances from the form fields. Do you see how I can? thanks -
django testing wrapped function view with mock
I am working through learning mock and I cannot figure out why this is not working... @validate_captcha def sendemail(request): ... email.send() return HttpResponse('Your email has been sent. Thank you for contacting us') I have a wrapper that validates google recaptcha and I need to test this view but I cannot figure out how to get around the wrapper. I tried this.... @patch('main.views.sendemail') def test_sendmail_captcha_pass(self, mock_sendemail): """Testing the view after the captcha passing""" mock_sendemail.return_value = True things = Things() data = { 'subject': 'test subject', 'name': 'john appleseed', 'email': 'john@apple.com', 'content': 'content of the message'} post_url = reverse("main:contact_email") result = things.client.post(post_url, {}) self.assertTrue(result.status_code == 401) Since the sendemail function is already wrapped, I am using the sendemail function for @patch instead of the validate_captcha function but I cannot see what to do next. I have tried making a mock object in the shell and verified that it does indeed give a a wrapped version of the sendemail function -
Google ReCAPTCHA VALIDATION FAILED WITH DJANGO
Even when the entered key is equal to the captcha text i got always the exception raise Recaptcha Invalid Challenge Error(challenge id). This is my backend script validation : recaptcha_client = RecaptchaClient('6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe', '6LeuNO4SAAAAAAdkaCUi6ybtISPI-YhIlOadgFNF&hl') try: is_solution_correct = recaptcha_client.is_solution_correct( str(request.POST["recaptcha_response_field"]), str(request.POST["recaptcha_challenge_field"]), '127.0.0.1', ) except RecaptchaUnreachableError as exc: print exc.message except RecaptchaException as exc: print exc.message else: if is_solution_correct: print('it works') else: print('captcha error') And this is the part of template script reserved for the captcha input <script type="text/javascript" src="https://www.google.com/recaptcha/api/challenge?k=6LeuNO4SAAAAAAdkaCUi6ybtISPI-YhIlOadgFNF&hl=en"></script> <noscript> <iframe src="https://www.google.com/recaptcha/api/noscript?k=6LeuNO4SAAAAAAdkaCUi6ybtISPI-YhIlOadgFNF&hl=fr" height="300" width="500" frameborder="0"></iframe><br /> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type='hidden' name='recaptcha_response_field' value='manual_challenge' /> </noscript> -
Bitnami Django Stack - not importing modules
I just tried deploying my Django application on my windows machine using Bitnami's Django stack. However, when I try to access my project via localhost/myapp/, I get an error stating that I can't load my modules/python libraries. I checked via pip and I have these modules installed. It seems this error applies to all my modules/python libraries. How do I solve this? Thanks! -
Python If Statement: Check if any item is in list
I am using Django's aggregate query expression to total some values. The final value is a division expression that may sometimes feature zero as a denominator. I need a way to escape if this is the case, so that it simply returns 0. I've tried the following, as I've been using something similar my annotate expressions: from django.db.models import Sum, F, FloatField, Case, When def for_period(self, start_date, end_date): return self.model.objects.filter( date__range=(start_date, end_date) ).aggregate( sales=Sum(F("value")), purchase_cogs=Sum(F('purchase_cogs')), direct_cogs=Sum(F("direct_cogs")), profit=Sum(F('profit')) ).aggregate( margin=Case( When(sales=0, then=0), default=(Sum(F('profit')) / Sum(F('value')))*100 ) ) However, it obviously doesn't work, because as the error says: 'dict' object has no attribute 'aggregate' What is the proper way to handle this? -
405 error when custom-defined PATCH method is called for Django REST APIView
I am making an API call in the test client: response2 = self.client.patch('/object/update/%d/' % object_id, {'object_attribute':4}) The relevant serializer and view class for the object: class ObjectUpdateSerializer(serializers.ModelSerializer): class Meta: model = Object include=('object_attribte','another_attribute',) class ObjectView(APIView): def patch(self, request, pk, format=None): obj = Object.objects.get(id=pk) data = request.data.copy() """do some stuff with the data here...""" serializer = ObjectUpdateSerializer(instance = obj, data=data, partial=True) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data,status.HTTP_200_OK) I was able to work with the PUT method when I used that, but I wanted to have the API call methods be more in-line with what the methods actually mean (so PATCH would be a partial replacement). However, the response to the test client call above is this: {u'detail': u'Method "PATCH" not allowed.'} Which is a 405 error (method not allowed). I checked to see if there were any issues with Django 1.10, and I also got this output in the django shell: >>> from django.views.generic import View >>> View.http_method_names [u'get', u'post', u'put', u'patch', u'delete', u'head', u'options', u'trace'] It appears as if it isn't an issue with Django's settings, but something that I've set up. What could be the issue here?