Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Unittest URL call with a different Django User
I have the following unittest class in Django. class TmpUrlTest(TestCase): def setUp(self): self.client = Client() test_group = Group('test_group') test_group.save() self.api_url = "/tmp_url/" self.test_user = User.objects.create(username='user1') self.test_user.set_password('pass') self.test_user.save() self.test_user.groups.add(test_group) def test_url(self): response = self.client.get(self.api_url) self.assertEqual(response.status_code, 200) Now in my get call, I want the user to be user1. Any ways to do this while making a call? -
Custom variable in Google analytics not capturing data from Django site?
I'm making a website in Python Django and I'd like to add my a custom variable (dimension with user level scope) to my Google Analytics. So, I created directions in creating one from this GA instructions page, yet my custom variable is not being tracked in my dashboard. I can see it in Reporting > Audience > Custom > Custom variables. The dimension is available for me to add as a secondary dimension (although strangely not as primary dimension - or is it auto selected because I have just one custom variable and the primary dimension in the table is auto selected as 'Custom Variable (Key 1)'?) Why am I not getting any data for my custom variable? I'm supposed to be getting the registered user's email. I've tried user.email and user.user.email and one of them should've worked for my site, but neither are capturing data. I can see the traffic being recording in real time as I reload a page, so code is fine, hits are being sent and recorded. Is my custom variable wrong? Did I overlook something in defining it? Or is there some 24 hour window for me to see custom variable data? It's my first … -
Deletion of objects in Django with foreign key in it
This question might be a stupid one, but I need to validate it from the SO community. I have 2 models. class Address(models.Model): name = models.CharField(max_length=100) area = models.ForeignKey(Area, null=True) class Area(models.Model): name = models.CharField(max_length=20) Now If I want to delete one instance of Address, will it delete the instance of Area object it is pointing to as a Foreign key? address = Address.objects.filter(...).delete() -
Forward déclaration with serializer
I have the two following serializers: class ActionSerializer(BaseSerializer): name = serializers.CharField(max_length=20) content = ContentSerializer(many=True, allow_null=True) elements = CarrouselElementSerializer(many=True, allow_null=True) class ContentSerializer(BaseSerializer): actions = ActionSerializer(many=True, allow_null=True) However when I try this code I have the following error: NameError: name 'ContentSerializer' is not defined I have read many explaination such as declaring the content while overloading the __init__ method but I was wondering if you have any easier/cleaner solution. I'm trying to serialize/deserialize json objects and I'm pretty sure I don't have a design problem in this kind of data Thanks for your advices -
Time issue in django with time and month in js
I have django (1.8) app with settings: Issue with date time TIME_ZONE = 'Europe/Berlin' USE_I18N = True USE_L10N = True USE_TZ = True and filed in models.py: from = models.DateTimeField('from', blank=True) and when I set hour for example 11:00 i get in template 10:00 Issue with month in js - I want to put month in js and I have to subtract one month but in template I get: {{ object.livestream_from|date:"m" }} - 1 -
Connect new celery periodic task in django
It's not a question but help to those who will find that the declaration of periodic tasks described in celery 4.0.1 documentation is hard to integrate in django: http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#entries copy paste celery config file main_app/celery.py: from celery import Celery from celery.schedules import crontab app = Celery() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) # Executes every Monday morning at 7:30 a.m. sender.add_periodic_task( crontab(hour=7, minute=30, day_of_week=1), test.s('Happy Mondays!'), ) @app.task def test(arg): print(arg) Question But what if we use django and our tasks are placed in another app? With celery 4.0.1 we no longer have @periodic_task decorator. So let's see what we can do. First case If you prefer to keep tasks and their schedule close to each other: main_app/some_app/tasks.py from main_app.celery import app as celery_app @celery_app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello')) @celery_app.task def test(arg): print(arg) We can run beat in debug mode: celery -A main_app beat -l debug and we will see that there's no such periodic task. Second case We can try to describe all periodic tasks in config file like this: main_app/celery.py ... app = … -
How can I speed up this Django query that uses distinct in a postgresql database and order it correctly?
I hope you can help me. I have this database filled with thousands of records, a lot of these are duplicated (different internal id but same 'idd') Basically what I need is to query the database to get the first x records with only 1 product (distinct idd) and ordered by '-sold_count' So this is the query I'm trying: Product.objects.distinct('idd').order_by('idd', '-sold_count')[:2000] Problem 1: That takes roughly 30 seconds, and I fear it will take longer with more data. How can I make it much faster? Problem 2: Also it doesn't order it by sold_count descending, if anything it seems to be doing the opposite. How can I order it by -sold_count? Tried removing the '-' to experiment but results seem to be the same. Other information: idd is a CharField sold_count is an IntegerField Hope this is clear enough, if not you can ask any question you may have. Thanks -
HTTP/1.0 301 Moved Permanently-Django
I have created a API using djangorestframework, but when i run it in terminal by using python manage.py runserver command it shows "HTTP/1.0 301 Moved Permanently" error.This the Message which it shows But the cool thing is , when i run it in browser it displays the data . This the result in Chrome I wanted to know had happened in it. And in this the POST call also is not working. Below is the code: serializers.py from rest_framework import serializers from snippets.models import Snippet class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('title','code',) def create(self, validated_data): return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.save() return instance Views.py from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer # Create your views here. class JSONResponse(HttpResponse): def __init__(self,data,**kwargs): content = JSONRenderer().render(data) kwargs['content_type']='application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() … -
Passing parameter from template to view in Django
A Django noob here. I'm stuck with my problem regarding exporting cvs in django. I'm currently successfully exporting a csv file containing all the objects(Product) in the database using this function in views.py of my Model Product. def export_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product-inventory.csv"' writer = csv.writer(response) writer.writerow(['Product Name', 'STATUS']) products = Product.objects.all().values_list('name', 'status') for product in products: writer.writerow(product) return response This is in my template <a class="export-btn" id="test" href="{% url 'export_csv' %}">Export</a> And this is the url.py url(r'^export/csv$', product_views.export_csv, name='export_csv') The question is how can I change dynamically the Product.objects.all() in my export_csv function so that it will be equal to the product list obtained from the user using search (using request.GET in another function)? Thanks in advance. -
Django File-Directory inside Python
I have created an CSV-FileReader inside an Django-Project. My question is where to put the csv-file ? My code looks so: with open(self.csvfile) as csvfile: csvreader = csv.reader(csvfile, delimiter=';') # Skip first line from csv-file csvreader.next() for row in self.read_csv(csvreader): .... Where is the best place inside an django-proect tu put my csvfile "self.csvfile" and what is the best way to reference to it. I think it is not nice, that self.csvfile would an rel-path like '/etc/blah/blah/blah/*.csv' I hope somebody could give me an nice tipp. Thanks -
Do you support Django 1.6.3 django-celery 3.1.9
I can not start working site. I am using Django 1.6.3 and django-celery 3.1.9 (Windows 7) (test) D:\test>python manage.py migrate Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "D:\test\lib\site-packages\django\core\management\__init__.py", line 399, in execute_from_command_line utility.execute() File "D:\test\lib\site-packages\django\core\management\__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\test\lib\site-packages\django\core\management\base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "D:\test\lib\site-packages\django\core\management\base.py", line 284, in execute self.validate() File "D:\test\lib\site-packages\django\core\management\base.py", line 310, in validate num_errors = get_validation_errors(s, app) File "D:\test\lib\site-packages\django\core\management\validation.py", line 34, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "D:\test\lib\site-packages\django\db\models\loading.py", line 196, in get_app_errors self._populate() File "D:\test\lib\site-packages\django\db\models\loading.py", line 78, in _populate self.load_app(app_name) File "D:\test\lib\site-packages\django\db\models\loading.py", line 99, in load_app models = import_module('%s.models' % app_name) File "D:\test\lib\site-packages\django\utils\importlib.py", line 40, in import_module __import__(name) File "D:\test\lib\site-packages\djcelery\models.py", line 14, in <module> from celery.utils.timeutils import timedelta_seconds ImportError: No module named timeutils The Internet information met that they can not be compatible, but to find their own compatibility can not. If you know how to solve my problem, I will be grateful! -
How to send csrf token in ajax requests for django 1.11+
Apparently 1.11 will start to make use of storing the csrf token in sessions (source). Although cookies will still be available, at the moment I'm sending ajax requests with the token in the header: XMLHttpRequest.setRequestHeader("X-CSRFToken", csrftoken); How would sessions change what I have to do with my ajax requests for them to pass csrf security checks? -
Django template: regroup dictsort method
I am trying to regroup a set of items by a @property (method) their class define, rather than an attribute: class Item: @property def some_property: return 1 if condition else 2 And here's how I am regrouping: {# several previous regroupings #} {% regroup items.list by some_property as items_by_some_property %} {% for group in items_by_some_property %} Group {{ group.grouper }} {% for item in group.list %} {{ item }} ({{ group.grouper }}) {% endfor %} {% endfor %} And I noticed this is not being grouped as expected, because rather than having the following output: Group 1 Item a (1) Item c (1) Item d (1) Group 2 Item b (2) Item e (2) I am having this other output: Group 1 Item b (2) Item a (1) Item c (1) Item e (2) Item d (1) I figured this is like it happens when using groupby where you need to sort before grouping otherwise you get unwanted results like above, so I tried doing this instead: {% regroup items.list|dictsort:'some_property' by some_property as items_by_some_property %} But it seems like since some_property is not an attribute of Item, the dictsort ordering is failing (not working as expected, that is, ordering does … -
Django IOError failed to write data - Exception occurred processing WSGI script
[Mon Dec 12 10:45:23 2016] [error] [client 178.161.91.227] (70007)The timeout specified has expired: mod_wsgi (pid=941): Unable to get bucket brigade for request. [Mon Dec 12 10:45:23 2016] [error] Internal Server Error: /profile/ [Mon Dec 12 10:45:23 2016] [error] Traceback (most recent call last): [Mon Dec 12 10:45:23 2016] [error] File "/sites/virtualenvs/capstone/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response [Mon Dec 12 10:45:23 2016] [error] response = self.process_exception_by_middleware(e, request) [Mon Dec 12 10:45:23 2016] [error] File "/sites/virtualenvs/capstone/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response [Mon Dec 12 10:45:23 2016] [error] response = wrapped_callback(request, *callback_args, **callback_kwargs) [Mon Dec 12 10:45:23 2016] [error] File "/sites/virtualenvs/capstone/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view [Mon Dec 12 10:45:23 2016] [error] return view_func(*args, **kwargs) [Mon Dec 12 10:45:23 2016] [error] File "/sites/virtualenvs/capstone/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view [Mon Dec 12 10:45:23 2016] [error] return self.dispatch(request, *args, **kwargs) [Mon Dec 12 10:45:23 2016] [error] File "/sites/virtualenvs/capstone/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch [Mon Dec 12 10:45:23 2016] [error] response = self.handle_exception(exc) [Mon Dec 12 10:45:23 2016] [error] File "/sites/virtualenvs/capstone/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch [Mon Dec 12 10:45:23 2016] [error] response = handler(request, *args, **kwargs) [Mon Dec 12 10:45:23 2016] [error] File "/sites/projects/capstone/app/views.py", line 258, in get [Mon Dec 12 10:45:23 2016] [error] pk = request.data.get('pk', None) [Mon Dec 12 … -
set webhook of telegram bot python
i want use telegram bot as webhook with python (django). i know for using webhook i must use https so i use http://pythonanywhere.com/ that support https (my domain is https://ehsan2589040.pythonanywhere.com/) and i can successfully set but it dont work my question is 1)should i post certification to telegram or my host support https is enough 2) any body know where is problem the code i use in django is simple urls.py: from mysite.view import hello,printesh urlpatterns = [ url(r'',printesh), url(r'^hello$', hello), url(r'^admin/', admin.site.urls), view.py: def printesh(request): x = urllib.request.urlopen('https://api.telegram.org/bot314538820:AAHyD87yEHsDd-***/sendmessage?chat_id=****&text=hi') return HttpResponse(x.read()) -
Work with prices an currencies using my own exchange rate source?
I'm looking for a way to work with Prices and Currencies. In my project, I compare prices of products which can be in different currencies. For now, the price is in decimal.Decimal format. I want to migrate project to work with different currencies. Unfortunately, django-currency-exchange and similar modules work with OpenExchangeRates api. Do you know a stable and reliable module in which I can use my own source (https://www.ecb.europa.eu/sta…/eurofxref/eurofxref-daily.xml)? django-money looks good but to currency exchanging, it works with django-money-rates which uses OpenExchangeRates too. I expect to work with prices this way: product.get_price('EUR') or something like this. -
<object> is not JSON serializable django
I have a list of all product with all specifications . So now i want to send JsonResponse with that list with pagination of 10 product at a time. when i try to send all product all_pro = Products.objects.all() return HttpResponse(all_pro ) it gives me a error is not JSON serializable. my product model class Products(models.Model): product_name = models.CharField(max_length=50,null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) price = models.IntegerField(default=0,null=True, blank=True) posting_date = models.DateTimeField(auto_now_add=True, blank=True) quantity = models.IntegerField(default=1,null=True, blank=True) extra_text = models.TextField(null=True, blank=True) color = models.CharField(max_length=50,null=True, blank=True) contact_number = models.CharField(max_length=50,null=True, blank=True) is_active = models.BooleanField(default=True) So how can i send JsonResponse to front end. Thanks in advance. -
Different result post serialization depending on the environment
I send request from rest web json form and custom_answers field a exist with converted list data, but when i send the same data from the test with ApiClient, custom_answers null list. print validated_data create serializer method from restf web json form {'custom_answers': [OrderedDict([('user', <SimpleLazyObject: <User: 123>>), ('question', <Question: Вопрос 2>), ('text', 'TExt')]), OrderedDict([('user', <SimpleLazyObject: <User: 123>>), ('question', <Question: Вопрос 1>), ('text', 'tes')])], 'poll': <Poll: Опрос 1>, 'user': <SimpleLazyObject: <User: 123>>} print validated_data create serializer method from test env {'custom_answers': [], 'poll': <Poll: Опрос 1>, 'user': <User: 123>} print serializer init data from test env: <QueryDict: {'poll': ['1'], 'custom_answers': ["{'question': 2, 'text': 'TExt'}", "{'question': 1, 'text': 'tes'}"]}> print serializer init data from web from with json data: {custom_answers': [{'text': 'TExt', 'question': 2}, {'text': 'tes', 'question': 1}], 'poll': 1} Sorry for my English. serializers.py class CustomUserAnswerSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=CurrentUserDefault() ) class Meta: model = CustomUserAnswer fields = ('user', 'question', 'text') class CompletedPollSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=CurrentUserDefault() ) custom_answers = CustomUserAnswerSerializer( many=True, write_only=True, required=False ) class Meta: model = CompletedPoll fields = ('poll', 'user', 'custom_answers') def create(self, validated_data): print(validated_data) models.py --- between a models not related class CompletedPoll(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='ended_polls' ) poll = models.ForeignKey(Poll) ended_date = … -
Old Python 2.7 is still used for my Django application instead of a virtual environment
So, I have two different versions of Python on my CentOS machine - 2.7 and 3.4. What I want is to simply run my Django application using Python 3.4 and not that old outdated garbage. To do this I created a virual environment, so that my folder structure now looks like this \vwrapper \bin \include \lib \lib64 ... I created this virtual environment using Python 3.4. After that I activated this environment like so: $ source vwrapper/bin/activate (vwrapper) [root@...] So, I clearly see, that I now inside this virtual environment. I now even can check, that indeed I'm using python 3.4: (vwrapper) [root@...] # python --version Python 3.4.5 At this stage everything looks good. Then I installed django: (vwrapper) [root@...] # pip install django Again it's ok. In \vwrapper\bin I can now see some django tools. I then use one of these tools to create my first django application: (vwrapper) [root@...] # bin/django-admin startproject accent Looks good. I go to wsgi.py and make a little correction: import os, sys path = '/var/www/vwrapper/accent' if path not in sys.path: sys.path.append(path) Then I go to settings.py and also make a little correction: ALLOWED_HOSTS = ['*'] Great! The only thing that remains to be … -
SQL - DJANGO : sql to query set
I have 2 tables: puzz_meeting_candidats : - id, canceled, candidat_id, meeting_id puzz_meeting : - id, Client I have a query follow: SELECT U1.candidat_id AS Col1 FROM puzz_meeting_candidats U1 INNER JOIN puzz_meeting U2 ON ( U1.meeting_id = U2.id ) WHERE U2.Client LIKE '%ipsos%' AND U1.canceled = False How to convert query above to query in django ? I so thank you if you can help me !! -
Django - Update or create syntax assistance (errror)
ive followed the guide in the queryset documentation as per (https://docs.djangoproject.com/en/1.10/ref/models/querysets/#update-or-create) but i think im getting something wrong: my code is as per below: maint = CircuitMaintenance( circuit = s, ref = m_ref, start_time = times[0], end_time = times[1], notes = content ) maint, CircuitMaintenance.objects.update_or_create(ref=m_ref) m_ref, is the unique field that will match the update, but everytime i run this in tests i get sites_circuitmaintenance.start_time may not be NULL but ive set it? -
virtualenv is not compatible with this system
I am trying to create a virtual env on a mac when is execute the following line i get an error saying virtualenv is not compatible with this system virtualenv env_new Using base prefix '/Users/ravinkohli/anaconda3' New python executable in /Users/ravinkohli/env_new/bin/python dyld: Library not loaded: @rpath/libpython3.5m.dylib Referenced from: /Users/ravinkohli/env_new/bin/python Reason: image not found ERROR: The executable /Users/ravinkohli/env_new/bin/python is not functioning ERROR: It thinks sys.prefix is '/Users/ravinkohli' (should be '/Users/ravinkohli/env_new') ERROR: virtualenv is not compatible with this system or executable -
Is foreign key reference stored at django level or MySQLDB
Consider that there is a mysql table defined as CREATE TABLE `table1` ( `id` int(11) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1 and table2 defined as CREATE TABLE `table2` ( `id` int(11) NOT NULL DEFAULT '0', `table1_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Here table 2 references 1 and this relationship is mentioned in models. Now when I query these tables in MySQL I do not see anything like references from table2 to 1. I would like to know is it the responsibility of the django to store such relationships. If so then in case I have to change my ORM from django to something else how do I manage to migrate such relationships. -
Add extract fields to Django model serializer while doing validations
Supposed I had the following model, and modelSerializer: models.py class Approve(models.Model): process = models.IntegerField(verbose_name='Associated Process') content = models.CharField(max_length=300, verbose_name="Approval Content") serializers.py class ApproveSerializer(serializers.ModelSerializer): class Meta: model = Approve fields = ('id', 'process' ,'content') def validate(self, value): process = value['process'] try: something_else = Something.objects.get(process) except Something.DoesNotExist: raise serializers.ValidationError('Invalid Process') return value The thing is that I want to validate the incoming data in serializers.py, instead of views.py. You can notice that in order to make a validation check, I had query the database for something_else. The problem is that I want to use this object something_else in the views.py, instead of making another database query. Is there any ways I can pass it with the serializer, without causing a serializer validation error when call serializer.is_valid() method. Any suggestions will be welcomed, thanks in advance. -
After installing django debugger, Pycharm debugger not working
I am working with Python 2.7.6 with PyCharm 3.1.2 . I installed django on my computer . When i wanted to debug code that doesn't use django , the PyCharm debugger gave the following notes. Any one can assist? Traceback (most recent call last): File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\PyCharm\helpers\pydev\pydevd.py", line 2, in from django_debug import DjangoLineBreakpoint File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\PyCharm\helpers\pydev\django_debug.py", line 3, in from pydevd_comm import CMD_SET_BREAK File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\PyCharm\helpers\pydev\pydevd_comm.py", line 107, in import pydevconsole File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\PyCharm\helpers\pydev\pydevconsole.py", line 21, in import fix_getpass ImportError: No module named fix_getpass