Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want develop a web application for AWS ec2 instance launch and termination using boto3,django.Please suggest how can i setup
I want develop a web application for AWS ec2 instance launch and termination(similar like AWS console) using boto3,django.Please suggest how can i setup -
how python import datetime?
Recently we use python/Django with django-tastypie to write a website prototype. And we find a strange behavior of Python importing: import datetime import another_module # another_module.AnotherBaseResource extends tastypie.resources.ModelResource class SomeResource(another_module.AnotherBaseResource): class meta: name = 'some' def another_api(self, request, time_string, **kwargs): datetime.datetime.strptime(time_string, "%Y") def customized_api(self, request, date_string, **kwargs): datetime.date.strptime(date_string, "%Y") When customized_api is invoked, it always report error of AttributeError: 'method_descriptor' object has no attribute 'strptime'; However, when another_api is invoked, it works!! We can confirm that we DO NOT have any line of something like from datetime import datetime in the same Python file. And if we add one line to customized_api like datetime = __import__('datetime'), there will be no error ever. Can someone explain what happens, especially about the Python importing system? Is it possible that Python can pass import symbol directly in some closure? -
Django Project can't force Google Appengine to redirect to https
Using sample Django Projects and my Django Rest Framework project, I can deploy to appengine without issue. I can access the site via both https://myappnamehere.appspot.com and the http:// version as well. However, I'm seemingly unable to force it to only allow HTTPS. Attempt 1: In my Django settings, I try to set : SECURE_SSL_REDIRECT = True This ends with my project no longer showing up on appengine, with AppEngine reporting that I should try again in 30 minutes Attempt 2: In app.yaml, I follow the advice from https://groups.google.com/forum/#!msg/google-appengine/11k3L18Ynh0/HYG7gp4Ph0YJ and other stack overflow threads by adding this: handlers: - url: /* script: myapplication.wsgi.application This also ended up with the routing seemingly messed up, and all my URLs no longer routed thru the django router as expected. What is inside the wsgi: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapplication.settings.settings") application = get_wsgi_application() -
Add parent field in django admin forms
Here are my two models: class Provider(models.Model): ''' @note PT has no prefix but multiple accounts AG has prefixes but only one account ''' name = models.CharField(max_length=75, null=True, blank=True) code = models.CharField(max_length=15) provider_parent = models.ForeignKey('self', null=True, blank=True) accounts = models.ManyToManyField('Account', blank=True) data_types = models.ManyToManyField('DataType', blank=True, through='ProviderDataType') class Account(models.Model): name = models.CharField(max_length=75, unique=True) prefixes = models.ManyToManyField('AccountPrefix', blank=True) Here is my admin.py class ProviderAdmin(admin.ModelAdmin): list_display = ('code', '__unicode__') class AccountAdmin(admin.ModelAdmin): list_display = ('__unicode__') admin.site.register(Provider, ProviderAdmin) admin.site.register(Account, AccountAdmin) I was wondering if it is possible to have a selection of the parent provider when I try to add or update my account model and upon saving it. The Parent model has already set the account on its manytomany field -
How to define custom location for Django Migrations
How do you define where Django puts database migrations? I've modified some third-party models, and now when I run manage.py makemigrations for my own models, Django tries to create migrations for these third-party models as well. However, it puts the migrations in the package's folder within my virtual environment, instead of in my application code. How do I configure Django to place custom migrations of third-party models in a local folder? South used to support this with the settings map SOUTH_MIGRATION_MODULES, but I can't find any similar feature in Django 1.10. -
Django Celery tasks run twice
My project directory structure is as follows: rss_reader - reader - __init__.py - models.py - views.py - ... - rss_reader - __init__.py - settings.py - urls.py - wsgi.py - rss_contents - __init__.py - celery.py - tasks.py - config.py - ... tasks.py from __future__ import absolute_import from rss_contents.celery import app @app.task def processArticle(): print "100" celery.py from __future__ import absolute_import from celery import Celery app = Celery('rss_contents', include=['rss_contents.tasks']) app.config_from_object('rss_contents.config') config.py from __future__ import absolute_import CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/5' BROKER_URL = 'redis://127.0.0.1:6379/6' reader > __init__.py from rss_contents import tasks tasks.processArticle.delay() My steps are as follows: celery -A rss_contents worker -l info The console displays: [2017-01-11 10:34:33,829: INFO/MainProcess] Connected to redis://127.0.0.1:6379/6 [2017-01-11 10:34:33,855: INFO/MainProcess] mingle: searching for neighbors [2017-01-11 10:34:34,861: INFO/MainProcess] mingle: all alone [2017-01-11 10:34:34,892: WARNING/MainProcess] celery@DESKTOP-6KAT7MF ready. Run server, Starting development server at http://127.0.0.1:8000/ But the celery console shows that the task was run twice: [2017-01-11 10:41:20,910: INFO/MainProcess] Received task: rss_contents.tasks.processArticle[aa355c77-4ee8-4208-9e8c-915b110c7bbd] [2017-01-11 10:41:20,911: WARNING/Worker-1] 100 [2017-01-11 10:41:20,917: INFO/MainProcess] Task rss_contents.tasks.processArticle[aa355c77-4ee8-4208-9e8c-915b110c7bbd] succeeded in 0.00600004196167s: None [2017-01-11 10:41:22,430: INFO/MainProcess] Received task: rss_contents.tasks.processArticle[d92a151c-f0f9-4e8f-921a-fff2c1eb64c6] [2017-01-11 10:41:22,431: WARNING/Worker-1] 100 [2017-01-11 10:41:22,447: INFO/MainProcess] Task rss_contents.tasks.processArticle[d92a151c-f0f9-4e8f-921a-fff2c1eb64c6] succeeded in 0.0160000324249s: None Why is it running twice? How can I do it once? Thanks in advance. -
Use Django Logic to Add CSS Class based on url with slug
I am pretty new to Django and I hope I will be able formulate my question correctly so please bare with me. What I have right now: A simple personal website with a blog section. When I go to different list items from the navbar, it adds an "activated" class if the li is active. The problem occurs with my blog section. What I am trying to achieve: Add the "activated" class when I am in the blog sections and blog posts so the link would be activated. I use slug for my posts urls. What I have right now and it doesn't work: template.html <li class="{% if request.resolver_match.url_name == "index" %}activate{% endif %}"><a href='/'>Home</a></li> <li class="{% if request.resolver_match.url_name == "blog" %}activate{% endif %}"><a href='/blog/'>Blog</a></li> <li class="{% if request.resolver_match.url_name == "photohraphy" %}activate{% endif %}"><a href='/photography/'>Photography</a></li> models.py from django.db import models from django.core.urlresolvers import reverse class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) body = models.TextField() date = models.DateTimeField() updated = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('blog:post_detail', args=[self.slug]) def __str__(self): return self.title urls.py from django.db import models from django.core.urlresolvers import reverse class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) body = models.TextField() date = models.DateTimeField() updated = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('blog:post_detail', … -
Django Invalid http_host header disallowed host
I am getting the Invalid HTTP_HOST header: 'example.com'. You may need to add u'example.com' to ALLOWED_HOSTS exception when simply attempting to access 'example.com' Of course I have added both 'example.com' and u'example.com' to ALLOWED_HOST together and separately as well as added the ip address. Side note: I can access my site by typing in the IP address If it helps to know, I am using digital ocean one click django app for hosting. -
Using a html form from another project with Django
I am trying to use a html form from the internet with Django. However, after watching crazy amount of videos on youtube and reading through https://docs.djangoproject.com/en/1.10/topics/forms/ , I can't manage to make it work. When I click the submit button, Chrome tells me the "The form has submitted", but nothing else happens. It should log the user in and redirects to the index page. registration_form.html <div class="panel panel-info mt10 br-n bg-gradient-1 mw500 mauto"> <form id="contact" method="post" action="/"> {% csrf_token %} <div class="panel-body text-center p50 text-center"> <div class="section"> <p class="text-uppercase text-white ls100 fw700">Username</p> <label for="username" class="field prepend-icon"> <input id="username" type="text" name="username" placeholder="Enter username" class="gui-input"> </label> </div> <div class="section"> <p class="text-uppercase text-white ls100 fw700">Password</p> <label for="password" class="field prepend-icon"> <input id="password" type="password" name="password" placeholder="Enter password" class="gui-input"> </label> </div> <div class="panel-footer clearfix p10 ph15"> <button type="submit" class="button btn-primary mr10 pull-right text-uppercase text-white ls100 fw700">Sign In</button> <label class="switch ib switch-primary pull-left input-align mt10"> <input id="remember" type="checkbox" name="remember" checked=""> <label for="remember" data-on="YES" data-off="NO"></label> <span>Remember me</span> </label> </div> <div class="section text-left pt20 pb10"><a href="#">Forget password?</a> <p><span class="text-white">Haven't yet registration? <a href="#">Sign up here</a></span></p> </div> <div class="section row"> <div class="col-md-6"><a href="#" class="fw700 ls100 text-white text-uppercase">Facebook</a></div> <div class="col-md-6"><a href="#" class="fw700 ls100 text-white text-uppercase">Google +</a></div> </div> </div> </form> </div> views.py … -
Django + Heroku: Images Work Until Next Push
I have a basic learning blog app that I am running into an issue with: a "blog post" with an image uploaded via the app's admin form works fine, until I push another version via heroku. Then where the image was displays the broken img icon, and the app cannot find the image even though the picture target when I look at the picture address is the same. I feel like I'm missing something fundamentally important about something - hence why I can't seem to fix this by google. Does anyone know why I'm tripping up here, and am I even approaching this right? I'm using Django + Gunicorn + dj-static to serve the static files. Here is the model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() picture = models.ImageField(upload_to='blog/static/blog/images') section = models.ForeignKey('Section') posted = models.DateTimeField(auto_now_add=True) posted_by = models.TextField() tags = models.ManyToManyField('Tag') def __str__(self): return self.title the view: def detail(request, post_id): post = Post.objects.get(id=post_id) picture = post.picture context = {'post': post, 'picture': picture} return render(request, 'blog/detail.html', context) snip containing the image html: <hr> <img src="{{ picture.url }}"> <hr> settings.py dealing with static files: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' BOOTSTRAP3 = … -
What is the most decent way to work with JavaScripts in Django projects?
Recently there have been a lot of changes in the frontend development, like Babel JavaScript compiler, and build systems like Browserify, Grunt, Gulp, Webpack, and others. Besides that, django-pipeline is also updated for the Django 1.10. What is the most modern and promising way to deal with JavaScripts in a Django project in 2017? -
Create django user and sign them in
I am using ajax to post register data to a view called signup. After I register the user, I want a way to sign them in and redirect to the home page. At first I couldn't get the redirect to work (probably due to ajax) and then I got an error File "/home/sam/Workspace/insight_v2/apps/welcome/views.py", line 29, in signup login(request, user) request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) AttributeError: 'AnonymousUser' object has no attribute '_meta' This is my views.py file: def signup(request): if request.POST: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] user = User.objects.create_user(username, email, password) user.is_active = False user.set_password(password) user.save() user = authenticate(username=username, password=password) login(request, user) return redirect('/') -
Passing csrf token through $.ajax() data not working
So I'm trying to make ajax commenting in my django app, and I've encountered the: Forbidden (CSRF token missing or incorrect.): /app/437/ error. After reading through many SO answers it seems the most used and simple method to deal with this error is by passing through the csrf token through $.ajax() data like this: $('.comment_form').on('submit', function(e) { e.preventDefault(); var url = window.location.href.split('?')[0]; console.log(url) $.ajax({ type: 'POST', url: url, data: { text: $('.comment_text').val(), 'csrfmiddlewaretoken': '{{csrf_token}}', }, success: function() { $('.comment_div').append("<div class='comment_div'><h3>username</h3><p>" + text + "</p></div>"); console.log(text); } }) }); Here's my template if you're curious: {% block comments %} {% load widget_tweaks %} <div class="commentsContainer"> <form action="" class="comment_form">{{csrf_token}} {{ comment.comment_text|add_class:"comment_text" }} <!-- this is a textarea--> <input type="submit" value="Comment" class="comment_submit"> </form> <div class="comment_div"> <h3>username1</h3> <p>Some text</p> </div> </div> {% endblock %} Any idea how I can fix this? -
Django, Celery, SQS on Elastic Beanstalk Database Connection refused error
I hosted a django app with celery on elastic beanstalk using sqs as broker. The answer to this question helped me to achieve this. how to run a celery worker with django app... when I test my app and observe the output by the celeryworker on the server I can see that tasks are received and complete: [2017-01-10 17:46:25,597: INFO/MainProcess] celery@ip-172-31-25-80 ready. [2017-01-10 17:46:28,469: INFO/MainProcess] Received task: sum_two_numbers[88589871-579a-4165-8de9-3765fae68ddd] [2017-01-10 17:46:28,471: INFO/PoolWorker-1] Task sum_two_numbers[88589871-579a-4165-8de9-3765fae68ddd] succeeded in 0.000839297004859s: 'It works!' But it only works when I test tasks that are not hitting the database. Tasks like the following, who try to change DB records result in an error. @task(name="sum_two_numbers") def test(x): test = Test.objects.get(name="test") test.count+=1 test.save() return "Created bill baby" error-log: OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The database is running. Du I have to set permissions somewhere? -
Django-Simple-Captcha add CSS
I read all the Documentation about Django-simple-captcha and I just find this sentence: (Used to default to: u'%(image)s %(hidden_field)s %(text_field)s') But it's don't do what I want... I don't want to change all the patern of the captcha, I just need to change this one maybe with add attrs={} if is possible like a the others fields. I have something like this Captcha : img + textfield in a render HTML. And if it's possible i want something like the documentation: django-simple-captcha.readthedocs.io/en/latest/_images/random_chars.png I use in forms.py: class RegisterForm(forms.ModelForm): ... captcha = CaptchaField(label='Are you an human? ') And in the view.py: <div class="fieldWrapper input-field col-xs-12"> <i class="material-icons">person_pin</i> <label for="id_captcha">{{ form.captcha.label }}</label> {{ form.captcha }} </div> I try to a find the possibility to use the argument image and text_field like attribute in my forms.py: captcha = CaptchaField(label='Are you an human? ', widget=captcha.image(attrs={'class':'white-text'}), widget=captcha.text_field(attrs={'class':'white-text'})) But i'm not sure I can use that it like this... Do you have already see this problem ? I try to find a solution but without success... -
Django Custom Client Login Page not Authenticating
New to Django and came from Laravel where it was much easier to setup login and authentication. That is to say I am struggling getting a simple login page to work properly and have spent several nights working on it using SO, Django docs, and various tutorials. The Django documentation doesn't seem to be organized well for someone just trying to get the basics of login page, kind of overwhelming, and most of the SO answers are old that I have come across. These two tutorials I have used and neither gets me what I am after: Right way of adding user authentication to Django How to Use Django's Built-in Login System Using Python 3.5.2, Django 1.1, and PostgreSQL 9.6. In my setup, localhost:8000 is the login page. The user needs to login before they can view anything. I also have apps /home, /results, etc. but right now I am only working with /home. If they try to go to localhost:8000/home they will be routed to login doing this currently brings them to http://localhost:8000/?next=/home/. So that much is working good. When I enter credentials, it just keeps sending me to the login screen. Going to localhost:8000 or /home just does … -
Django: Warning of unapplied migrations after upgrading to 1.9.4
A few months ago I upgraded to Django 1.9.4, and ever since then I've been getting the following warning whenever I run my app: You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. Indeed, running python manage.py showmigrations --list | grep -v '[X]' to get a list of any unapplied migrations yields the following output: admin [ ] 0002_logentry_remove_auto_add auth [ ] 0007_alter_validators_add_error_messages I traced these to the migration folders for the Django 1.9.4 admin and contrib/auth packages, respectively. I have put off attempting to fix this but now I would really like to, as the warning is getting quite annoying. But what is the fix? I just came across the MIGRATION_MODULES entry for settings.py - is that the solution? -
related_name changed after 1.6
I'm upgrading from 1.6 to 1.9. My project includes code derived from this sample AuditTrail: https://code.djangoproject.com/wiki/AuditTrail Essentially, this AuditTrail allows to create an Audit model on-the-fly to record any changes to an audit table. Part of the code needs to make sure to avoid clashes between related_name. This is done as follows, and works fine as of 1.6. if isinstance(field, models.ForeignKey): rel = copy.copy(field.rel) rel.related_name = '_audit_' + field.related_query_name() attrs[field.name].remote_field = rel For some reason, after upgrading, django fails with SystemCheckError on all of these, with a traceback looking like: SystemCheckError: System check identified some issues: ERRORS: ?: debug_toolbar.middleware.DebugToolbarMiddleware is missing from MIDDLEWARE_CLASSES. HINT: Add debug_toolbar.middleware.DebugToolbarMiddleware to MIDDLEWARE_CLASSES. email_reporting.ReportAudit.team: (fields.E304) Reverse accessor for 'ReportAudit.team' clashes with reverse accessor for 'Report.team'. HINT: Add or change a related_name argument to the definition for 'ReportAudit.team' or 'Report.team'. email_reporting.ReportAudit.team: (fields.E305) Reverse query name for 'ReportAudit.team' clashes with reverse query name for 'Report.team'. HINT: Add or change a related_name argument to the definition for 'ReportAudit.team' or 'Report.team'. Any ideas how to fix it? I can't find any changes to related_name that may be the culprit. -
Django - Generate shortest random slug
How i can generate random slug consisting of the smallest amount of characters. i try with this. import random import string u_id = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) and model class Articles(models.Model): slug = models.CharField(max_length=6) How i can do this in model? Generate slug, check if is available and set. I want create short slugs lenght 1 to 6 chars, best for me is starting from 1 letter slugs. -
Set-Cookie response header not working using Angular 2 + django-rest-framework
I am developing an Angular 2 app that is using django-rest-framework a backend. I am doing my tests using a development server (ng serve from angular-cli) and another one for django (default from manage.py). Both server are accessible from 127.0.0.1 but on different ports. My authentication system is based on cookie served by django-rest-framework. Everything works fine when using the views from django-rest-framework. When I try to login from angular 2, I receive a valid response with a Set-Cookie Header. The problem is that the cookie is never set i the browser (tested in chrome and firefox). Is this a CORS problem? I have set corsheader app installed with CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True -
Register User with custom fields in Djoser and Rest Framework
I'm trying to use the "register" endpoint from Djoser. It works properly, but I need more fields than just "username", "email" and "password". I've seen this question and indeed I can see the fields I wanted (in the browsable API). But when I try to post it, I get this error ImproperlyConfigured at /account/register/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. And I don't have idea what's going wrong. My models.py looks so: from django.db import models class User(models.Model): created = models.DateTimeField(auto_now_add=True) email = models.CharField(max_length=100, blank=False) name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) birthday = models.CharField(max_length=15, blank=False) password = models.CharField(max_length=100, blank=False) class Meta: ordering = ('created',) the serializers.py from rest_framework import serializers from users.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'id', 'email', 'name', 'last_name', 'birthday', 'password') my views.py from users.models import User from users.serializers import UserSerializer from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer and in the settings.py I added: DJOSER = { ... 'SERIALIZERS': { 'user_registration': 'users.serializers.UserSerializer', }, } Does someone have an … -
Django 1.10 TemplateSyntaxError. Did you forget to register or load this tag?
I'm trying to load a css file from my static folder, and the "TemplateSyntaxError" is showing in this line: Here is the code that I'm using to load a template <!DOCTYPE html> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <title>{% block title %} Portuaria {% endblock %}</title> And this is the error that I'm getting Am I trying to load the template in a wrong way? I'm using django v 1.10 -
DJango Persist session across 2 forms
I am trying to pass data from one form to another. Its a multi step form. For this I am using request.session object. However when after Post from the first form when I reach second form the session data is None and when I printed the session key it seems that it has changed. I am using default db based session. My overall aim to pass data from form1 to form2. If there are any other suggestion for doing that I am willing to try them out as well. Reference Docs - https://docs.djangoproject.com/en/dev/topics/http/sessions/ http://gregblogs.com/dealing-with-forms-a-beginners-look-into-django-forms-and-sessions/ Settings.py INSTALLED_APPS = ( 'django.contrib.sessions', ... ) MIDDLEWARE_CLASSES = [ 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ] Views.py def step1(request): form = UploadPickFileForm(request.POST) # Create form instance print "Session{}".format(request.session._get_session_key()) if request.method == 'POST': initial = {'text':request.session.get('text', None)} form = UploadPickFileForm(request.POST, request.FILES, initial = initial) if form.is_valid(): action = form.cleaned_data.get('action') uploaded_file = form.cleaned_data.get('file') extractor = get_upload_extractor_for_source(form.cleaned_data.get('source')) print "Action{}".format(action) if action == INGEST_ACTION: uploaded_file = form.cleaned_data.get('file') try: ingestable_upload = extractor.get_ingestable_upload(uploaded_file) context = {'ingestable_upload': ingestable_upload} except ParseError as e: return self.show_error(e) request.session['text'] = form.cleaned_data.get('action') tt = request.session.get('text', None) request.session.modified = True # just to force session save print "Session data{}".format(tt) return HttpResponseRedirect(urlresolvers.reverse('step2')) else: form = UploadPickFileForm() else: print "form is INVALID {}".format(form.errors) return … -
Django - make admin fields invisible to some users
TL;DR I'd like to be able to disable certain models per-user in /admin view. Specifically: I'm looking to make admin models invisible to some staff users, so that they can have a sort of customized dashboard. There's all sorts of fields that change how to present, search, query, etc. models based on whatever you want, but I can't find anything to allow me to determine whether or not to even show models on the /admin page without resorting to blacklisting individual permissions (of which there are hundreds), and I'd like to be able to make some models only available to superusers and not staff. Any thoughts? Thanks! -
Django form field do not save
I have some code, which allows users to create a 'transaction' object after filling a form and save it to a database. All fields entered in the form are being saved correctly except for 'Wallet' field, which remains empty after saving. What should I look for to solve it? Here is my code: MODEL : simplified class Transaction(models.Model): name = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) type = models.CharField(choices=TRANSACTION_CHOICES, max_length=10) user = models.ForeignKey(User, related_name='transactions') wallet = models.ForeignKey(Wallet, null=True, blank=True, related_name='transactions') VIEW: @login_required def transaction_create(request): current_user = request.user if request.method == 'POST': Transaction.wallet = Wallet.objects.filter(user=current_user) transaction_create_form = TransactionCreateForm(current_user, request.POST) if transaction_create_form.is_valid(): new_transaction = transaction_create_form.save(commit=False) new_transaction.user = request.user new_transaction.save() return render(request, 'transaction/done.html') else: transaction_create_form = TransactionCreateForm(user=current_user) return render(request, 'transaction/create.html', {'transaction_form': transaction_create_form}) FORMS: class TransactionCreateForm(forms.ModelForm): field_order = ['name', 'type', 'wallet', 'category', 'date', 'amount', 'notes', ] class Meta: model = Transaction fields = ('name', 'type', 'wallet', 'category', 'date', 'amount', 'notes',) def __init__(self, user, *args, **kwargs): super(TransactionCreateForm, self).__init__(*args, **kwargs) self.fields['wallet'] = forms.ChoiceField( choices=[(wallet.id, str(wallet)) for wallet in Wallet.objects.filter(user=user)])