Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Refresh values of Django app in Docker (Cloudron)
So I have some Python knowledge, but am a complete beginner with Django and Docker. My problem is the following: I packaged a very basic Django app into a Docker app (actually a Cloudron app, Cloudron is a solution based on Docker). The app is now running on my server (eth.ncollig.net). It's purpose is to give me the price of Ether. But the view.py script ran at the startup of the app on the server, the value of the variable, the price of ether in euros, has been set to 251.7, and it is never refreshed. I would like the value of this variable to be recalculated at every new page load. What should I do to achieve this? Thanks in advance for any help. Here's my views.py: from django.http import HttpResponse from coinbase.wallet.client import Client client = Client('yhKYHa8AkQaHXDMc','quspNs86vAvsRtyuGmE3nC5o9Nki2pqP') rates = client.get_exchange_rates(currency='ETH') eth_rate = rates['rates']['EUR'] def index(request): return HttpResponse("1 ETH = %s EUR" % eth_rate) Here's my start.sh, used to launch the gunicorn server: #!/bin/bash # Start Gunicorn processes echo Starting Gunicorn. exec gunicorn ethprice.wsgi:application \ --bind 0.0.0.0:8000 \ --workers 3 The Dockerfile: FROM cloudron/base:0.11.0 MAINTAINER Authors name <support@cloudron.io> RUN mkdir -p /app/code WORKDIR /app/code COPY ethprice /app/code/ COPY start.sh … -
AttributeError - When using Django NestedFields serializers
I've 2 models:- class Users(models.Model): first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255) class UserAddress(models.Model): line1 = models.CharField(max_length=255) country = models.CharField(max_length=255) user = models.ForeignKey(Users) The user model & user address model. Following are the 2 serializers. class UserAddressSerializer(ModelSerializer): class Meta: model = UserAddress exclude = ('id', 'user') class UserSerializer(ModelSerializer): address = UserAddressSerializer(many=True) class Meta: model = Users fields = '__all__' def create(self, validated_data): address = validated_data.pop('address', []) user = Users.objects.create(**validated_data) for ad in address: UserAddress.objects.create(user=user, **ad) return user The data I receive from the client is { "first_name": "string", "last_name": "string", "address": [{ "line1": "asd", "country": "asd", }], } This is how I create a new user and its corresponding address. class UserCreate(GenericAPIView): serializer_class = UserSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserSerializer(data=data) if not serializer.is_valid(): return user = serializer.save() response = { 'user_id': user.uuid } return Now, upon getting the user details back, I receive an error saying AttributeError: Got AttributeError when attempting to get a value for field `address` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Users` instance. Original exception text was: 'Users' object has no attribute 'address'. This is how I get the … -
Django rest-api: Postman can't see CSRF token
I'm using django 1.11.6 and python 3.5 on an ubuntu server. I have an api for user registration. This is my curlcommand: curl -i -H 'Accept: application/json; indent=4' -X POST https://mydomain/users/:register/ -d "id=222111&firstname=andy&yearofbirth=2007&lastname=Chris&othernames=" When I use it in cygwin I get this response which is the desired: HTTP/1.1 200 OK Date: Thu, 26 Oct 2017 06:41:00 GMT Server: Apache/2.4.18 (Ubuntu) Allow: POST, OPTIONS Vary: Accept,Cookie Content-Length: 188 X-CSRFToken: acY2oPGkkqkzBe9itBq56oFeTFAllqv2bS39c7TpPN9LlGh90E1FxsI0YXLlu1Vu X-Frame-Options: SAMEORIGIN Set-Cookie: csrftoken=QfxnUGTmrRi1MThcn8Qau5ytnt2NR8tdRVCuIY6rWe7dwlp3UbrKV9BfsLdN0JTF; expires=Thu, 25-Oct-2018 06:41:01 GMT; Max-Age=31449600; Path=/ Content-Type: application/json { "isnew": "true", "user": { "othernames": "", "id": "222111", "firstname": "Andy", "yearofbirth": 2007, "lastnames": "Chris" } } As I can see, I have X-CSRFToken header and `csrftoken' cookie. When I try to run the same curl command from postman I get: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this HTTPS site requires a 'Referer header' to be sent by your Web browser, but none was sent. This header is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable 'Referer' headers, please re-enable them, at least for this site, or for HTTPS connections, or for 'same-origin' requests. My function … -
Django elastic search filter Aggregations
I have two filters in my django elastic search... search = search.filter("term", status=Status.ACTIVE) search = search.filter("term", organization__pk=self.request.user.organization.pk) How can I aggregate them ? -
Django Query Regex for filtering data
I have a Category model class Category(models.Model): title = models.CharField(_('title'), max_length=200, blank=False) qs = Category.objects.all() Say Title values are Trailer1 Trailer2 ABC Trailer BCD EFG Trailer EFG GEF TED Trailer ..... These values are in random order. And on filtering we would need the data in the above order I want to perform ranking / selection . 1) Starts with search string qs1= qs.filter(title__istartswith= format('trailer')) What's the best way of filtering the results. I can get the output easily in pythonic way. But was trying out with regex and loops. Any suggestions will help. Thanks -
Django- Retrieve all details from mysql database
I have a django application connected to mysql database. In the MySQL database I have a table called Evaluation with eval_id, eval_name and date as its columns. From my django view I am trying to get the releveant data with the below code. from django.http import HttpResponse, JsonResponse from .models import Teacher, Subject, Evaluation, Teaches, eval_summary # Create your views here. def index(request): eval_list = Evaluation.objects.all() return HttpResponse(eval_list) Here in the output I am only getting the eval_name entries and not the eval_id and date. What should I include to get all the details? My output is just 2014_Term1 2014_Term2 2014_Term3 2015_Term1 so on.. I also want the ID and date to be associated with each entry. -
Django+PostgreSql: Can I run out of id/pk?
In my application I am going to need a setup where every user has some derived/calculated information in the database. It should be maximum 100 different data sets with each around 100 rows (100x100) per user. This rows need to be refreshed around every three months. So, let's say with 10000 users, if everybody uses all hundred places that would be 100M rows recreated every 3 months. As far as my knowledge the postgre int field is 2147483647, that is 2100M+. So, am I going to run out of id/pk in around 5 years with this setup? Should I rethink my setup or is there a way around? I am using Python 2.7.6, postgresql server is 9.3 and django 1.8. -
Django forms field not appearing on webpage
Fields I have added in django forms are not visible on webpage. Attached model, view and html for the reference below. This is an additional filed which I intent to add to the forms, I am new to Django and learning by enhancing the current project. Thanks forms.py class ClientProfileForm(forms.ModelForm): class Meta: model = ClientProfile fields = ('full_name', 'short_name', 'account_payable', 'require_job_number', 'currency', 'segment', 'market', 'estimated_headcount', 'is_technicolor', 'address') views.py def client_profile(request): all_profiles = ClientProfile.objects.filter(status='active') profile = None pid = request.GET.get('pid') client_profile_form = ClientProfileForm() if pid: profile = ClientProfile.objects.get(id=pid) client_profile_form = ClientProfileForm(instance=profile) if request.method == 'POST': client_profile_form = ClientProfileForm(request.POST, instance=profile) if client_profile_form.is_valid(): profile = client_profile_form.save() profile.csv_mapping = profile.full_name profile.save() if profile: for task_type in TaskType.objects.all(): if not profile.task_costs.filter(task_type=task_type): task_cost = TaskCost(task_type=task_type) task_cost.save() profile.task_costs.add(task_cost) return render(request, "prod/client_profile.html", {'all_profiles': all_profiles, 'profile': profile, 'client_profile_form': client_profile_form}) **HTML** <div class="content"> <form id='add_new_client_form' method="post" action=""> {% csrf_token %} <table class="table"> <tbody> {{ client_profile_form.as_table }} </tbody> <tfoot> <tr> <td></td> <td> <button class="lock" type="button" onclick="unlock(this, '#add_new_client_form')">Unlock </button> <button type="submit">SAVE</button> </td> </tr> </tfoot> </table> </form> </div> -
Asking permission to post and tag friend using graph API and Django
I have tried an application where I have shared the post with my application output and have tagged friends. The Facebook had blocked me saying that the application is violating the facebook policies. I guess it is because I have not asked person before posting and tagging the friends. Here is the code of what I have tried: def share(request): access_token = SocialToken.objects.get(account__user=request.user, account__provider='facebook') message = request.POST.get('message') params = { "access_token": access_token.token, "fields": "taggable_friends.limit(5){id}" } friends = json.loads(requests.get('https://graph.facebook.com/v2.10/me', params=params).text) friend_id = ','.join([id1['id'] for id1 in friends['taggable_friends']['data']]) # print friend_id params = { "access_token": access_token.token, "message": message, "place": "post", "tags": friend_id } requests.post('https://graph.facebook.com/v2.10/me/feed', params=params) return HttpResponse(json.dumps({'status': 200}), content_type="application/json") I want to know what improvement is required in my code so that it will ask for the permissions and then post on the users wall with tagged friends. Kindly, help me in making improvements to my code. -
Django: Advanced Template Filters
Here's my problem, In view I have, object = Data.objects.all() In template, {% for obj in object %} Here I can print Data... But also I wants to print Game and Extras. Where Game to related to "Data" through foreign key & "Extras" is related to "Game" through foreign key. This is how I'm doing it, {% for abc in obj.game_set.all %} Here I can print ]Games related to Data.. but also I wants to print Extras. this is what i'm doing, {% for var in abc.extras_set.all %} {{ var }} {% endfor %} {% endfor %} {% endfor %} Everything is fine accept the fact that I wants to print out latest 2 games having latest extras. I can use distortreversed & then slice to get latest 2 games but that will simply print out the latest games not will not give the latest games having latest extras. SO, how can I do that? Is there a way to do this in view & then follow with for loop in template? -
django-notes replacement package or reimplement?
I am looking for a replacement for the dated and unmaintained django-notes package. Essentially, I need a way to associate an arbitrarily sized text blob to any Model within my django app. This would be much like the django-tagging or django-taggit apps do, except with one text field instead of many tags. I am fairly new to django and python and my time is limited at the moment. My options are: find an existing and maintained notes application look at existing tagging apps and adapt them to a notes application, using django contenttypes / GenericRelations update the existing app to current django standards Any advice on these options would be much appreciated! -
edxapp : migrate Migration getting failed
I'm struck with below issue from past few and require help very badly. I've installed a Native stack on fresh Ubuntu system in EC2 using https://openedx.atlassian.net/wiki/spaces/OpenOPS/pages/146440579/Native+Open+edX+Ubuntu+16.04+64+bit+Installation. During Installation, every time, installation got failed at [edxapp : migrate] step. I repeated installation many times and one time it worked without any issues. Now I'm trying to activate e commerce service using Native stack using : https://openedx.atlassian.net/wiki/spaces/OpenOPS/pages/110330276/How+to+Install+and+Start+the+E-Commerce+Service+in+Native+Installations , even now, my installation is getting failed at migrate step with below log: failed: [localhost] (item=lms) => {"changed": true, "cmd": ["/edx/bin/edxapp-migrate-lms"], "delta": "0:04:58.188980", "end": "2017-10-26 01:14:15.137864", "failed": true, "item": "lms", "rc": 1, "start": "2017-10-26 01:09:16.948884", "stderr": "2017-10-25 21:09:21,176 INFO 18199 [dd.dogapi] dog_stats_api.py:66 - Initializing dog api to use statsd: localhost, 8125\nTraceback (most recent call last):\n File \"manage.py\", line 116, in <module>\n execute_from_command_line([sys.argv[0]] + django_args)\n File \"/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/__init__.py\", line 354, in execute_from_command_line\n utility.execute()\n File \"/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/__init__.py\", line 346, in execute\n self.fetch_command(subcommand).run_from_argv(self.argv)\n File \"/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py\", line 394, in run_from_argv\n Complete log : https://pastebin.com/1vCTvYg4 Can any help me as I'm struck at this point without a way to proceed. Thanks in advance. -
Django RestAuth Custom password reset link
I have tried the solutions I found for a similar question but none worked for me. I am using an angular frontend + DRF + Django Rest Auth, for the confirmation url, I was able to override it to point to my frontend by adding a custom adapter that looks liked this, class AccountAdapter(DefaultAccountAdapter): def send_mail(self, template_prefix, email, context): context['activate_url'] = settings.URL_FRONT + \ 'access/verify-email/' + context['key'] msg = self.render_mail(template_prefix, email, context) msg.send() with URL_FRONT = 'http://localhost:8080/app/#/' as the setting to direct the user to the client. My problem is implementing the same thing for the password reset url. I want it to start with the URL_FRONT setting and attached the tokens just liked what I have for the confirmation. What will be the best way to go about this? -
override : algorithm, verify(), encode() and safe_summary()
i keep having the same error for my override hashers.py . i customize my own password hasher . i still cannot save . hashers.py : class MyHoneywordHasher(PBKDF2PasswordHasher): algorithm = "honeyword_base9_tweak3_pbkdf2_sha256" iterations = PBKDF2PasswordHasher.iterations*3 def hash(self, password, salt, iterations=None): hash = pbkdf2(password, salt, iterations, digest=self.digest) return base64.b64encode(hash).decode('ascii').strip() def salt(self): salt = get_random_string() while Sweetwords.objects.filter(salt=salt).exists(): salt = get_random_string() return salt def verify(self, password, encoded): algorithm, iterations, salt, dummy=encoded.split('$',3) hashes = pickle.loads(Sweetwords.objects.get(salt=salt).sweetwords) hash = self.hash(password, salt, int(iterations)) if hash in hashes: return honeydetector.check_index(salt, hashes.index(hash)) return False def encode(self, password, salt, iterations=None): sweetwords = ['road,models,table'] honeywordtweak = 3 sweetwords_len = len(sweetwords) if iterations is None: iterations = self.iterations sweetwords.extend(honey.gen(password, base64, ["passfiles.txt"])) for i in range(0, 3): sweetwords.extend(honeywordtweak.tweak(password[i], 3)) random.shuffle(sweetwords) hashes = [] for swd in sweetwords: hashes.append(self.hash(swd, salt, iterations)) self.honeydetector.update_index(salt, sweetwords.index(password)) h = Sweetwords(salt=salt, sweetwords = pickle.dumps(hashes)) h.save() return "%s$%d$%s$%s" %(self.algorithm, iterations, salt, hashes[0]) i have an error in this line specificly . sweetwords.extend(honey.gen(password, base64, ["passfiles.txt"])) the error : Name error : name 'honey' is not defined . i tried to defined it like this : honey = open('honeywordHasher/honey.py', 'r') because it is a python file in the same directory as hashers.py . that is honeywordHasher. it is file that will generate honeyword my … -
Why doesn't Django's select_for_update raise an exception with unsupported backends?
The Django docs for select_for_update say Using select_for_update() on backends which do not support SELECT ... FOR UPDATE (such as SQLite) will have no effect. SELECT ... FOR UPDATE will not be added to the query, and an error isn’t raised if select_for_update() is used in autocommit mode. This strikes me as an odd and potentially dangerous decision, especially since select_for_update is used to lock rows. If I write code that uses select_for_update, I would rely on it actually being honored! If the DB backend doesn't support it, I would expect Django to either fall back to a safe-but-less-efficient alternative or, if one doesn't exist, to throw an exception of some kind. In this case it seems like Django could suddenly and silently reintroduce race conditions by just ignoring select_for_update where it's not supported (such as SQLite). My intuition says Django wouldn't do that and there must be some type of fallback or reason why it's not needed (perhaps complete database locking?) but I can't seem to find anything concrete in the docs to back up that theory. This is making me very leery of using select_for_update even though it would solve some current problems nicely. -
How user can upload video in django
I am creating web app in which I want user to upload video file. Can somebody help me with sample code or if you have any links please share. Thank you in advance. -
How can I convert the data to that type?
How can I convert this list data : [ { "home_page_second_module__name": "云主机", "home_page_second_module__home_page_first_module__name": "产品", "id": 1, "name": "云主机子1" }, { "home_page_second_module__name": "云主机", "home_page_second_module__home_page_first_module__name": "产品", "id": 4, "name": "云主机子4" }, { "home_page_second_module__name": "云硬盘", "home_page_second_module__home_page_first_module__name": "产品", "id": 2, "name": "云硬盘子2" }, { "home_page_second_module__name": "云硬盘", "home_page_second_module__home_page_first_module__name": "产品", "id": 3, "name": "云硬盘子3" } ] to this: [ {"name":"产品", "data":[ {"name":"云主机", "data":[{"name":"云主机子1", "data":{"id":1}}, {"name":"云主机子2", "data":{"id":2}}]}, {"name":"云硬盘", "data":[{"name":"云硬盘子1", "data":{"id":3}}, {"name":"云硬盘子2", "data":{"id":4}}]} ] } ] There should has a arithmetic method to do this, but I tried, do not get that. I only think of this below little things: home_page_second_module__name_list = [] home_page_second_module__home_page_first_module__name_list = [] id_list = [] name_list = [] for home_page_second_module__name,home_page_second_module__home_page_first_module__name,id,name in ori_list: if not (home_page_second_module__name_list.__contains__(home_page_second_module__name)): home_page_second_module__name_list.append(home_page_second_module__name) if not (home_page_second_module__home_page_first_module__name_list.__contains__(home_page_second_module__home_page_first_module__name_list)): home_page_second_module__home_page_first_module__name_list.append(home_page_second_module__home_page_first_module__name) But now I think this is very difficult to do that, and I think mine is wrong way to do that. Is there a convenient way to realize it? -
Can flask be used to develop single page applications?
Can I use flask to develop a single page application? What are the pros and cons of using Flask as opposed to django? -
How to edit UserCreationForm password advice?
When I create a registration form that inherits from UserCreationForm, the text "Your password can't be too similar to your other personal information. Your password must contain at least 8 characters. Your password can't be a commonly used password. Your password can't be entirely numeric." always appears under the password input fields and takes up quite a bit of space. Is there a way I can remove this? -
Django migrations changing choices value
A field has been added to one of my MySQL table previously: # -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2017-09-14 00:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', '0102_previous_migrations'), ] operations = [ migrations.AddField( model_name='my_client', name='my_team', field=models.CharField(choices=[('Unassigned', 'Unassigned'), ('ACT', 'ACT'), ('Korea', 'Korea'), ('National', 'National')], default='Unassigned', max_length=255, verbose_name='My Team'), ), ] So users have a choices of the above selection in my UI and will be saved into the table my_client: Unassigned ACT Korea National The changes have been deployed and now a beginner like me would like to change, i.e. remove Korea and add 2 new choices: NSW and SA How would I go about this? Do I need another migration or I will just need to change those choices in the models? I use this in my model now like this: class Client(MyAppModel): TEAM_CHOICES = ( ('Unassigned', 'Unassigned'), ('ACT', 'ACT'), ('Korea', 'Korea'), ('National', 'National'), ) DEFAULT_TEAM = 'Unassigned' my_team = models.CharField(verbose_name='MyTeam', null=False, max_length=255, choices=TEAM_CHOICES, default=DEFAULT_TEAM) -
Angular 4 with Django - Development Environment
I am building an Angular4 application using Django rest_framework as a backend. I like having the browser automatically refresh to display my changes when working on my angular application. So I spin up both the Django server via python manage.py runserver and the angular dev server by running npm start. I have setup my environment/environment.prod.ts and environment/environment.dev.ts files to point to the proper API source as necessary. After sorting out CORS I am running into a CSRF token issue. I have configured Django to use angular's default CSRF cookie/response header names of XSRF-TOKEN/X-XSRF-TOKEN respectively. All this is working just fine. Where the issue lies is that Angular does not automatically read the X-XSRF cookie or return the header. Ok, that's fine, I can write an interceptor to do that for me. And that would be OK - except that I cannot access the response headers in the interceptor... import {DOCUMENT, ɵparseCookieValue as parseCookieValue} from '@angular/common'; import {Inject, Injectable, InjectionToken, PLATFORM_ID} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import { HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpInterceptor, HttpXsrfTokenExtractor } from '@angular/common/http'; /** * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests. */ @Injectable() export class DevHttpXsrfInterceptor implements HttpInterceptor { constructor( private tokenService: … -
django product price tracker: getting the amount and date of the all time maximum and minimum prices
I'm trying to build a django app where I can track product prices over time. The app fetches new prices routinely, graphs them and shows the recent history of price changes. I'm checking the price once a day and saving that price plus the date timestamp to my models. models.py Class Product(models.Model): title = models.CharField(max_length=255) Class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date_seen = models.DateTimeField(auto_now_add=True) price = models.IntegerField(blank=True, null=True) Along with the current price of a product I'd also like to show the max and min over all the price data I've collected. I want to get the value and also the date it was at that value. So far I can get the value but I can't get the corresponding date. I'm using this: def price_hla(self): return Product.objects.filter(price__product=self).aggregate(high_price=Max('price__price'), low_price=Min('price__price'), avg_price=Avg('price___price')) Any advice? Thanks! -
Adding placeholder to django-taggit field - TaggableManager()
I have this model with a TaggableManager() field: class MyModel(models.Model): knowledge_topics = TaggableManager( verbose_name="Áreas de conocimiento", help_text=_("Una lista de temas separada por comas.") ) I want add placeholder to knowledge_topics field, then my form is: class MyModelForm(forms.ModelForm): title = "Detalles del anfitrión de estudios" knowledge_topics = forms.CharField(label='Áreas de conocimiento', widget=forms.TextInput(attrs={ 'placeholder': 'Una lista de temas separada por comas'})) class Meta: model = MyModel fields = ('knowledge_topics',) But when I go to my form, the placeholder does not works of a suited way: -
will django uwsgi request continue after incoming request closes the connection
I have a web service. Incoming http request goes through an oauth server, then haproxy, then a django/uwsgi. My API is to make a http call another server to get data, write to db, then return data to the original caller. Assume the call to another http server takes 90 sec but the oauth server cut the connection after 60 sec. Will the api continues the effort and eventual finishes writing the data into db? or the api will end immediately after the incoming request closes the connection? Thanks. -
Filtering results of multiple models under one API Endpoint with django-rest-framework
I am using DRF to generate API for my django app. I am using the ViewSet class and exposing API endpoints for most of my models at their own path. I want to allow viewing of my Endpoint and TLSCertificate models at an /assets/ path. As they are both children of an Organisation entity, I want to allow the results to be filtered Organisation. So far I have: serializers.py class AssetSerializer(serializers.Serializer): endpoints = EndpointSerializer(many=True) certificates = TLSCertificateSerializer(many=True) views.py class AssetFilterSet(filters.FilterSet): organisation = filters.ModelChoiceFilter( name='organisation', queryset=Organisation.objects.all()) project = filters.ModelChoiceFilter( name='project', queryset=Project.objects.all()) class Meta: model = Endpoint fields = ['organisation', 'project'] # the object type to be passed into the AssetSerializer Asset = namedtuple('Asset', ('endpoints', 'certificates')) class AssetViewSet(CacheResponseAndETAGMixin, viewsets.ViewSet): """ A simple ViewSet for listing the Endpoints and Certificates in the Asset list. Adapted from https://stackoverflow.com/questions/44978045/serialize-multiple-models-and-send-all-in-one-json-response-django-rest-framewor """ # TODO filtering not functional yet filter_class = AssetFilterSet filter_fields = ('organisation', 'project',) queryset = Endpoint.objects.all() def list(self, request): assets = Asset( endpoints=Endpoint.objects.all(), certificates=TLSCertificate.objects.all(), ) serializer = AssetSerializer(assets, context={'request': request}) return Response(serializer.data) This works in returning the objects but does not allow for filtering to take place. I would appreciate any guidance in how to enable the filtering in this situation?