Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django recommendation engine only works via phython shell
I have written this recommendation engine(based on Django by Example Antonio Mele). All works when tested using the shell, and the recommended products can been seen in the rendered templates. But when an order is completed via the application, recommendations are not created or d0isplayed. Am completely stuck on this one, any suggestions much appreciated.... import redis from django.conf import settings from .models import Product # connect to redis r = redis.StrictRedis(host=settings.REDIS_HOST,port=settings.REDIS_PORT,db=settings.REDIS_DB) class Recommender(object): def get_product_key(self, id): return 'product:{}:purchased_with'.format(id) def products_bought(self, products): product_ids = [p.id for p in products] for product_id in product_ids: for with_id in product_ids: # get the other products bought with each product if product_id != with_id: # increment score for product purchased together r.zincrby(self.get_product_key(product_id),with_id,amount=1) def suggest_products_for(self, products, max_results=6): product_ids = [p.id for p in products] if len(products) == 1: # only 1 product suggestions = r.zrange(self.get_product_key(product_ids[0]),0, -1, desc=True)[:max_results] else: # generate a temporary key flat_ids = ''.join([str(id) for id in product_ids]) tmp_key = 'tmp_{}'.format(flat_ids) # multiple products, combine scores of all products # store the resulting sorted set in a temporary key keys = [self.get_product_key(id) for id in product_ids] r.zunionstore(tmp_key, keys) # remove ids for the products the recommendation is for r.zrem(tmp_key, *product_ids) # get the … -
Django 2: Migration with data that doesn’t exist in another app
I’m trying to create a new table and load it with initial values that don’t currently exist in another table. All of the migration information that I have found is to pull from an existing model into a new model. I want to put new information in a new model. For example: If I want a “Country Model” and a “State Model” with a foreign key to the country, how do I make a “Country(US)” with all of the states that go with that country? And then if I later create “Country(Canada)” with all the territories in the same file as “US”, will it only add “Canada” or will it duplicate all of the “US” information. Sorry for the bad format. I’m currently typing on my iPhone and haven’t figured out the formatting. -
Where should I put extra methods?
I have extra codes that are not applied to the view. It is not a model and is not part of the URL. It is just a code that increments a default number to a number field of a model. Should I put this method inside the models.py file? Remembering that I use the django framework. This is method: def increment_process_number(): year_date = now().year year_atual = int(year_date) last_number = Process.objects.all().filter(date__year=year_atual).order_by('number').last() if not last_number: new_number = 1 return new_number else: number = last_number.number number_int = int(number) new_number = number_int + 1 return new_number Prioritizing good development practices, where should I save this method. -
Validate Foreign Keys, just one to have a not null value
I have a model with 2 FK keys class C(models.Model): a1 = models.ForeignKey(A, blank=True, null=True, related_name='c', on_delete=models.CASCADE) a2 = models.ForeignKey(B, blank=True, null=True, related_name='c', on_delete=models.CASCADE) When the model is saved I want just on FK to exist, the other to be null. If is not this case o raise a Validation. Because I need it also in Django Admin, I prefer to be done in the Model, to avoid using a complex custom form in Django Admin. -
Django no reverse match for view in {% url %}
When using Django 2.0.3, I get the error Reverse for 'detail_view' not found. 'detail_view' is not a valid view function or pattern name. With this row highlighted in my template (results/list.html): data-href="{% url 'detail_view' intron_id=hit.0 %}" (If it matters, this line is in a {% for hit in results %} loop; I didn't include the rest of the html file because the tags were being displayed) The main urls.py file is from django.contrib import admin from django.urls import path, include from sitepages import views from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('about/', views.about, name="about"), path('results/', include('results.urls')), ] urlpatterns += staticfiles_urlpatterns() and the results app's urls.py file is from django.contrib import admin from django.urls import path, re_path from . import views app_name='results' urlpatterns = [ path('list', views.list), re_path('(?P<intron_id>\w+)/$', views.detail_view, name='detail_view'), ] The views.py file for the results app is from django.shortcuts import render import apsw import re from .models import Introns #parse input from search bar and get requested info from database def detail_view(request, id): conn = apsw.Connection('subset.db') cur = conn.cursor() #just get one example intron so that we can format the individual intron view page cur.execute("SELECT * … -
Templating a directly raw query in a html table
I'm beginner in django and i'm using a read-only db, I just wanna make some selects and show it as a table in my template, but I cant return coulmn by column into my html table, help me, I'm using a directky raw query Model.py from django.db import connection # Create your models here. def dictfetchall(cursor): "Returns all rows from a cursor as a dict" desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def my_custom_sql(self): with connection.cursor()as cursor: cursor.execute(""" SELECT EQUIP_ID, LINE_CODE, PLANT_CODE FROM tbs_rm_mnt_shift_sumr where SUMR_YMD = '20180405' AND SIDE_CODE = 'T' AND rownum < 20 """ ) row = dictfetchall(cursor) return row view.py from django.shortcuts import render, redirect, get_object_or_404 from .models import my_custom_sql # Create your views here. def show_list(request): query= my_custom_sql(self='my_custom_sql') return render(request,'monitoring.html', {'query': query}) monitoring.html <table border="2" style="solid black"> <tr> <td>Equip</td> <td>Line</td> <td>Plant</td> {% for instance in query %} {% for field, value in instance.items %} <tr> <td>{{ value }} </td> </tr> {%endfor%} {% endfor %} </tr> </table> browser output: enter image description here -
Django 2.0 - Facebook login with allauth - Can't Load URL: The domain of this URL isn't included in the app's domains
I´m doing a small project that requires login with facebook. I´m working locally, on https://localhost:8000/ The technologies used are Django 2.0, django-allauth and, in order to avoid an error that I was having for not using an SSL connection, I´m using Django-sslserver as a development server. When I click on the facebook-login button on my website, I´m bein redirected to this address: https://www.facebook.com/v2.12/dialog/oauth?client_id=160259374640207&redirect_uri=https%3A%2F%2Flocalhost%3A8000%2Fsocial-auth%2Ffacebook%2Flogin%2Fcallback%2F&scope=email+user_friends+public_profile&response_type=code&state=pavN29C9zMgo&auth_type=reauthenticate I´m having this error: 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. Part of my settings.py file: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['mysite.com', 'localhost'] # Application definition INSTALLED_APPS = [ # My Apps 'account', # Django Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Third party Apps 'sslserver', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_social_website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', # allauth specific context processors # "allauth.account.context_processors.account", # … -
Issues getting the distinct value from a hierarchy
I have a table in my model called Campus. Which is defined in a hierarchy such as: Group Campus Sector A 1 1 A 1 2 A 2 3 B 3 4 B 3 5 B 4 6 B 4 7 In my campus view I pull all fields from Campus with: # campus dimension for data reduce codes campusdim = CampusDimension.objects.all().distinct() When I try to render the distinct value of Campus or Sector in my HTML in a select 2 control it displays multiple values. <select data-placeholder="Choose one or more Sectors..." data-id="6" class="js-example-basic-multiple" multiple="multiple" id = "id_sectorsdimselect" value = "{{campus.d_level}}" name = "slevel" style="width: 1140px" > {% for sector in campusdim %} <option value="{{campus.d_level}}">{{campus.sector_name}}</option> {% endfor %} </select> </div> The sectors come through as duplicates. I've tried to add the following to my view and it states QuerySet' object has no attribute 'group_name'. sector = campusdim.sector_name.distinct() I've tried to add a CampusDimension.objects.values_list('sector_name',flat = True).distinct() but i still get duplicate values as list. How can I get a single value for the sector_name? -
Added Arbitrary number of page choices in Django Wagtail
I am trying to allow the linking of an unspecified number of data-sets to an articles using Wagtail CMS. There does not seem to be a way to allow the specification of multiple connections without creating a separate entity that allows you to link pages independently. I am assuming I will have to create a custom content panel to facilitate, this am I wrong? -
Error installing django-nvd3
I have the following error when executing the following command pip3 install django-nvd3 Collecting django-nvd3 Using cached django-nvd3-0.9.7.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/rs/30thcgbd2334t5kfx1n3fj5w0000gn/T/pip-build-g97vw973/django-nvd3/setup.py", line 7, in <module> readme = readme_file.read() File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 2070: ordinal not in range(128) ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/rs/30thcgbd2334t5kfx1n3fj5w0000gn/T/pip-build-g97vw973/django-nvd3/ Why this is happening? -
Asymmetric behaviour of ModelSerializer
I have the following models: class Brand(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) name = models.CharField(max_length=30, blank=False, null=False) and: class Product(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) brand = models.ForeignKey('Brand', on_delete=models.CASCADE, null=True) I am writing the ModelSerializer for the Product model: class ProductSerializer(serializers.ModelSerializer): brand = serializers.UUIDField(source='brand.uuid', default=None) class Meta: model = models.Product fields = ('uuid', 'brand', ) read_only_fields = ('uuid',) Now going to the shell to serialize / deserialize product objects. First let's deserialize a Product instance: In [1]: product = Product.objects.all().first() In [2]: ProductSerializer(product) Out[2]: ProductSerializer(<Product: Product object (2)>): uuid = UUIDField(read_only=True) brand = UUIDField(default=None, source='brand.uuid') In [3]: ProductSerializer(product)['brand'] Out[3]: <BoundField value=1b03c6e1-8d9c-4273-ad07-d0d59a7f8cd9 errors=None> So the field 'brand' is a normal UUID field, as expected. Now in the other way around (serializing): In [4]: data = {'brand': '1b03c6e1-8d9c-4273-ad07-d0d59a7f8cd9', } In [5]: serializer = ProductSerializer(data=data) In [6]: serializer.is_valid() Out[6]: True In [7]: serializer.validated_data Out[7]: OrderedDict([('brand', {'uuid': UUID('1b03c6e1-8d9c-4273-ad07-d0d59a7f8cd9')})]) In [8]: serializer.validated_data['brand'] Out[8]: {'uuid': UUID('1b03c6e1-8d9c-4273-ad07-d0d59a7f8cd9')} So here is the issue: in one way (deserialization), brand is the UUID of the Brand instance, as expected in its declaration in ProductSerializer. In the other way (serialization), brand points to a dictionary with a key called 'uuid' to refer to the UUID of the brand. As if DRF is managing … -
Django :How can I let my modelChoiceField take two possible types of models
I need to let a modelChoiceField have the possiblity of taking two different models objects. for example can billnum take as queryset: facture_ventes.objects or facture_depc.objects at the same time instead of only one model : billnum=forms.ModelChoiceField(queryset=facture_ventes.objects) Thank You For your Help -
Django model manager using foreign models
Can I make a manager in django to return queries from another model? This is for django 2 with python 3.4. Possibly a newbie problem. Say I have two models, one with foreign key to another: class Person(models.Model): name = models.CharField() class Car(models.Model): driver = models.ForeignKey(Person, related_name='driver') name = models.CharField() I want to have a manger for Person that gives all cars that has a given "Person" as a driver. I can think of some workarounds, but it feels like django default manager should allow that. My idea was to prepare a manger for Person that returns hard-coded queries of Car, but it is impossible because names of classess can't be resolved (Person needs to know the body of a manager, and a manager needs to know the body of a Car). -
Django Oauth Issue 'AccessToken' object is not callable or not iteratable
I am try to implement the Django Oauth for generating Access token with respect to user creation with class based method. serializer.py class UserCreateSerializer(ModelSerializer): def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user class Meta: model = User fields = ('username', 'email' ,'password') views.py class User_Create_view(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() permission_classes = [AllowAny] authentication_classes = Has_Access_Token def create(self, request): serializers =self.serializer_class(data=request.data) if serializers.is_valid(): # pdb.set_trace() serializers.save() #Has_Access_Token.access_token() return Response(serializers.data) permission.py class Has_Access_Token(BaseAuthentication): def access_token(request): app = Application.objects.get(name="testing") tok = generate_token() acce_token=AccessToken.objects.create( user=User.objects.all().last(), application=app, expires=datetime.datetime.now() + datetime.timedelta(days=365), token=tok) return acce_token # @method_decorator(access_token) def authenticate(self): return request If I am using the above implicit method at which access token is generated with respect to the user created but not the best practice. So for making the custom authentication class in APIView, what's the standard procedure, either with respect to decorator or through BaseAuthentication class what should i change. When I am Not using the Decorator File "/home/allwin/Desktop/response/env/local/lib/python2.7/site-packages/rest_framework/views.py", line 262, in get_authenticators return [auth() for auth in self.authentication_classes] TypeError: 'type' object is not iterable when I use the Decorator File "/usr/lib/python2.7/functools.py", line 33, in update_wrapper setattr(wrapper, attr, getattr(wrapped, attr)) AttributeError: 'tuple' object has no attribute '__module__' How to debug the … -
How to post data from arduino to python / django database
I have created a arduino program and upload it to my arduino devices, but now I have faced a major issues that I don't know how to post the data from arduino to my python program through a serial port, can anyone help me with this ? Please, Thanks !!! If you need my arduino program , I will upload it ~ Thanks !! -
Django NULL constraint fails
I want to have an IntegrityError to raise, once a null value is being stored in a field that is not allowing null. The model is as follows: class Domain(models.Model): uuid = models.UUIDField(default=get_hex_uuid, primary_key=True, editable=False) name = models.CharField(null=False, max_length=128) The get_hex_uuid function works, I've tested this. It all fails when I start to save Domain objects as follows: d = Domain().save() or Domain().save() Clearly both of these should raise an error, as their name value is None/NULL, but it doesn't happen. Now when I select either one of these objects with the Domain.objects.all(), I do get that their name value is stored as >>> d = Domain.objects.all().first() >>> d.name >>> '' So I started checking at the normal initialise of the Domain object: >>> d = Domain() >>> d.name >>> '' So apparently it defaults to ''. Why is this? In my earlier experiences, the properties got initialised to None or NULL. So why does the object property start at ''. How can I fix this? -
Redirecting User To Non Coded URL
Our app POSTS user data and then get's a success or rejected response. The success response will come with a URL like such: b'SUCCESS|http://examplesite.com/m.cfm?t=17&wm_login=info&gouser=50105E5C440' The issue is when I split this data in python to so I can send users to the URL python encodes this URL so it no longer works. There is no server error message but rather the error is apparent in the redirect URL: http://examplesite.com/m.cfm?t=17&amp;wm_login=info&amp;gouser=50105E5C440 Notice the & gets converted to &amp; I have tried contless solution to similar problems but nothing seems to redirect the user to an uncoded URL. The part that get's me is that when I print() the redirect URL it actually shows the right one! The reason I redirect to a page first is that this form is an iframe and otherwise the Parent page does not get redirected. views.py def iframe1(request): ip = get_real_ip(request) created = timezone.now() if request.method == 'POST': form = LeadCaptureForm1(request.POST) if form.is_valid(): # Save lead lead = form.save(commit=False) lead.created = created lead.birth_date = form.cleaned_data.get('birth_date') lead.ipaddress = get_real_ip(request) lead.joinmethod = "Iframe1" lead.save() # API POST and save return message payload = { ... } r = requests.post(url, payload) print(r.status_code) print(r.content) api_status1 = r.content.decode("utf-8").split('|')[0] api_command1 = r.content.decode("utf-8").split('|')[1] print(api_status1) … -
OperationalError during adding records with polish signs through django-admin
I use Django with Mysql database. During adding records to database through django-admin with specjal characters like ąęćźż I get: (1366, "Incorrect string value: '\\xC4\\x86wicz...' for column 'object_repr' at row 1") It happens only during adding records through admin panel. I don't have any problems adding records with special character through other views or raw query through mysql console. Is there any simple solution? I tried to execute every of this query: ALTER TABLE event_coursetype CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER DATABASE Events CHARACTER SET utf8; SET NAMES utf8; SET NAMES latin2; but it didn't help. -
Django (2.0.4) Paginator get_page() not working properly
My problem is excatly with Paginator get_page() method. Here is my view code: @login_required def photo_index_default_album(request): album = Album.get_default_album(request.user) photo_list = Photo.objects.all() photo_list.filter(Q(album=album.id)) # Here is the problem: # photo_list = Photo.objects.filter(album=album.id) paginator = Paginator(photo_list, 2) # Show 2 post per page page = request.GET.get('sayfa') photos = paginator.get_page(page) context = { 'title': album.name, 'photo': photos, } return render(request, 'photo/index.html', context) Above code is working properly. But if I call the line I commented, paginator.get_page() is working for only 1. page. After second page it returns a page that has a object_list with an empty QuerySet. I am new with Django and web works. Probably it is a basic knowledge. I just want to know, what is the difference between these 2 assigments that cause the problem: photo_list = Photo.objects.all() photo_list.filter(Q(album=album.id)) and photo_list = Photo.objects.filter(album=album.id) -
Send images by email
I want to send images by email in a html but when I see the mail the image is broken this is part of my code: data = { 'image_url': cms.image.url, } subject = 'Recibo de Pago - Shamosh Palombo' email_body = render_to_string( 'mails/supplier_receipt_html.html', {'data': data, } ) msg = email_body headers = {'Reply-To': "contacto@comuna18.com"} TO = 'mauricio.munguia@comuna18.com' mail = EmailMessage(subject, msg, 'contacto@comuna18.com', [TO], headers=headers) mail.content_subtype = "html" mail.send() And in the template i code like this: <img src="data.image_url" style="width:200px"> -
'ellipsis' object has no attribute 'lower' [on hold]
I am getting the following error when I run python3 manage.py runserver 0.0.0.0:8000 File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py", line 138, in __call__ response = self.process_request(request) File "/usr/local/lib/python3.6/dist-packages/django/middleware/security.py", line 25, in process_request host = self.redirect_host or request.get_host() File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 105, in get_host if domain and validate_host(domain, allowed_hosts): File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 579, in validate_host if pattern == '*' or is_same_domain(host, pattern): File "/usr/local/lib/python3.6/dist-packages/django/utils/http.py", line 291, in is_same_domain pattern = pattern.lower() AttributeError: 'ellipsis' object has no attribute 'lower' I am running this command on Ubuntu 16.04 in AWS(Amazon Web Service). Please help me how to fix this error. -
Django admin filter foreign key combobox
I'm a django beginner, so the code might be basic or wrong, but anyway... I have the following models: from django.db import models from django.conf import settings GRADE_CHOICES = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10'), ) class Professor(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=30) def __str__(self): rta = self.first_name+" "+self.last_name return rta class Student(models.Model): first_name = models.CharField(max_length=20, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) def __str__(self): rta = self.first_name+" "+self.last_name return rta class Subject(models.Model): first_name = models.CharField(max_length=50) students = models.ManyToManyField(Student, blank=True) professors = models.ManyToManyField(Professor, blank=True) def __str__(self): return self.first_name class Grade(models.Model): value = models.CharField(choices=GRADE_CHOICES, max_length= 2) subject = models.ForeignKey(Grade, on_delete=models.CASCADE, related_name='fk_grade') student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='fk_student') def __str__(self): return self.value To add a grade I need to select the subject and the student, so I want to filter the students based on the subject they belong to. If the student is not in that subject he shouldn't appear in the list. I'm using django 1.11 and python 2.7. -
In Django, whether the `session_key` is the `session id`?
In the Django database, whether the session_key is the session id? if is, why Django do not use session_id as the colum name? -
How to overwrite the built-in widget template?
The documentation for Django 2.0 says: Overriding built-in widget templates¶ Each widget has a template_name attribute with a value such as input.html. Built-in widget templates are stored in the django/forms/widgets path. You can provide a custom template for input.html by defining django/forms/widgets/input.html, for example. See Built-in widgets for the name of each widget’s template. If you use the TemplatesSetting renderer, overriding widget templates works the same as overriding any other template in your project. You can’t override built-in widget templates using the other built-in renderers. The way I understand this is that if I want to render a custom variant of my form field {{ form.name }} (which is an <input> element), I create a file in my templatesfolder named django\forms\widgets\input.html. However, this does not work for me. My customized input.html is not used for rendering. I would appreciate some help on this. -
ValueError at /setupuser/ invalid literal for int() with base 10: 'ekatech'
i given charfield to organiztion but it is giving error int()with base 10.I followed the django documentation and tried different ways but not working. plz help views.py def set_user(request): if request.method == "POST": form = Set_User_Form(request.POST) if form.is_valid(): organization=form.cleaned_data.get('organization') email_id=form.cleaned_data.get('email_id') Designation=form.cleaned_data.get("Designation") job_level=form.cleaned_data.get("job_level") emails_for_help=form.cleaned_data.get("share_email_with") instance=Setup_user(organization,email_id,Designation,job_level,emails_for_help) instance.save() return HttpResponse("form saved") forms.py: class Set_User_Form(forms.Form): organization=forms.CharField(max_length=200) email_id=forms.EmailField(max_length=30) CEO = 'CEO' JCHOICES = ( (CEO, 'CEO'), ) Designation=forms.ChoiceField(label="Designation",choices=JCHOICES) LEVEL1 = "L1", LCHOICES = ( (LEVEL1, "Level 1"), ) job_level=forms.ChoiceField(label="Job level",choices=LCHOICES) share_email_with= forms.ModelMultipleChoiceField(label="share Knowledge with", queryset=User.objects.all(),widget= forms.CheckboxSelectMultiple) class Meta: model = Setup_user models.py class Setup_user(models.Model): organization=models.CharField(max_length=200,blank=False,default="not given") email_id=models.EmailField(_('email address'), unique=True) CEO = 'CEO' JCHOICES = ( (CEO, 'CEO'),) Designation = models.CharField(max_length=5,choices=JCHOICES) LEVEL1 = "L1" LCHOICES = ( (LEVEL1,"Level 1"), ) job_level=models.CharField(max_length=2,choices=LCHOICES) emails_for_help=models.CharField(max_length=2000,null=True)