Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update balances on financial ledger
I've read a lot of different opinions on this so far, and remain confused. I am working on a system that has thousands of clients, with tens of thousands of transactions - not very large (yet). It's a financial system, tracking transactions (inputs/outputs). The system is running on Django (Python) with PostgreSQL. To determine someone's balance we run SQL queries against the ledger and extract the resulting 'balance'. However, as the transactions grows this will likely become an issue. It also makes some queries very difficult / extremely expensive. An example: Find all customers who have an account balance greater than 10,000. This would involve computing the current balance for each customer, annotating the resulting record set, and then querying that. This could become extremely expensive very quickly. I've seen a number of solutions recommended: Using db triggers to update a running total Using a caching layer to reduce the db queries Structuring the application to eliminate these expensive queries altogether (this is not an option) What is the best practice in this type of application? -
Unknown Heroku Git Message Won't allow me to Push
I was configuring my Django code and db before deploying to heroku. After I push to Heroku via git, I get successfully installed messages, then it follows with this. Is it because I have an old dependency in requirements.txt? remote: $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line 302, in execute remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/conf/__init__.py", line 55, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/conf/__init__.py", line 43, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/conf/__init__.py", line 99, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.5/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 986, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 969, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 673, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 662, in exec_module remote: File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed remote: File "/app/hypetroopdjango/settings.py", line 147, in <module> remote: DATABASE['default'].update(db_from_env) remote: NameError: name 'DATABASE' is not define remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above … -
Tastypie: can't get one field from related resource
Problem in that ToManyField returns set of objects or set of urls. How i can get only one field from related table? class PlaceResource(ModelResource): location = fields.ManyToManyField(PlaceLocationResource, 'location') action = fields.ToManyField('menus.resources.ActionResource', attribute= lambda bundle: bundle.obj.action.distinct('type').only('name'), null=True, related_name='place', full=True) I tried to manipulate with querySet of 'action' and add method 'only', but it doesn't work ('distinct' workes fine), it returns all fields of the 'action'. Maybe there is same method 'only' exactly for tastypie, but i didn't saw that. Thank you. -
Using Date Picker to filter data for graphs in Django
I am trying to plot graphs from django models using Django Chartit. I am using date picker to select dates. I have a model like this class racktestresult(models.Model): idTestResult = models.IntegerField() Date = models.DateTimeField() ProjectName = models.CharField(max_length=255) I have a view like this def reports_chart_view(request): revodata = \ DataPool( series= [{'options': { 'source': racktestresult.objects.all()}, 'terms': [ 'Author', 'PassNumbers', 'TotalActions', 'Result', 'FailNumbers']} ]) cht = Chart( datasource = revodata, series_options = [{'options':{ 'type': 'line', 'stacking': False}, 'terms':{ 'Author': [ 'TotalActions'] }}], chart_options = {'title': { 'text': 'Pass and Fail Result of Revo Test Cases'}, 'xAxis': { 'title': { 'text': 'Total Action'}}}) return render( request, "app/reports.html", { 'revochart': [cht], } ) I have a template like this <link href="{% static 'app/content/jquery-ui.css' %}" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <script> $(function() { $( "#datepicker-1" ).datepicker(); $( "#datepicker-2" ).datepicker(); changeMonth: true, changeYear: true, yearRange: "1900:2012", }); </script> {% load chartit %} {{ revochart|load_charts:"chart_1 }} <li ><a id="chart_1" class="tab-fix" href="" data-toggle="tab">Chart 1</a></li> Data from from my racktestresult model idTestResult,Date,ProjectName,TestJobName,TestJobExecutionId,SuiteName,TestCaseID,Author,Tester,BoxType,BoxUnitAddress,BoxIP,TotalActions,TotalConditions,PassNumbers,FailNumbers,Result,ExecutionTime 9744,8/12/2016 20:13,VOD_EVO,STB-REVO/VMS-JOBS/VMS_01/Suite_01,jenkins-STB-REVO-VMS-JOBS-VMS_01-Suite_01-72,REG_AGREED_SUITE01,VOD_EVO_020_021.py,RANGAAL,v585102,VMS,105878443034,192.168.1.111,19,13,13,0,PASS,680 9746,8/12/2016 20:18,VOD_EVO,STB-REVO/VMS-JOBS/VMS_01/Suite_01,jenkins-STB-REVO-VMS-JOBS-VMS_01-Suite_01-72,REG_AGREED_SUITE01,VOD_EVO_025.py,RANGAAL,v585102,VMS,105878443034,192.168.1.111,17,15,15,0,PASS,308 9748,8/12/2016 20:22,VOD_EVO,STB-REVO/VMS-JOBS/VMS_01/Suite_01,jenkins-STB-REVO-VMS-JOBS-VMS_01-Suite_01-72,REG_AGREED_SUITE01,VOD_EVO_033.py,RANGAAL,v585102,VMS,105878443034,192.168.1.111,22,2,2,0,FAIL,220 Right now I am able to plot graph with what ever data I have. Is there any way to create graphs from selected date range? -
How to get rid of the duplicate Set-Cookie?
I have rest token login added into my django app. Now I see two set-cookie in the http respose, like below. One is obviously related to csrftoken. Seems the two set-cookie causes problem, any idea how can I fix it? HTTP/1.0 200 OK Date: Wed, 12 Oct 2016 21:53:44 GMT Server: WSGIServer/0.1 Python/2.7.6 Vary: Cookie Content-Type: text/html; charset=utf-8 Set-Cookie: csrftoken=YpQ0gkxrYqAolE4XMtkLgLMOajdErNor; expires=Wed, 11-Oct-2017 21:53:44 GMT; Max-Age=31449600; Path=/ Set-Cookie: sessionid=1drlllx17d417jhzfjvjuwzgnoxsrzix; expires=Wed, 12-Oct-2016 22:53:44 GMT; httponly; Max-Age=3600; Path=/ -
Schedule table updates in Django
How do you schedule updating the contents of a database table in Django based on time of day. For example every 5 minutes Django will call a REST api to update contents of a table. -
Analogs for Placeholder from Django-CMS or Streamfield from Wagtail without cms itself
I often need to implement rich content editing in my django projects. There are a lot of different wysiwyg-editors, but they are not good for creating complex content structure. Placeholder from Django-CMS or Streamfield from Wagtail can do it much better, but I don't want to add whole CMS to my project, because it brings a lot of unnecessary stuff into interface. All I need is just a field with ordered list of widgets inside + editing interface for it. Can you suggest something? -
Terminal shows wrong with python manage.py runserver
Working on a django app and all of the sudden I realized my terminal is showing thee wrong time. Running 10.10.5 Yosemite on my macbook air. When I go to run the server locally using python manage.py runserver everything runs and I can access the app fine through urls. However, I see the following in my terminal: System check identified no issues (0 silenced). October 12, 2016 - 21:12:28 Django version 1.10.2, using settings 'polls.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. In my settings.py file I have the following: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True Why would the local server not reflect my current timezone? -
Multiple tables OneToOne relation to a table serialize
This is Django ORM models class A(models.Model): ... class B(models.Model): a = models.Foreignkey(A, on_delete=models.CASCADE) class C(models.Model): a = models.Foreignkey(A, on_delete=models.CASCADE) And here are the serializers: class ASerializer(serializers.ModelSerializer): class Meta: model = A class BSerializer(serializers.ModelSerializer): a = ASerializer(many=False) class Meta: model = B class CSerializer(serializers.ModelSerializer): a = ASerializer(many=False) class Meta: model = C B and C are working as expected. Problem 1: Now, if I want to get data of B and C from serializer A by doing b = BSerializer(many=False) and c = CSerializer(many=False). I will get an error that NameError: name 'BSerializer' is not defined and if I put B and C serializer above A errors for Aserializer. How do I fix this? Problem 2: B and C have one-to-one relation with A. So, when serializing A, it might not have a subsequent B or C or both data in B and C tables. So, in ASerializer b = BSerializer(many=False) c = CSerializer(many=False) might give errors if there is no relation between A and C for a particular row. How do I fix this? -
Front-end Tech Stack
I want to develop a web page to help me understand all the front end tech out there. I've done a ton of reading and tutorials and think I'm ready to dive in to a full blown project. Here is the tech stack I've identified I wanna use along with a lay-man description of what it is/does. Frontend Angular 2 - Javascript Framework Typescript 2 - another (better, easier) way of writing javascript Underscore.js - library for common and convenient operations jQuery - same as above Sass - like typescript but for CSS Middle-end Django - framework for db processing and admin controls Mongoose - ODM for MongoDB Backend Node.js - server to host and serve the web application MongoDB - db for the website to store all information Testing tslint - code quality analysis tool for typescript sass-lint - same as above but for Sass Jasmine - unit-testing for angular Tools Gulp - task runner to automate common tasks MongoDB Compass - GUI for MongoDB My main question is, does this technology stack all mix well? Is there anything contradictory/redundant/unnecessary etc here? -
python error parsing json
I'm trying to parse the information found in this link here: http://stats.nba.com/stats/playergamelog?DateFrom=&DateTo=&LeagueID=00&PlayerID=203518&Season=2016-17&SeasonType=Pre+Season What I want to pull is the information under rowSet (so 0, 1, 2, etc will be one entry) Code I'm using: urlPlayerLog = "http://stats.nba.com/stats/playergamelog?DateFrom=&DateTo=&LeagueID=00&PlayerID=203518&Season=2016-17&SeasonType=Pre+Season" responses = requests.get(urlPlayerLog) dataGameLogs = responses.json()['resultSets'][0]['rowSet'] This was working for me for months and then one day I kept getting the following error: Which made me think the issue was with dataGameLogs = responses.json()['resultSets'][0]['rowSet'] , but unsure why that is returning an error... -
How to deploy wagtail project to digitalocean?
I created my first project on wagtail and can't deploy it on digitalocean, help me please. I use last versions of Python, Django and Wagtail -
Django: How to send money from my account to other account
I am implementing a platform where users can book a guide tour. I need to send this money to my account (company) and then (few days later) to the guide who makes the tour (subtracting a % of commission). Do you know if it is possible to implement this? I have a clear idea how to implement the payment gateway, but I want to automate the second payment (the one that has to be done to the guide through my bank account). Thank you very much ;) The platform is developed using Django -
How can my user upload an image to email to me [Django]
I've got a simple website for a Screenprinting company built using Django 1.10 and Python 3.5.2, but I am having issues with my "Get a Quote" page. The idea is a user can go to www.example.com/quote/ and they are presented with a form. Here they put in their Name, Email Address, a Brief Message, and most importantly they can upload an image. When they click submit, this data gets sent to my email address as an email using the EmailMessage method. I have set up a simple email form plenty of times in the past so I know my settings.py file is fine. Here is my forms.py: class QuoteForm(forms.Form): name = forms.CharField(required=True) from_email = forms.EmailField(required=True) subject = "Quote" uploaded_image = forms.ImageField() message = forms.CharField(widget=forms.Textarea) Here is my views.py: def quote(request): form = QuoteForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] message = "From: " + name + "\n" + "Return Email: " + from_email + "\n" + "Subject: " + subject + "\n" + "Message: " + message uploaded_image = form.cleaned_data['uploaded_image'] msg = EmailMessage(subject, message, from_email, ['example@email.com'], reply_to=[from_email]) msg.attach_file(uploaded_image) try: msg.send() except BadHeaderError: return HttpResponse('Invalid header found') return HttpResponseRedirect('thankyou') return render(request, "quote.html", {'form': form}) When I … -
How to remove 'selected' attribute from item in ModelChoiceField?
ModelChoiceField adds attribute selected in HTML, if object from choices list has FK to parent object. How\where can I remove this 'selected' attribute in order to get just list of choices? Want to mention, that I need to remove just 'selected' attribute, i.e the value itself should not be removed from the list of choices. I need to hook it somehow from python side, not from HTML. I tried to find needed atribute in different places inside form, but no luck. -
How to get current user from a Django Channels web socket packet?
I was following this tutorial: Finally, Real-Time Django Is Here: Get Started with Django Channels. I wanted to extend the app by using Django User objects instead of the handle variable. But how can I get the current user from the received WebSocket packet in my ws_recieve(message) function? I noticed that both the csrftoken and the first ten digits of sessionid from the web socket packet match a normal HTTP request. Can I get the current user with this information? For reference the received packet looks like this: {'channel': <channels.channel.Channel object at 0x110ea3a20>, 'channel_layer': <channels.asgi.ChannelLayerWrapper object at 0x110c399e8>, 'channel_session': <django.contrib.sessions.backends.db.SessionStore object at 0x110d52cc0>, 'content': {'client': ['127.0.0.1', 52472], 'headers': [[b'connection', b'Upgrade'], [b'origin', b'http://0.0.0.0:8000'], [b'cookie', b'csrftoken=EQLI0lx4SGCpyTWTJrT9UTe1mZV5cbNPpevmVu' b'STjySlk9ZJvxzHj9XFsJPgWCWq; sessionid=kgi57butc3' b'zckszpuqphn0egqh22wqaj'], [b'cache-control', b'no-cache'], [b'sec-websocket-version', b'13'], [b'sec-websocket-extensions', b'x-webkit-deflate-frame'], [b'host', b'0.0.0.0:8000'], [b'upgrade', b'websocket'], [b'sec-websocket-key', b'y2Lmb+Ej+lMYN+BVrSXpXQ=='], [b'user-agent', b'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) ' b'AppleWebKit/602.1.50 (KHTML, like Gecko) Version' b'/10.0 Safari/602.1.50'], [b'pragma', b'no-cache']], 'order': 0, 'path': '/chat-message/', 'query_string': '', 'reply_channel': 'websocket.send!UZaOWhupBefN', 'server': ['127.0.0.1', 8000]}, 'reply_channel': <channels.channel.Channel object at 0x110ea3a90>} -
Django django.test Client post request
Working on hellowebapp.com Please help test valid form post using Django test client post request? response = self.client.post('/accounts/create_thing/', { 'name': dummy_thing.name, 'description': dummy_thing.description, }) Here's the TestCase Code Snippet: from django.contrib.auth.models import AnonymousUser, User from django.test import TestCase, RequestFactory from collection.models import Thing from collection.forms import ThingForm class SampleTest(TestCase): def setUp(self): # Every test needs access to the request factory. self.factory = RequestFactory() self.dummy_user = User.objects.create_user(username='dummy', password='nothings') self.dummy_thing = Thing.objects.create(name="Dummy Book", description="Book For Dummies.", slug="dummy-book", user=self.dummy_user) def test_form(self): dummy_thing = Thing.objects.get(name="Dummy Book") form = ThingForm(instance=dummy_thing) self.assertFalse(form.is_valid()) # No data has been supplied yet. form = ThingForm({ 'name': dummy_thing.name, 'description': dummy_thing.description, }, instance=dummy_thing) self.assertTrue(form.is_valid()) def test_form_post(self): dummy_thing = Thing.objects.get(name="Dummy Book") self.client.login(username=dummy_thing.user.username, password='nothings') # Test POST invalid data response = self.client.post('/accounts/create_thing/', { }) self.assertFormError(response, 'form', 'name', 'This field is required.') self.assertFormError(response, 'form', 'description', 'This field is required.') self.assertTemplateUsed(response, 'things/create_thing.html') self.assertEqual(response.status_code, 200) # Test POST valid data? # response = self.client.post('/accounts/create_thing/', { 'name': dummy_thing.name, 'description': dummy_thing.description, }) # self.assertEqual(response.status_code, 200) Here's the Model models.py class Thing(models.Model): name = models.CharField(max_length=255) description = models.TextField() slug = models.SlugField(unique=True) user = models.OneToOneField(User, blank=True, null=True) Note: user = models.OneToOneField(User, blank=True, null=True) "Thing.user" must be a "User" instance. column user_id is must be unique. views.py from django.contrib.auth.decorators import login_required … -
Show multiple forms on a single page without refresh django template
I am planning on creating a single page with toolbar on the top. [IMG]http://i66.tinypic.com/102nts3.jpg[/IMG] I want to click on different buttons on the toolbar and get the form without page refresh. Is there a way i can do it with Django templates if conditions? and is the page refresh necessary? {% if new button pressed %} {% else %} View.py if request.POST.get('new'): logger.info('user clicked new') elif request.POST.get('last'): logger.info('user clicked due next') elif request.POST.get('previous'): logger.info('user clicked due next') Is it doable or not? -
FBSDK Access token string is always nil
I am building an iOS app that uses facebook for user login and then will pass the token to my django web server to convert into a access token. The issue is that the FBSDK access token is appearing and can be used but is appearining as nil when trying to access the string value of it which can be seen in this function. I have been trying for hours to find the issue and so any sort of help would be much appreciated. func login(userType: String, completionHandler: @escaping (NSError?) -> Void) { let path = "api/social/convert-token" let url = baseURL!.appendingPathComponent(path) let params: [String: Any] = [ "grant_type": "convert-token", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "backend": "facebook", "token": FBSDKAccessToken.current().tokenString!, "user_type": userType ] /* Does appear */ print("THE TOKEN NO STRING IS \(FBSDKAccessToken.current()") /* Shows as nil */ print(" THE TOKEN IS \(FBSDKAccessToken.current().tokenString!)") Alamofire.request(url!, method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (response: DataResponse<Any>) in switch response.result { case .success(let value): let jsonData = JSON(value) self.accessToken = jsonData["access_token"].string! self.refreshToken = jsonData["refresh_token"].string! self.expired = Date().addingTimeInterval(TimeInterval(jsonData["expires_in"].int!)) completionHandler(nil) break case .failure(let error): completionHandler(error as NSError?) break } } } -
Django 3rd party image uploading service from browser
HiI want users to be able to upload their own photos from the browser, but I read that it isn't safe to let them upload files to your server without many protections. I need a image hosting website that has an easy API for uploading photos (for free). The only one I have found is Cloudinary, which is awesome, but following their tutorial didn't work. I guess the reason is it's outdated, and I'm using Django 1.10... If there is a way of doing so, even without a special API, (by sending requests to some image hosting site) I would like to give it a try as well. Thanks in advance! -
Wrong Behaviour doing tests on Django
I'm having problems to do test on Django. I've been reading the documentation of the responses and I can't do the same as they explain on the documentation. When I get the response, I only have access to response.status_code and can't access to context or redirect_chain when I write response.(and now PyCharm shows all available options). I've checked on settings.py and I've 'BACKEND': 'django.template.backends.django.DjangoTemplates' to be sure that I'm using Django templates so I don't know why don't work the test. I need configure something? The code of the test I'm trying to do it's: from django.test import TestCase from django.test.client import Client class Test(TestCase): def testLogin(self): client = Client() headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'} data = {} response = self.client.post('/login/', headers=headers, data=data, secure=True, follow=True) assert (response.status_code == 200) # self.assertRedirects(response, '/menu/', status_code=301, target_status_code=200) I'm not using Django authentication, the login form sends the data to an IDP and if the IDP sends with a correct answer, the "login" it's successful: def login(request): logout(request) message = None if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] headers = {'X-OpenAM-Username': username, 'X-OpenAM-Password': password, 'Content-Type': 'application/json'} data = {} req = requests.post('http://openam.idp.com:8090/openamIDP/json/authenticate', headers=headers, … -
Django admin not serving static files on Apache
I've seen similar questions but they are more than 4 years old and the answers doesn't work anymore. I have a site that works correctly on Apache, except for the admin staticfiles. The staticfiles work fine with Django's runserver. I'm kind of lost here, any advice will help. -
issubclass() arg 1 must be a class - How to pass parameter from Inline to Form?
In order to avoid code duplication, I want to pass parameter from inline to form, but I have error. My Inline: class SportUserCriteriasInlineAdmin(GenericTabularInline): model = CTSportOrPlaceTypesToCriteriasGroups form = test_form('user') extra = 1 verbose_name = 'User Sport' verbose_name_plural = 'Users Sports' My admin: @admin.register(SportTypesGroups) class SportTypeGroupsAdmin(admin.ModelAdmin): inlines = [SportUserCriteriasInlineAdmin] My Form (similiar to the answer from here): def test_f(user_or_team): class SportUserCriteriaChoicesFieldForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SportUserCriteriaChoicesFieldForm, self).__init__(*args, **kwargs) if 'user_or_team' == 'user': # DO SOMETHING class Meta: model = CTSportOrPlaceTypesToCriteriasGroups fields = '__all__' The line inlines = [SportUserCriteriasInlineAdmin] generates error: File "/home/sweetuser/www/sportproject/lib/python3.5/site-packages/django/contrib/admin/checks.py", line 255, in _check_form if hasattr(obj, 'form') and not issubclass(obj.form, BaseModelForm): TypeError: issubclass() arg 1 must be a class -
django: how to make two models share one unique primary key
In my case, I have two models: Equipment and Asset, they both have their own fields but they should share one unique field: asset_number. By sharing, I mean that when creating a equipment, the asset_number user inputted would be check against both Equipment and Asset database. If it already exist in any, then there is going to be prompt telling the user that this is not unique. For only one model, this is easily done by setting unique = True. However if I would like to do for two models, how should I proceed? TIA -
Django Wagtail Form Builder Form Stopped Working - No Error
I am using the Wagtail Form builder for the contact page form and everything worked great when I first set it up - it logged the data to the admin area and sent the notification email. I just launched the site last night and decided to test the form again...nothing. Doesn't give me the thank you message, email, error or log anything to the admin forms log. Without an error, I really have no way of troubleshooting this; I am just hoping someone else has seen this happen and can offer some advice. Below is a screenshot of my forms log to confirm it was working. Thank you.