Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django SMTP
After reading the docs on the Django website, I'm a little confused on how to configure the SMTP backend with my Djagno application. I have a local exchange server that is running a business domain business.com that uses Outlook as the client. How do I configure the settings so that I am using a corporate email (local exchange) to send emails in the settings? Thanks for you help! -
How to run Django with Python 3.5?
After source ./bin/activate, on doing a which python3.5 I get the following response /path/to/virtualenv/bin/python3.5 I am using Django 1.10.5 which according to their documentation supports Python 3.5. But on doing python3.5 manage.py runserver, I get the following error, Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ImportError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? My project works perfectly fine with the default python 3 (3.4) in my Ubuntu 14.04 system. What is the issue here? If it's any help, I followed this process to install python 3.5. I did not remove the existing python3 from the machine as given in the end of the answer. I have both python3 and python3.5 -
Details page doesn't work? Django
I'm creating an aviation comparison website. On the main page, all the aircrafts are listed, and the title serves as a link to get to the details page. However this does not seem to work. I've spent 2 hours but can't see what the problem is? I appreciate any help! View.py def browseaircraft(request): all_aircraft = Aircraft.objects.all() variables = {'all_aircraft':all_aircraft} return render(request,'browseaircraft.html', variables) def aircraftdetail(request): model = Aircraft def get_context_data(self, **kwargs): context = super(aircraftdetail, self).get_context_data(**kwargs) context['aircraft_detail'] = Aircraft.objects.all() return context def aircraft_detail(request,pk): try: aircraft_id=Aircraft.objects.get(pk=pk) except Aircraft.DoesNotExist: raise Http404("Book does not exist") return render(request,'aircraft_detail.html',context={'aircraft':aircraft_id,}) URLs.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', 'aircraft.views.browseaircraft', name='browseaircraft'), url(r'^aircraft/(?P<pk>\d+)$', 'aircraft.views.aircraftdetail', name='aircraftdetail'),] browseaircraft.html % extends 'base.html' %} {% block content %} {% if all_aircraft%} {% for a in all_aircraft %} <img src="{{a.image.url}}"height="100" width="100"> <a href="{{ a.get_absolute_url }}"> {{ a.title }}</a> {{ a.range }}, {{ a.body }}, {% endfor %} {% else %} <p>There are no planes in the library.</p> {% endif %} {% endblock %} aircraft_detail.html {% extends "browseaircraft.html" %} {% block content %} <h1>Title: {{ a.title }}</h1> {{ a.cost }} {{ a.range}} {{ a.cost }} {{ a.cruise_speed }} {% endblock %} -
Working around SQLite's lack of named parameter support
Django's documentation on objects.raw() says the following about using named parameters: Dictionary params are not supported with the SQLite backend; with this backend, you must pass parameters as a list. I use SQLite when running unit tests in our codebase because it's ridiculously fast in comparison to our real database backend. But since it doesn't seem to support named parameters, I cannot write tests for this piece of functionality. Is there a clean generic way to work around this limitation? As in, without resorting to hacks that could expose code to SQL injection? -
Get the image (picture) of an django database using django-image-cropping and easy-thumbnails
I have an django installation with the plugins django-image-cropping and easy-thumbnails in use. I want to add users pictures to there vCard using vObject. models.py: (...) class Person(TranslatableModel): (...) pic = ImageCropField(_(u"profile picture"), blank=True, null=True, upload_to=settings.USER_PICTURE_DIR, ) picture_cropped = ImageRatioField( 'pic', '{}x{}'.format(*settings.USER_PICTURE_SIZE) ) (...) So far all I can find about this topic is, how to get an URL to the original Picture, but I don't know how to get the cropped Picture nor do I know how to get the Picture itself and not an URL nor a pseudo-file-type. -
django database functions cumulative count?
is their a way to create cumulative count using/customizing django database functions. this built-in query gets the number of items for each year. what if we need the number of items before that year ? Item.objects.values('year').annotate(nb=Count('id')) -
How to fetch data from three table in django?
I am trying to fetch data from three tables in which one is parent table and another two are OneToOne realted tables. My Table structure is as follows: Parent Table: class Request(models.Model): user = models.ForeignKey(User) order_id = models.CharField(max_length=100,unique=True) keyword = models.CharField(max_length=200) status = models.CharField(max_length=100,null=True,blank=True) locked = models.IntegerField(default=1) processed = models.IntegerField(default=0) reqest_mode = models.CharField(max_length=50) requested_on = models.DateTimeField(default=datetime.now) Child Tables are: class Recharge_request(models.Model): rech_request=models.OneToOneField(Request) mobile_no = models.BigIntegerField() operator = models.ForeignKey(Recharge_Operators,related_name='operator') amount = models.FloatField() billing_unit = models.IntegerField(null=True,blank=True) processing_cycle = models.IntegerField(null=True,blank=True) city = models.ForeignKey(City ,related_name='city',null=True,blank=True) account_no = models.CharField(max_length=20,null=True,blank=True) service_type = models.IntegerField(null=True,blank=True) cycle_number = models.IntegerField(null=True,blank=True) bill_group_number = models.IntegerField(null=True,blank=True) date_of_birth=models.DateField(null=True,blank=True) against = models.CharField(max_length=300,null=True,blank=True) class Wallet_Request(models.Model): wal_request = models.OneToOneField(Request) wallet = models.ForeignKey(Wallet) amount = models.FloatField() trans_type = models.CharField(max_length=20) against = models.CharField(max_length=100) trans_detail = models.TextField(max_length=500, null=True, blank=True) comment = models.TextField(max_length=500, null=True, blank=True) transfer_to = models.ForeignKey(User, null=True, blank=True) -
Multiple Databases --Migrations
I am using 2 postgres databases in my django app. 'newpostgre': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'new_postgre2', 'USER': 'tester', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', }, 'newpostgre2': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'new_postgre3', 'USER': 'tester', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', }, I have a very simple model class Check1(models.Model): title = models.CharField(max_length=100) I had run python manage.py migrate --database=newpostgre python manage.py migrate --database=newpostgre2 when I open my new_postgre2(for newpostgre) database in postgre, I can see my Check1 table there. But in my new_postgre3(for newpostgre2) database in postgre, no Check1 table is there, only those initial migrations are there. Why I can't see my table in new_postgre3 when migrations have been successfully made? -
APIs/Plugins in Ansible
I need to know is there any APIs or Plugins in Ansible that can be used to invoke Ansible scripts from GUI(or is it possible to invoke Ansible scripts from web framework like django or flask ?) -
Wrong number of constrains when refactoring modules to another app
After refactoring some models in a bloated app (everything in appname/models.py) into a subfolder application (some of the models in appname/subapp/models.py) and running makemigrations, I'm getting the following error when running manage.py migrate: ValueError: Found wrong number (2) of constraints for appname_modelname1(modelname2_id) Getting rid of all migrations and starting over would be one option, but then I'd have to manually edit all existing production databases. Are there any alternatives to make the migrations apply smoothly? -
Ways to implement google adwords-esque geo targeting functionality
Im looking for a way to implement something similar to google adwords geotargeting functionality (obviously less intense) Just something that takes user input as an HTML form, be able to select different countries/states/cities and somehow saves them to a database. If it helps, I am currently trying to do this in Django using python. But I'm guessing that any ideas or concepts will still be helpful. Right now, all I have on the drawing board of how to implement this, is just a giant table in MySQL with many many boolean columns # this is in Django, btw class GeoTargetSelection(models.Model): chose_canada = models.BooleanField() chose_china = models.BooleanField() ... Obviously this is not very salable, nor does it allow for states/cities. Does anyone have any ideas for the model/form/where to get list of states/cities/countries/etc? Anything will be appreciated -
make web portal for reading/write database
I need to know if there any service/product (like wordpress) that can do what I need: I have a DB with some data, and I need some webpages that can easly Show report from DB queries Write data in tables manage multi user with own permissions / own reports upload data from external in admin mode (secondary) I'm a DB developer, I can write all queries but I'm not good in front end web pages.. I had a look in django framework but I need something more "DRAG AND DROP" or something like wordpress/squarespace if it's possible. my budget is 100-20 $/€ year -
Send current user when model is saved in Django
I have a problem after a bigger upgrade from Django 1.7 to 1.10 and to Django Rest Framework 3.5.4. The problem is when I try to claim a voucher, the endopint /calims returns a 500 Error with the text: IntegrityError at /claims (1048, "Column 'user_id' cannot be null") In urls.py that route is added like this: url('^claims', v.ClaimList.as_view(), name='claim_list') And the relevant part from the views.py file is: class ClaimSerializer(serializers.ModelSerializer): company_name = s.ReadOnlyField(source="ad.company.name") company_address = s.ReadOnlyField(source="ad.company.address") ad_thumbnail = ThumbnailField(source="ad.picture", size="200x200", read_only=True) class Meta: exclude = ('user',) model = m.Claim class ClaimSerializerDeep(ClaimSerializer): class Meta: exclude = ('user',) model = m.Claim depth = 2 class ClaimSerializerFlat(ClaimSerializer): class Meta: exclude = ('user',) model = m.Claim @permission_classes((IsAuthenticated,)) class ClaimList(Limitable, generics.ListCreateAPIView): model = m.Claim def get_queryset(self): tab = self.request.GET.get("tab", "active") q = m.Claim.objects.filter(user=self.request.user.pk) if tab == "active": q = q.filter(redeemed=False, ad__end__gte=dt.date.today()) elif tab == "used": q = q.filter(redeemed=True) return self.limit(q) def pre_save(self, obj): obj.user = self.request.user def get_serializer_class(self): if self.request.method == "POST": return ClaimSerializerFlat else: return ClaimSerializerDeep And the claim model is: class Claim(models.Model): ad = models.ForeignKey("Ad") user = models.ForeignKey(settings.AUTH_USER_MODEL) created = models.DateTimeField(auto_now_add=True) redeemed = models.BooleanField(default=False) def save(self, *args, **kwargs): increase_claimed = False if self.pk is None: increase_claimed = True self.user = User.objects.first() super(Claim, self).save(*args, … -
Export csv file on django
Link: <a href="{% url 'testing:export_csv' tr_details.tr_id %}">Export CSV</a> When I click the anchor link, I would like to export the csv file and then go to the confirmation page. {% extends "users/UserBar.html" %} {% load staticfiles %}<!--Loading for CSS sheet--> {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'testing/style.css' %}" /> {% endblock css %} {% block title %}{{ tr_info.tr_id }} Export to CSV {% endblock title %} {% block header %}<a href="{% url 'testing:TrDetail' tr_info.tr_id %}">{{ tr_info.tr_id }}</a> Export to CSV {% endblock header %} {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} {% csrf_token %} {% block main %} <p>The file has been export to CSV for tr id : {{ tr_info.tr_id }} </p> {% endblock main %} All is working fine till this step. import csv from django.db import connections from django.http import HttpResponse from django.views.generic import ListView from testing.models import TrRunSummary, TrDetails class ExportCsv(ListView): """Displays the different tests performed on the specified test request""" template_name = 'testing/tr_export_csv.html' context_object_name = 'export_csv' def get_context_data(self, **kwargs): context = super(ExportCsv,self).get_context_data(**kwargs) context['tr_info'] = self.tr_info() return context def get_queryset(self): qtr_id = self.kwargs['trID'] s = str(qtr_id) # print s # print type(s) cursor = connections['default'].cursor() query =("SELECT results_stb_id, results_stbs.stb_id, stb_inv.mac_add, … -
Django : methode in models vs methode in views
I ask myself this question, what the difference and the more performant between a methode in models.py and views.py ? Example 1: models.py: class Counter(models.Model): number = models.PositiveSmallIntegerField(default=0) def add_one(self): self.number += 1 self.save() views.py from *xxx* import Counter def count(request): c = Counter() c.add_one() c.save() return render(request, *xxx*) Example 2: models.py: class Counter(models.Model): number = models.PositiveSmallIntegerField(default=0) views.py from *xxx* import Counter def add_one(nb): nb += 1 return nb def count(request): c = Counter() c.number = add_one(c.number) return render(request, *xxx*) My example is a little bit simple, but what the difference in the real life with big methode and so many variables ? Its have an impact on the performance of the server ? Did he have conventional or preference to choose one way ? -
downloadable file link in django tables
I am using django-tables2 and have a view which basically should allow user access to the data store. My table model has a link column is as follows: class DummyTable(tables.Table): download = tables.LinkColumn('dummy_download', args=[tables.A('pk')], orderable=False, empty_values=(), verbose_name='') The rendering of the link column is done as follows: class Meta: model = DummyModel attrs = {'class': 'paleblue'} def render_download(self): url = static('cloud-download.png') media_root = settings.MEDIA_ROOT href = media_root + "/mask.nii.gz" return mark_safe('<a href="' + href + '"><img src="' + url + '"></a>') So basically I have some data in my /media folder which I would like to allow the user to download when the link is clicked. However, I am unable to generate the correct link in the render_download method. Putting the link simply as I have it does not initiate any download even though it seems to point to the correct file location (locally). Also, I am not sure if this will work when someone connects remotely. I have a feeling it should call some reST API internally to initiate the download but I am not sure how to achieve this. The settings.py file configures the media settings as follows: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Disable model saves without going though DRF
I need to disable model saves unless the data is coming via a DRF serializer. I'm not sure the best way to do this. One way i can think of is override the save method and add some check which is fulfilled by the data coming from drf. Is there a better way to do this? -
Swift: Passing Password as parameter in alamofire to Django API
I am pretty new to django, so please bear with me. I had created a django rest api is linked to a postgresql database. I tested out the responses by hitting the urls via a python post request. I then proceeded to create an iOS app which communicates with the API through the Alamofire framework(meant for http requests). I created a dummy user in my postgres auth db with an unencoded password and am able to generate a token which I then use to hit the remaining urls. My question basically is this: Is it a good practice to send my password as a parameter without encoding it (maybe using md5)? Basically, how does djangorest perform authentication? Will it decode my password before it checks the authentication backend or does it straight up try to match the exact characters that are sent? Should I encode my password before I pass it? -
TemplateDoesNotExist at / Django?
I'm using Python 3.5 and Django 1.9. I know I'm making a stupid error somewhere but I can't seem to find it, any help on where the error can be? View.py from django.shortcuts import render from aircraft.models import Aircraft def browseaircraft(request): all_aircraft = Aircraft.objects.all() variables = {'all_aircraft':all_aircraft} return render(request, 'templates/browseaircraft.html', variables) Urls.py from django.conf.urls import url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', 'aircraft.views.browseaircraft', name='browseaircraft'), Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'AviationProject/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'debug': DEBUG, }, }, ] ...... STATIC_URL = '/static/' SETTINGS_PATH = os.path.dirname(__file__) PROJECT_PATH = os.path.join(SETTINGS_PATH, os.pardir) PROJECT_PATH = os.path.abspath(PROJECT_PATH) TEMPLATES_PATH = os.path.join(PROJECT_PATH, "templates") TEMPLATE_DIRS = ( TEMPLATES_PATH, ) My file directory looks something like this: -
Django : Export OneToMany using django-export-import
We have two models: class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): book = models.ForeignKey(Book) name = models.CharField(max_length=50) price = models.CharField(max_length=50) Now we want to export data of Author with book's details : Output Format : | author_name | book_name | book_price | ---------------------------------------- A1 B1 10 B2 20 B3 30 ---------------------------------------- A2 B4 20 B5 25 ---------------------------------------- A3 B1 10 ---------------------------------------- -
Django REST Framework and FileField absolute url on the same field
DRF serializes by default a filefield or imagefield path to it's relative path. Like in this questions Django REST Framework and FileField absolute url I know it's possible to generate a custom field called i.e. "file_url" and serialize the full path. But is it possible to serialize it in the same field? like: class Project(models.Model): name = models.CharField(max_length=200) thumbnail = models.FileField(upload_to='media', null=True) class ProjectSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Project fields = ( 'id' ,'url', 'name', 'thumbnail') class ProjectViewSet(viewsets.ModelViewSet): queryset = Project.objects.all() serializer_class = ProjectSerializer { "id": 1, "url": "http://localhost:8000/api/v1/projects/1/", "name": "Institutional", "thumbnail": "ABSOLUTE URL" } -
Django rest framework import error in on django.test.client
Im using google app engine dev server for python running on mac os. The project I'm running is an appengine django project using djangae and django rest framework. Everything in the project works fine, however as soon as a declare an import relating to the rest_framework I get an error regarding django.test.client eventhough I'm not running any tests at the moment. The import I try to do is 'from rest_framework.decoraters import api_view', as soon as I make this import or any other import relating to the rest framework. This is the error I get with every import I make that involves the rest framework. ERROR 2017-02-27 10:19:08,019 base.py:256] Internal Server Error: /_ah/warmup Traceback (most recent call last): File "/Users/MyUser/git/project-name/src/lib/django/core/handlers/base.py", line 223, in get_response response = middleware_method(request, response) File "/Users/MyUser/git/project-name/src/core/middleware/url_definition.py", line 32, in process_response response = redirect('%s/' % request.path) File "/Users/MyUser/git/project-name/src/lib/django/shortcuts.py", line 116, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "/Users/MyUser/git/project-name/src/lib/django/shortcuts.py", line 205, in resolve_url return urlresolvers.reverse(to, args=args, kwargs=kwargs) File "/Users/MyUser/git/project-name/src/lib/django/core/urlresolvers.py", line 578, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/Users/MyUser/git/project-name/src/lib/django/core/urlresolvers.py", line 432, in _reverse_with_prefix self._populate() File "/Users/MyUser/git/project-name/src/lib/django/core/urlresolvers.py", line 284, in _populate for pattern in reversed(self.url_patterns): File "/Users/MyUser/git/project-name/src/lib/django/core/urlresolvers.py", line 401, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/MyUser/git/project-name/src/lib/django/core/urlresolvers.py", line … -
Authentication failed in Github | python-social-auth
In my django project I use python-social-auth. I am tring to add social login with Github but unfortunately have next error: Authentication failed: The redirect_uri MUST match the registered callback URL for this application. Full error looks like this: Traceback (most recent call last): File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\views\decorators\cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\social_django\utils.py", line 50, in wrapper return func(request, backend, *args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\social_django\views.py", line 28, in complete redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\social_core\actions.py", line 41, in do_complete user = backend.complete(user=user, *args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\social_core\backends\base.py", line 39, in complete return self.auth_complete(*args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\social_core\utils.py", line 253, in wrapper return func(*args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\social_core\backends\oauth.py", line 386, in auth_complete self.process_error(self.data) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\social_core\backends\oauth.py", line 379, in process_error data['error']) social_core.exceptions.AuthFailed: Authentication failed: The redirect_uri MUST match the registered callback URL for this application. [27/Feb/2017 16:06:53] "GET /ru/complete/github/?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fv3%2Foauth%2F%23redirect-uri-mismatch&state=fEheCJ4QPZZuz7qHPQUKxvMWl2Rw4xTV HTTP/1.1" 500 105176 I registered application in Github and set set the callback URL as http://localhost:8000/complete/github/. settings.py INSTALLED_APPS = [ *** 'social_django', # python-social-auth ] … -
Customize form field according to other field
Please give me advice for my following question. I have added corresponding script at the bottom of this sentence. Thank you in advance!!! What I want to do: Customize form field according to the target field specified in the database as shown in following image. Current situation All the radio buttons in Ecms table are listed in one column html file {% extends "base.html" %} (% load widget_tweaks %} {% block content %} <form method="post" enctype="multipart/form-data"> <h4 style="margin-top: 0">Project Upload</h4> {% csrf_token %} {% for hidden in form.hidden_fields %} {{hidden}} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> <label for="{{field.id_for_label}}">{{field.label}}</label> {{field}} </div> {% endfor %} <button type="submit">Upload</button> </form> {% endblock %} Model.py(parent) class html(models.Model): project = models.CharField(max_length=50, blank=True) version = models.IntegerField(default=0) ecms=models.ManyToManyField(ecm, blank=True) diff = models.TextField(blank=True) PROGRAM_CHOICES = ( ('Office', 'General office'), ('Residential', 'Residential'), ('Retail', 'Retail'), ('Restaurant', 'Restaurant'), ('Grocery', 'Grocery store'), ('Medilcal', 'Medilcal office'), ('Research', 'R&D or laboratory'), ('Hotel', 'Hotel'), ('Daycare', 'Daycare'), ('K-12', 'Educational,K-12'), ('Postsecondary', 'Educational,postsecondary'), ('Airport', 'Airport'), ('DataCenter','Data Center'), ('DistributionCenter','Distribution center,warehouse') ) program = models.CharField(max_length=20, choices=PROGRAM_CHOICES, default='Retail') LOCATION_CHOICES = ( ('Beijing', 'Beijing'), ('China', 'China'), ('Hong Kong', 'Hong Kong'), ('Japan', 'Japan'), ('Shanghai', 'Shanghai'), ('Shenzhen', 'Shenzhen'), ('Taiwan', 'Taiwan'), ('USA', 'United States') ) location = models.CharField(max_length=15, choices=LOCATION_CHOICES, default="Hong Kong") … -
is db_column changing my mongodb field?
i'm new here. I'm having a problem with django where i have 'type' which is a reserved keyword as a column in mongodb. Based on answers in stackoverflow, i solved it by applying https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.db_column My code currently looked like this discountType = StringField(required=True, db_column='type') However, the problem is the field 'type' was changed to 'discountType'. Is there a way to prevent the model from changing the field name? TQ in advance