Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djstripe (django stripe) - should I create local or remote customers first?
When I receive my stripe token after a valid form: what data should I be using to create my local customer model? Many fields returned from the stripe create customer JSON response are incompatible with the local dj.stripe Customer model. Am I supposed to be deleting and changing fields from the stripe JSON response to shoehorn it into my local model or am I missing the advantage of using djstripe? -
Integrate Django with VueJs
How to Integrate Django with VueJs? What is the Standard way to integrate Django and VueJs? can anyone provide project structure and reference to learn -
Deploy django in ec2 instance with nginx and uwsgi which only allow HTTPS connections
I tried many tutorials for the same but none of them worked for me. I am not able to connect Django with uwsgi. -
Orderdict is not defined in django template when using in js
I have implemented nested serailizer via djangorestframework. I am sending the variable as a context in my django template. I struck with a problem while using template variable inside <script> tag it is showing an error that Error: Orderdict is not defined var data = {{ data.companies|safe }}; what i get after rendering was [OrderedDict([('id', 4), ('name', 'axis'), ('acronym', 'axis'), ('growth', [OrderedDict([('datetime', '2007-11-30T00:00:00+05:30'), ('_close', 224.199997)]), OrderedDict([('datetime', '2007-12-31T00:00:00+05:30'), ('_close', 169.125)]), OrderedDict([('datetime', '2008-01-31T00:00:00+05:30'), ('_close', 160.024994)]), OrderedDict([('datetime', '2008-02-29T00:00:00+05:30'), ('_close', 123.199997)]), OrderedDict([('datetime', '2008-03-31T00:00:00+05:30'), ('_close', 155.300003)]), OrderedDict([('datetime', '2008-04-30T00:00:00+05:30'), ('_close', 140.300003)]), OrderedDict([('datetime', '2008-05-31T00:00:00+05:30'), ('_close', 112.074997)]), OrderedDict([('datetime', '2008-06-30T00:00:00+05:30'), ('_close', 99.224998)]),.....] So as Orderdict is not a valid thing in JS but it is rendering as such. How can i solve this? I have also tried escapejs filter but no help. -
How to configure .htaccess Django deployment
I am trying to deploy my first Django application (on A2 Hosting). Unfortunately, I don't have access to my Apache2 conf file (and/or httpd), I can only modify the .htaccess file than you can see below. After many try, I think it is the Apache server who can't load the wsgi.py, because I add a logs file, create when the wsgi.py file is called and it wasn`t create (I tried manually and the logs file are correctly created). Right now, all I am trying to do its to print the Django "Wello World", because I thought, if I can't pass through this basic step, how can I deploy my "real" application ... Finally, I am running with Django 1.11.6 and Python 3.5.4 on a virtual env. .htaccess DirectoryIndex /home/hairduseres/public_html/myapp/myapp/myapp/wsgi.py WSGIScriptAlias / /home/user/public_html/myapp/myapp/myapp/wsgi.py WSGIPythonHome /home/user/virtualenv/myapp/3.5 WSGIPythonPath /home/user/public_html/myapp <Directory /home/user/public_html/myapp/myapp/myapp/> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/user/public_html/myapp" PassengerBaseURI "/myapp" PassengerPython "/home/user/virtualenv/myapp/3.5/bin/python3.5" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END wsgi.py """ WSGI config for myapp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi … -
Changing django form from POST to GET
I have my view with form where I use POST and I want to switch my form method from POST to Get. @login_required def payment_range_list(request): #import pdb; pdb.set_trace() title = 'payment list' #import pdb; pdb.set_trace() if request.method == "POST": form = PaymentRangeForm(request.POST) #import pdb; pdb.set_trace() if form.is_valid(): start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] building = form.cleaned_data['building'] if building == '': payment_list = LeasePayment.objects.filter(payment_date__range=[start_date, end_date] ) building = 0 else: payment_list = LeasePayment.objects.filter(payment_date__range=[start_date, end_date],lease__unit__building = building ) total = payment_list.aggregate(Sum('amount')) else: payment_list = None payment_page = None start_date = None end_date = None building = None total = None form = PaymentRangeForm() else: payment_list = None payment_page = None start_date = None end_date = None building = None total = None form = PaymentRangeForm() return render(request,'payment/payment_range.html', {'form':form, 'payment': payment_list,'page_payment':payment_page, 'start_date':start_date, 'end_date':end_date, 'building':building, 'total':total, }) and I have my form class PaymentRangeForm(forms.Form): start_date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'} )) end_date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'} )) building = forms.ChoiceField(choices=BLANK_CHOICE_DASH + list(Building.objects.values_list('id', 'name')), required=False) I want to switch my form method from POST to Get . What should I do? I tried simply changing POST to GET in my view but it is not working. -
Django - Update a Model every couple of minutes
I am building an app, where I need to fetch some data from an API and update all the models with that data every few minutes. What would be a clean way to accomplish something like this? -
Facebook Social Auth Login: Can't Load URL: The domain of this URL isn't included in the app's domains
I am developing a web application using Django and python-social-auth. I want users to login with Facebook. I have this in my python settings: SOCIAL_AUTH_FACEBOOK_KEY = '...' SOCIAL_AUTH_FACEBOOK_SECRET = '...' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] When my users enter the facebook page where they should provide credentials they see an error like this: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. In Facebook for Developers dashboard I have added "Facebook Login" product and added redirect url: http://localhost:8000/complete/facebook/ In settings, Website Site URL is set to: http://localhost:8000/ and App Domains is set to localhost. What am I doing wrong? BTW this is the url that my users see when the facebook page opens: https://www.facebook.com/v2.9/dialog/oauth?scope=email&state=HSfkstGUR5028DMhUzfWOSgo6fpPx29E&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcomplete%2Ffacebook%2F%3Fredirect_state%3DHSfkstGUR5028DMhUzfWOSgo6fpPx29E&client_id=...&return_scopes=true -
Django unit tests fail when ran as a whole and there is GET call to the API
I am facing an issue when I run the tests of my django app with the command python manage.py test app_name OR python manage.py test All the test cases where I am fetching some data by calling the GET API, they seem to fail because there is no data in the response in spite of there being in the test data. The structure which I have followed in my test suite is there is a base class of django rest framework's APITestCase and a set_up method which creates test objects of different models used in the APIs and I inherit this class in my app's test_views class for any particular API such as class BaseTest(APITestCase): def set_up(self): ''' create the test objects which can be accessed by the main test class. ''' self.person1= Person.objects.create(.......) class PipelineViewTestCase(BaseTest): def setUp(self): self.set_up() def test_get_pipeline_sales_person_no_closed_lost_deals(self): ''' To test if the logged in user is a person from the Sales group,then they shouldn't see closed deals and they should see only their deals :return:QuerySet-> All the non closed lost deals of the sales person ''' #Person.objects.get.reset_mock() url='/crmapi/pipeline/' self.client.login(username='testusername3',password='testpassword3') response=self.client.get(url,{'person_id':self.person3.id}) self.assertEqual(response.status_code, status.HTTP_200_OK) #excludes closed lost deal self.assertFalse(self.is_closed_deal_exist(response.data)) self.assertTrue(self.is_same_person_deal_exist(response.data,'testusername3')) self.assertEqual(len(response.data),6) So whenever I run the test as … -
Django route returns AnonymousUser error even permission to route stays IsAuthenticated
User extends AbstractBaseUser. UserViewSet extends ModelViewSet. my route @list_route(methods=['patch'], permission_classes=[IsAuthenticated]) But after sending request to route, returns error 'AnonymousUser' object has no attribute '_meta'. How anonymousUser can use this route, if permissions stays IsAuthenticated; -
how to redirect the user to user-specific url after login django?
I am new in django. I am trying to create a user specific page where after login the user land to somthing like mydomain.com/dashboard/. I am trying to implement the following solution Django - after login, redirect user to his custom page --> mysite.com/username Can anyone provide more detail like how to create models , call back , views and login page thanks -
Cannot add ManyToManyField objects in Django
I am unable to add ManyToManyField objects in Django 1.11 on Python 3.6 even after following the doc models.py class Label(models.Model): ... name = models.CharField(blank=False, max_length=100) class Template(models.Model): ... labels = models.ManyToManyField(Label, blank=True, related_name="labels") And then >>> from content.models import Label, Template >>> l1 = Label.objects.get_or_create(name='one') # saves in db >>> l2 = Label.objects.get_or_create(name='two') # saves in db >>> t1 = Template.objects.get(pk=1) # loads existing >>> t1.labels.set([l1,l2]) # fails throws this error Traceback (most recent call last): File "<console>", line 1, in <module> File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1007, in set self.add(*new_objs) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add self._add_items(self.source_field_name, self.target_field_name, *objs) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1083, in _add_items '%s__in' % target_field_name: new_ids, File "/path/env3tt/lib/python3.6/site-packages/django/db/models/query.py", line 784, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1250, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1276, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1206, in build_filter condition = lookup_class(lhs, value) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__ self.rhs = self.get_prep_lookup() File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in get_prep_lookup self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in <listcomp> self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value return int(value) TypeError: … -
How to validate and provide cleaned_data for a dynamically introduced field in forms.modelform?
I would like to make it clear. I am aware inlineformset would solve this however for another purpose I was wondering how this would be done. Here are some models.py class Address(models.Model): address_0 = models.CharField("address", max_length=64) address_1 = models.CharField("address cont'd", max_length=64, blank=True) city = models.CharField("city", max_length=64) state = USStateField() # django_localflavor_us.models zip_code = USZipCodeField() # django_localflavor_us.models class ContactInfo(models.Model): name = models.CharField(max_length=50) address = models.ForeignKey(Address, null=True, blank=True) phone = models.CharField(max_length=50, blank=True) This is my modelviews.py class AddressModelForm(forms.ModelForm): class Meta: model = Address fields = '__all__' class ContactInfoModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ContactInfoModelForm, self).__init__(*args, **kwargs) for k, v in AddressModelForm.base_fields.items(): self.fields['address_{}'.format(k)] = v class Meta: model = ContactInfo exclude = ('address', ) I have tried playing around with is_valid and clean, but I can never seem to get it accept the new fields. I am unsure which method to validate it myself and get a cleaned_data version of the new input. Which I believe it is because address is missing, but I am trying to replace address with an Address form myself. -
How do I deploy Django app to (AWS) domain name?
I've only been working with Django for a few weeks, and just learned deployment. I have an AWS EC2 Instance, which I'm able to deploy my Django website/app to (i.e., if I go to the IP address in my browser, I'm able to access my website). However, I can't figure out how to deploy that same website to my domain name, which is registered on AWS. I followed AWS's documentation (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-ec2-instance.html), and https://cachecheck.opendns.com/ shows that my domain name routes to my EC2 instance. However, when I go to my domain name in my browser, it shows a 400 Bad Request. Is there something else I need to do when I setup nginx or gunicorn? I've tried replacing the {{yourEC2.public.ip}} in the nginx code to be my domain name instead of the IP address. I haven't been able to find any other resources online regarding deployment to domain names, specifically with AWS. :/ If anyone has any advice, I'd really appreciate it! This is what I have for deploying to the EC2 instance: settings.py DEBUG = False ALLOWED_HOSTS = ['{{yourEC2.public.ip}}'] STATIC_ROOT = os.path.join(BASE_DIR, "static/") (venv) ubuntu@54.162.31.253:~myRepoName$ python manage.py collectstatic gunicorn [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/{{repoName}} ExecStart=/home/ubuntu/{{repoName}}/venv/bin/gunicorn --workers 3 … -
Cloning ec2 linux instance on aws in local environment
I have a production server running on aws ec2 instance. Since, I was beginner when I started everything I hadn't use virtual env etc. Now, there are many dependencies and packages that I have installed somehow. Now is there a way to clone entire aws ec2 instance environment with all the packages into my local machine for dev work. I know from pip freeze I can get all the python dependencies (I have a running django server). But is there a way to clone everything (from docker etc.). -
How does transaction work? does it lock resources?
I thought transaction.atomic make the block either commit as a whole and roll all back to original. It seems transaction.atomic doesn't lock tables( or objects). I wonder if it doesn't lock all these referenced resources, how does it roll back? -
Variable not found. Declare it as envvar or define a default value
I am very new to Django and trying to configure python-decouple to use .env variables. I am getting DB_PASSWORD not found. Declare it as envvar or define a default value. when trying to run the server. The .env file is located in the root directory. Here is my code: settings.py import os from decouple import config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_development', 'USER': "db_user", 'PASSWORD': config('DB_PASSWORD'), } } my_app.env DB_PASSWORD=my_password -
Add User related objects in User model in Django Admin
I'm working on a Django 1.10 project, in which I have a model called Tagged article which is related to a user with the related_name as "tagging", now I want to display a table of TaggedArticle objects when we open a user object in Django admin.How can I achieve that functionality in Django Admin? Here's my models: TaggedArticle: class TaggedArticle(models.Model): user = models.ForeignKey(User, related_name='tagging') email = models.EmailField(max_length=255) category_fit = models.CharField(choices=choices, max_length=255) article = models.ForeignKey(Article, related_name='articles') link = models.URLField(max_length=255,) relevant_feedback = models.TextField(blank=True) category = models.CharField(max_length=255,) created_at = models.DateTimeField(default=timezone.now, editable=False) Help me, please! Thanks in Advance! -
What is selected_choice in views.py in dango Tutorials?
In django Tutorial polls/views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from .models import Choice, Question # ... def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice=question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I couldn't find a brief explanation how selected_choice,selected_choice.vote works ? please explain me in novice terms . Thank you for your time and effort !! -
def __str__(self) return doesnt work - python 3.6/ Django 1.11.6
The following is my code in the models.py file: from django.db import models # Create your models here. class RestaurantLocation(models.Model): name = models.CharField(max_length=120) location = models.CharField(max_length=120, null=True, blank=True) category = models.CharField(max_length=120, null=True, blank=True) def __str__(self): return self.name Instead of returning the restaurant name, it returns "RestaurantLocation object" in the output window of the admin section. Where am I going wrong? -
Possible to use WhiteNoise with Django-Compressor?
I'm new with Django, and I'm trying to automate and optimize my deployment for production. At this moment I use WhiteNoise to handle static files, but as far as I know he just handle and compress the static files. Recently I found out about this tool: https://github.com/django-compressor/django-compressor , but I don't know if it really worth it to drop WhiteNoise in order to use this Django-Compressor, since I've never heard of it and every guide recommends to use WhiteNoise for safety and stability reasons. It's possible to use both in the same project? If yes, how? If not, worth changing it to use in a PaaS like Heroku? -
group by SKU using date range filter in Django Admin
I have the following model: from django.db import models class KPIReport(models.Model): Date = models.DateField() ASIN = models.CharField(null=True,blank=True,max_length=200) ItemSKU = models.CharField(max_length=200,blank=True,null=True,default='sku') Account = models.CharField('ACCT',null=True,blank=True,max_length=200) Country = models.CharField('MKT',null=True,blank=True,max_length=200) Sessions = models.IntegerField('SESS',blank=True,null=True) Session_Pct = models.DecimalField('SESS %',max_digits=8,null=True,blank=True, decimal_places=2) Page_Views = models.IntegerField('P.VIEWS',blank=True,null=True) Page_Views_Pct = models.DecimalField('P.VIEWS %',max_digits=8,null=True,blank=True, decimal_places=2) Buy_Box_Pct = models.DecimalField('B.B. %',max_digits=8,null=True,blank=True, decimal_places=2) Units_Ordered = models.IntegerField('UNITS ORD',blank=True,null=True) Units_Ordered_B2B = models.IntegerField('U.O. B2B',blank=True,null=True) Unit_Session_Pct = models.DecimalField('U.SESS %',max_digits=8,null=True,blank=True, decimal_places=2) Ordered_Product_Sales = models.DecimalField('ORD SALES', max_digits=8,null=True,blank=True, decimal_places=2) Ordere_Product_Sales_B2B = models.DecimalField(max_digits=8,null=True,blank=True, decimal_places=2) Total_Order_Items = models.IntegerField('TOTAL',blank=True,null=True) Total_Order_Items_B2B = models.IntegerField('T. ITEM B2B',blank=True,null=True) BSR = models.IntegerField(blank=True,null=True) Actual_Sales = models.IntegerField('SALES',blank=True,null=True) Selling_Price = models.DecimalField('PRICE', max_digits=8,null=True,blank=True, decimal_places=2) Notes= models.CharField(max_length=200,null=True, blank=True) class Meta: ordering = ['-Date','-Country','Account','BSR','ItemSKU',] verbose_name_plural = "-KPI REPORT" def __str__(self): return self.ItemSKU I am using a date range filter and it is working as expected. I use this model manager to get filtered results excluding objects without Sessions (sessions=None) class CAN_Manager(models.Manager): def get_queryset(self): return super(CAN_Manager, self).get_queryset().filter(Country='CAN').exclude(Sessions=None) class KPI_CAN(KPIReport): objects = CAN_Manager() class Meta: verbose_name_plural = "Marketplace: Canada" proxy = True Is there a way to use the rangeFilter, or, make a custom range filter that would -sum the values that are aggregate (sessions, totals) -average the values that are not aggregates (average %) -and display the values that are the same (SKU, account, etc) Here is my … -
Two forms one view: model variable loses value
Here's my code @login_required def upload(request): form_type = '' transcript = Transcript() transcript.file_path = '' if request.method == 'POST': if 'file_form' in request.POST: file_form = FileForm(request.POST, request.FILES) if file_form.is_valid(): path = handle_uploaded_file(request.FILES['file'], request.user) transcript.file_path = path transcript.user = request.user export_form = InfoForm() form_type = 'info_form' elif 'info_form' in request.POST: if transcript.file_path: info_form = InfoForm(request.POST) if info_form.is_valid(): transcript.user = request.user transcript.title = info_form.cleaned_data.get('title') transcript.instructions = info_form.cleaned_data.get('instructions') transcript.save() return HttpResponseRedirect('thanks') else: raise ValueError('Transcript object has no file path attribute') else: export_form = FileForm() form_type = 'file_form' return render(request, 'transcription/upload.html', {'form': export_form, 'form_type': form_type}) always, the file-form is called before the info-form, so the code in the if statement if transcript.file_path: #... should always execute. But the ValueError always gets raised, meaning transcript.file_path is reset. How does this happen, and how can it be fixed? def handle_uploaded_file(file, user): id = randint(0, 10000) user_dir = settings.MEDIA_ROOT + '/' + str(user.id).replace(".", "") + '/' path = user_dir + file.name.replace(".mp3", str(id) + ".mp3") if not os.path.exists(user_dir): os.makedirs(user_dir) with open(path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) file = File(destination) info = {'path': path, 'file': file} return path -
Django - manytomany relation between User.Profile and another model, ValueError: Cannot add
user/models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Bread(models.Model): title = models.CharField(max_length=40) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) picture = models.ImageField(upload_to="photos/", default="photos/none/default.png") bread = models.ManyToManyField(Bread) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I trying to add a simple object to Profile model, but it does not work. >>> from user.models import Bread >>> from user.models import Profile >>> from django.contrib.auth.models import User >>> p1 = Bread(title="Example") >>> p1.save() >>> Profile(User).bread.add(p1) ValueError: Cannot add "<Bread: Example>": instance is on database "None", value is on database "default" >>> u1 = Profile(User) >>> u1.save() TypeError: _prepare() takes 1 positional argument but 2 were given Seeing similar previous questions I tried to save profile model, as u can see, I know its related with User and his id, but i have no idea how to fix it easily -
django.urls.exceptions.NoReverseMatch Class Based List Views
I am attempting to set up a website on cookeicutter, I created a new app called "bots" and added a class called Trade and Unit within models. I created two class based views inside of views.py; detail and list view. The trade detail view works fine and directs to the correct trade, but when I attempt to visit the html page that references the trade list view, the page returns the following error. django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'trade-detail' with arguments '('1',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I believe something is wrong with the get_absolute_url, because when i remove it from the model.py the list error above goes away and the page renders, but then the links don't work. Most of my code is from this tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views Models.py from django.db import models from datetime import date from django.urls import reverse from django.urls import reverse_lazy from django.conf import settings import uuid class Unit(models.Model): TRADE_UNIT = ( ('ETH', 'Ethereum'), ('BTC', 'Bitcoin'), ('LTC', 'Litecoin'), ('IOT', 'IOTA'), ('OMG', 'OmiseGo'), ('BCH', 'BitcoinCash'), ) sell = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='ETH', help_text='Currency to Sell') buy = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='BTC', help_text='Currency to Buy') def get_absolute_url(self): """ Returns the url to access a …