Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Frequent use of include template tag - how much is too much?
I noticed that I started using include template a lot. One of my template files has 20+ include tags. Some of them are for modal dialogs that in turn have include for different form field sets. I am also using basically the same buttons with different data attributes so these are also done with include tags. Some my "fragments" that I use with include have around only five lines of HTML code. I worry if this is too much and can negatively affect performance (since Django loads another files, etc..) For example whis is markup of one of my HTML fragments I am using with include: <div class="form-group"> <input type="url" class="form-control" id="video-link-input" name="video_link" placeholder="YouTube link"> </div> <input type="hidden" id="video_id" name="video_id" value=""> <img class="img-fluid img-thumbnail" id="video-img-preview"> Hope the question is not too broad. I would just like to avoid possible bad practice. -
Django how to serialize and validate external xml data
i have "problems" validating external xml. What i want is to fetch data from an external rss site, validate if all fields are present and save it to the database then. The problem i am having is that i am not sure how can i send the xml data to my validator. I tried in different ways but it was not working. https://api.foxsports.com/v1/rss?partnerKey=zBaFxRyGKCfxBagJG9b8pqLyndmvo7UU&tag=nba This is an example of the rss i am trying to parse. Here is my code: import json import requests import xml.etree.ElementTree as ET from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status, generics class Test(APIView): def get(self, request, format=None): response = requests.get( channel.url ) print(response.status_code) if response.status_code == 200: xml = response.text.encode("utf-8") tree = ET.fromstring(xml) for child in tree.iter("item"): serializer = RssSerializer(data=child) if serializer.is_valid(): serializer.save(parsed_xml) The problem here is that my serializer is always not valid, no matter what i do. I kind of got around this problem when i wrote a small helper function that is manually extracting fields from the request. It looks like this: def parse_xml(self, node): parsed_json = { "title": node.find("title").text, "description": node.find("description").text, "link": node.find("link").text, "pub_date": node.find("pubDate").text, "guid": node.find("guid").text, } return parsed_json Basically i just added this line parsed_xml … -
Undestanding Django Multi-tenancy
My env: Django + Postgres I have this case to solution: My models: ORG -> oneToMany -> BU(business Unit) -> ManyToMany -> departments ->OneToMany ->assets ->a dozen other related to assets. A Want to implement Multi-tenancy on ORG level, so that every time I create a new ORG everything above is replicate. In the past Where I using PHP and MYSQL it will be done on query it was horrible and not good to performance. Thanks -
How to create an image search engine similar to draw.io in Django? [on hold]
I am trying to implement something very similar to draw.io, is there a way I can have search shapes functionality in draw.io, without the use of an expensive api. -
how to change the path with render
I am working on a django application which contains two forms in two different templates. In the first form an image can be uploaded. Once the image is uploaded an image classifier classifies the image and renders the template with the second form. In the second form some description about the image is filled and the form is submitted. The form is then saved and can be viewed in a different template. urls.py urlpatterns = [ path('', views.index, name='home'), path('accounts/', include('django.contrib.auth.urls')), path('signup/', views.signup, name='signup'), path('items/', views.item_list, name='item_list'), path('items/upload/', views.upload_image, name='upload_image'), path('items/upload/description/', views.upload_item, name='upload_item'), path('items/<int:pk>/', views.delete_item, name='delete_item'), path('items/upload/image_classification/', views.image_classification, name='image_classification'), ] In the first form after the image is uploaded, the the path becomes items/upload/image_classification/ and the second form is rendered, which according to urls.py is path('items/upload/description/', views.upload_item, name='upload_item'). The problem I am facing is, when I try to save the second form, the image_classification function from views.py runs whereas upload_item function should ideally run. This leads to the form not saving. When I try to load the second form directly without the first form, the path then is 'items/upload/description/' and the form is saved successfully. What am I doing wrong? Here is the rest of the code views.py def upload_image(request): … -
ImportError: Interpreter change detected while importing xmlsec
I have a Django service and I recently added OneLogin SSO in it. Everying is working fine on local machine, but on server, login view throws this ImportError on each request. ImportError: Interpreter change detected - this module can only be loaded into one interpreter per process. The complete stacktrace is Traceback (most recent call last): File "/.virtualenvs/dj/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/.virtualenvs/dj/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 172, in _get_response resolver_match = resolver.resolve(request.path_info) File "/.virtualenvs/dj/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 267, in resolve for pattern in self.url_patterns: File "/.virtualenvs/dj/local/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/.virtualenvs/dj/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 310, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/.virtualenvs/dj/local/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/.virtualenvs/dj/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 303, in urlconf_module return import_module(self.urlconf_name) File "/.virtualenvs/dj/lib64/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "./bwell_clientportal/urls.py", line 23, in <module> from bwell_clientportal.apps.onelogin_sso import views as onelogin_views File "./bwell_clientportal/apps/onelogin_sso/views.py", line 9, in <module> from onelogin.saml2.auth import OneLogin_Saml2_Auth File … -
python manage.py runserver doesn't display anything
I used to work with django and I didn't face this problem in the past, Then I shifted for a while to Laravel ( and sure I changed a lot of things in the windows which I don't remember ). and now when I hit python manage.py runserver .. nothing happen and the shell seems as it hanged . hover once I hit crt + C .the normal window suddenly appear that says : You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. January 08, 2019 - 14:16:30 Django version 2.1.1, using settings 'django_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. However I am able to go to http://127.0.0.1:8000/ and I have the welcome page of django with this line added enter image description here It sounds crazy I know , please excuse me cause I am a newbie and thanx in advance -
What happens in the background when you submit a class based view?
I'm using a class based generic view, specifically the UpdateView. I have other objects that I have currently which does CRUD as expected. Now, I created a new object which also uses the generic class based views. My issue right now is that when I submit an update form, I can't exactly trace what happens when I press that submit button on an update form. it is pointing to go on this url http://localhost:8000/order/question_update/ but I don't have a question_update url that doesn't have a parameter. I have a question_update url that has a parameter at the end. from my urls.py path('question_update/', views.QuestionUpdate.as_view(), name='question_update'), and also the success url is not pointing to the question_update url above. How do I know what does the generic class UpdateView does when I hit the submit button? I'd just like to trace where it's getting the URL which I did not declared anywhere. I did a text search on my codes and this url is not declared at all. -
Add Custom Widget to Multiselect field (Sumoselect) - Django Smartmin
I having Model field which has ManyToMany field in which i want to select the multiple selection. The default selection will be shown. How to override to show Sumo select instead of that. -
python django running mysql docker using mysqldb getting SSL connection Error 2026
i am currently trying to run tests on local computer (i configured the docker on local) - so able to run tests not only on docker. so when i run the tests on the docker its work perfect. but when i run pytest its not working. i am using mysqldb library. Here is the error i am getting : File "/home/ido/miniconda3/envs/mdf-service/lib/python3.6/site-packages/django_prometheus/db/common.py", line 41, in get_new_connection *args, **kwargs) File "/home/ido/miniconda3/envs/mdf-service/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/home/ido/miniconda3/envs/mdf-service/lib/python3.6/site-packages/MySQLdb/__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "/home/ido/miniconda3/envs/mdf-service/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') if needed any configuration i will put here but i am not sure which code you need here to see. (important to say its works in 3 other computers with the same configuration. so its maybe related to computer mysql settings i am not sure at all) -
django haystack search directory is not growing
I have Django app with whoosh as search engine. I have also two language version - English and German. I made commands: python manage.py rebuild_index --noinput -u default --remove python manage.py update_index -u default Both versions is not working. I have no results. Size of folders on server (after rebuild_index and update_index): whoosh_index_de - 1.5 MB whoosh_index_en - 1.5 MB On staging everything is working, folders have about 150 MB. settings configuration: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'search.backend.MultilingualWhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index_de'), }, 'default_de': { 'ENGINE': 'search.backend.MultilingualWhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index_de'), }, 'default_en': { 'ENGINE': 'search.backend.MultilingualWhooshEngine', 'PATH': os.path.join(BASE_DIR, 'whoosh_index_en'), }, } On staging everything is working, but not on live. -
Google Chrome does not show the back end error
i want chrome to show the error by detail but it doesn't! the way i see i want some thing like this. the way i want to see -
how to allow users to send email once they submit the form in django
i am creating a website that allow user to enter some data and once they submit the form system will send an email to inform the receiver that a new record had been created. the problem is i do not know how to send email using django i tried to add the basic settings in the settings .py file and import send-email and use this function in order to send the email with all required arguments. settings.py: # email setup EMAIL_HOST = 'smtp.hushmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'devleb@hushmail.com' EMAIL_HOST_PASSWORD = '************' EMAIL_USE_TLS = True views.py this function allow user to select the receiver by check the box and once the user select the receivers and send the data in the background i need to send an email to the receiver to inform him about the new record. def post_send(request): te2chira_id=request.POST['i'] section=request.POST['s'] print(request.POST) print(te2chira_id) print(section) te2chira.objects.filter(te2chira_id=te2chira_id).update(is_sent=1) te2chira_record=te2chira.objects.get(te2chira_id=te2chira_id) Createq=destination( te2chira_id=te2chira_record, section=section ) Createq.save() #send the email after to inform selected sections send_mail('New Te2shira', 'hello there this is a test email.', 'devleb@hushmail.com', ['camiw@mail-2-you.com'], fail_silently=False) return render(request, './creativePage.html', {}) once the user select the receiver sections the system send in the background the email to the selected sections in order to inform them … -
Django Queryset : Update object with input table value
I would like to get your mind on my issue. I would like to update objects with my queryset but there are conditions to update them. My environment : Django 1.11.18 PostgreSQL Context : I'm managing publications in my Django web application. Each publication gets some attributes (title, id, ...) and 2 very important parameters : in_carousel carousel_order The first one is a Boolean field. If yes, the publication is displayed in the main carousel, if not it doesn't. The second one lets to define an order of appearance for publications displayed in the carousel. My table : What I would like to do : I would like to Addpublications and Adda number in the input Define Orderfield. But I don't overcome to add a specific number for a specific publication that I would like to set as in_carousel. How I could do that ? My model : class Publication(models.Model): pub_id = models.CharField(max_length=10, verbose_name=_('publication ID'), unique=True, default='') title = models.CharField(max_length=512, verbose_name=_('title'), null=False, unique=True) cover = models.ImageField(upload_to='media/cover/', verbose_name=_('cover page'), default='') in_carousel = models.BooleanField(verbose_name=_('carousel'), default=False) carousel_order = models.CharField(max_length=500, verbose_name=_('carousel order'), null=True) My view : class ManageCarouselView(TemplateView): model = Publication template_name = 'manage_carousel.html' def get_context_data(self, *args, **kwargs): context = super(ManageCarouselView, self).get_context_data(*args, **kwargs) subtitle … -
Can't able to access Model custom functions after adding values to queryset in View
I created a Product model and added a custom def get_status_class to manage css classes for badges as per status and it works if I use all() in queryset but after using .values() with some particular field It's not working. Model.py class Product(models.Model): PRODUCT_STATUS = ( ('Planning','Planning'), ('In Progress','In Progress'), ('Final','Final'), ) status = models.CharField(max_length=20,choices=PRODUCT_STATUS) def get_absolute_url(self): return reverse('products:product_detail',kwargs={'pk':self.pk}) def get_status_class(self): status_class = "" if self.status == "Planning": status_class = "primary" elif self.status == "In Progress": status_class = "secondary" elif self.status == "Final": status_class = "success" return status_class def __str__(self): return self.title View.Py class ProductListView(LoginRequiredMixin,ListView): model = Product def get_queryset(self): queryset = Product.objects.all().order_by(self.order_by) return queryset.values('status') Template.py <span class="badge badge-pill badge-{{product.get_status_class}}">{{ product.status }}</span> product.get_status_class is not working if I add .values('status') in queryset. -
How set up default values in Django forms choice field?
I am trying to set up some default values in a django form choicefield where i ask for the user his birthdate and the city where he lives, i already tried pass the parameter "initial" in the form and add an attribute value but is not working. here is my code... forms.py class RegisterForm2(forms.Form): gender = forms.ChoiceField(choices = gender_choices,required=True) birthdate = forms.DateField(widget =forms.SelectDateWidget(years=range(1900, 2020))) marital_status = forms.ChoiceField(choices = marital_status, required=True) districts = forms.ChoiceField(choices = districts, required=True) city = forms.CharField(widget = forms.TextInput(attrs= {'id':'id_cidade', 'placeholder':'Nome da cidade onde vives'})) job = forms.CharField(widget = forms.TextInput(attrs= {'id':'id_profissao', 'placeholder':'A tua Profissão'})) class meta: model = UserRegister fields = ['gender', 'birthdate', 'marital_status', 'districts', 'city', 'job'] choices.py gender_choices = (('F', 'Feminino'), ('M', 'Masculino')) marital_status = (('S','Solteiro'), ('D', 'Divorciado'), ('V', 'Viuvo'), ('C', 'Casado')) districts = (('Aveiro','Aveiro'), ('Beja','Beja'), ('Braga','Braga'), ('Bragança','Bragança'), ('Castelo Branco','Castelo Branco'), ('Coimbra','Coimbra'), ('Évora', 'Évora'),('Faro','Faro'), ('Guarda','Guarda'),('Ilha da Madeira','Ilha da Madeira'),('Ilha dos Açores','Ilha dos Açores'),('Leiria','Leiria'),('Lisboa','Lisboa'), ('Portalegre','Portalegre'),('Porto','Porto'), ('Santarém','Santarém'),('Setúbal','Setúbal'),('Viana do Castelo','Viana do Castelo'), ('Vila Real','Vila Real'),('Viseu','Viseu')) -
How to fix 'name 'csrf' is not defined' error in Django
I took this code in the WEB but it was for Django 1.9. I'm using 2.1 in my project. I import this: from django.shortcuts import render_to_response, reverse from django.views import View from django.core.mail import send_mail from .forms import ContactForm from blog import settings class EContactsView(View): template_name = 'home/contacts.html' def get(self, request, *args, **kwargs): context = {} context.update(csrf(request)) context['contact_form'] = ContactForm() return render_to_response(template_name=self.template_name, context=context) def post(self, request, *args, **kwargs): context = {} form = ContactForm(request.POST) if form.is_valid(): email_subject = 'EVILEG :: Сообщение через контактную форму ' email_body = "С сайта отправлено новое сообщение\n\n" \ "Имя отправителя: %s \n" \ "E-mail отправителя: %s \n\n" \ "Сообщение: \n" \ "%s " % \ (form.cleaned_data['name'], form.cleaned_data['email'], form.cleaned_data['message']) send_mail(email_subject, email_body, settings.EMAIL_HOST_USER, ['target_email@example.com'], fail_silently=False) return render_to_response(template_name=self.template_name, context=context) name 'csrf' is not defined / traceback: img -
Django dropdown dependency , JSON
The point of my application is to only use the admin interface of django. I have two dropdowns , equivalent to country and city. So when i choose the country i need to show only the city's that belong to that country. Already make my view, but right now , i need to change my change_form.html and make javascript to recieve my view and i dont really know how to do that. My application: myproject/ |-- myproject |-- daa/ |-- avarias/ |-- models.py |-- views.py |-- mapeamento/ |-- models.py |-- templates/ |-- admin/ |-- daa/ |-- change_form.html My models #Mapeamento Model class freguesia(models.Model): freguesia_nome = models.CharField("Freguesia",max_length=200) def __str__(self): return format(self.freguesia_nome) class rua(models.Model): rua_id_freg = models.ForeignKey(freguesia, on_delete=models.CASCADE) rua_nome = models.CharField("Rua",max_length=200) def __str__(self): return format(self.rua_nome) #daa/avarias Model from mapeamento.models import freguesia from mapeamento.models import rua class avaria(models.Model): avaria_freguesia = models.ForeignKey(freguesia, on_delete=models.CASCADE,verbose_name="Freguesia") avaria_rua = models.ForeignKey(rua, on_delete=models.CASCADE,verbose_name="Rua") My views #daa/avarias views from django.http import HttpResponse import json def get_Avaria_rua(request,avaria_rua): freguesia_id_rua = request.GET.get('avaria_freguesia','') result = list(avaria_rua.filter(rua_id_freg=freguesia_id_rua).order_by('rua_nome').values('id', 'rua_nome')) return HttpResponse(json.dumps(result), content_type="application/json") My change_form.html {% extends "admin/change_form.html" %} {% block extrahead %} {{ block.super }} <script # DO SOMETHING </script> {% endblock %} -
Django using input field instead of select in createview
This is my model.py class Form(models.Model): color = models.ForeignKey(Color, on_delete=models.PROTECT) ... class Color(models.Model): color = models.CharField(max_length=20, unique=True, help_text="required") ... and this is my views.py class CreateForm(generic.CreateView): model = Form template_name = "..." fields = [__all__] my template is like this {% for field in form %} <div class="form-group"> <label class="control-label col-sm-2">{{ field.label_tag }}</label> <div class="col-sm-10">{{ field }}</div> <div class="col-sm-offset-2 col-sm-10"><span class="text-danger">{{ field.errors }}</span></div> </div>{% endfor %} There are thousands of colors in the DB, so using select field to find the one is not effective. Can I use the input field to instead of select field? Or is there any other good solution? Thanks -
AtributteError "object has no attribute" - how to prevent without try/except - accessing model field
I have a question: (I'm working on django 1.8, python 2.7.15) I'm getting object from database: shop_users = ShopUsers.objects.get(pk=_id) Then if object exists I am preparing data for View: if shop_users: data = { 'full_name': shop_users.full_name, 'shop': shop_users.shop.title, 'price_title': shop_users.price.title if shop_users.price.title else '', 'package_price': shop_users.price.price, 'user_price': shop_users.payment.operation_amount } But there is a possibility that shop_users.price.title won't exists. I would like to check it right while I prepare data like above (I'm doing '... if ... else'), but if shop_users.price.title does not exists it provides AttributeError. I can use try/except before 'data' declaration but this will double my code... Is there any trick for handling AttributeError with (... if ... else)? Maybe shop_users.price.title[0] (does not work) or get(shop_users.price.title) ? I just don't want to double my code... but I don't know any trick for this :/ I'm junior. I appreciate any help! -
post() missing 2 required positional arguments: 'self' and 'request'
I am trying to save a post request but I am getting post() missing 2 required positional arguments: 'self' and 'request' error. View: class MakeLeaveRequest(generics.CreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = MakeLeaveRequestSerializer # login_url = '../../users/v1/login/' def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): # self.perform_create(serializer) date = serializer.save() print(date) # headers = self.get_success_headers(serializer.data) return Response({'ok':'ok'}, status=status.HTTP_201_CREATED) Serializer: class MakeLeaveRequestSerializer(serializers.ModelSerializer): # date_to = serializers.DateField() # date_from = serializers.DateField() # description = serializers.CharField() # types_of_leave = serializers.IntegerField() class Meta: model = LeaveRequest fields = ('date_to', 'date_from', 'description', 'types_of_leave',) def create(self, validated_data): user = self.context['request'].user print(user) # print(validated_data['date_to']) LeaveRequest.objects.create(user = user) return user -
django jquery.ajax() & json load dynamic images
I'm trying to use JSON, jquery, ajax in Django to load dynamically images. I didn't learn about Django. I searched on stackoverflow and copy and paste what I understood. so I don't know Django well.. and There is few example. Therefor I ask question. There is no error. but it doesn't work. I don't know how works in Django. how can I fix this survey.html <script type="text/javascript"> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { startLoadFile(); } }; function startLoadFile() { $.ajax({ url: '/static/polls/json/images.json', type: 'GET', dataType: 'json', success: function (data) { createImages(data) } }) } function createImages(objImageInfo) { var images = objImageInfo.images; var strDOM = ""; var image = images[0]; var image1 = images[1]; strDOM += ' '; strDOM += '<img src="' + image.url + '" '; strDOM += 'class="wheel-first" width="135" height="135" />' strDOM += ' '; strDOM += '<img src="' + image1.url + '" '; strDOM += 'class="wheel-second" width="135" height="135" />' var $imageContainer = $("#wheels-img-container"); $imageContainer.append(strDOM); } </script> <div class="wheels-img-container"></div> views.py from django.shortcuts import render from django.views.generic import DetailView from polls.models import Wheel from django.core import serializers def survey(request): json_serializer = serializers.get_serializer("json")() wheels = json_serializer.serialize(Wheel.objects.all(), ensure_ascii=False) return … -
Not Able Receive Data from AngularJS
I am trying to send Parameters to Django View, but showing blanks. The following is my Angularjs Code The Value x, when I put altert, it is showing the expected value from HTML. This is my Django code @csrf_exempt def getEmpAppwise(request): print("In GET EMP AppWise.....................................................................") x=QueryDict(request.body) y=len(request.body) h=HttpRequest.body print('-rrrrrrrr :',x,y,h) #print('oooooooooo',json.loads(x)) print("Get EMp Wisee ",request.POST) print("Get EMp Wiseeeeee ",request.POST.get('ap')) ap=request.POST.get('ap') print("::::::::::I am in Get APP Name :::::::::::::::",ap) I tried in all possible ways with the help of StackOverflow, but could not get success The display shows as follows 0 None When I looked at parameters passed, in Firefox, it is showing as "No Parameters Passed" Can Some one help me please I have put all my details above I have put the code -
get() returned more than one TenantUser
my views.py @api_view(['POST']) @permission_classes((AllowAny,)) @csrf_exempt def transfer_tokens(request, domain): """ transfer tokens """ email = request.data['to_email'] # user_id = request.data['connected'] user = request.user coins_to_be_transferred = request.data["coins"] to_user = User.objects.get(email=email) user_id = to_user.id to_tuser = TenantUser.global_manager.get(user=user_id) tenantuser = TenantUser.global_manager.get(email=user.email) if to_user and user.kyc_done and to_user.kyc_done and coins_to_be_transferred >= 0: if user.coins >= coins_to_be_transferred: PoolHistory._default_manager.create( tenant=tenantuser, coins=coins_to_be_transferred, loss=True) user.coins = get_coins(tenantuser) user.save() PoolHistory._default_manager.create( tenant=to_tuser, coins=coins_to_be_transferred, profit=True) message = "You have received %s tokens from %s" % (coins_to_be_transferred, tenantuser.name) notification = Notifications(user=to_user, message=message) notification.save() return Response({"detail": "Tokens have been transferred successfully.", "coins": user.coins}, status=200) else: return Response({"detail": "Your account has insufficient tokens to complete the transfer."}, status=400) else: if not coins_to_be_transferred >= 0: return Response({"detail": "Tokens can't be transferred."}, status=400) if not to_user.kyc_done: return Response({"detail": "User with email isn't verified."}, status=400) else: return Response({"detail": "email doesn't exist."}, status=400) -
How to get value from choices in Django?
How to get a value from choices and display it on a form in Django? In this case (as in the picture), so that English is displayed, not en Picture of form In the template I print the form as a variable {{ form }}. I also tried to output by one field {{ form.language.get_lang_display }}, but in this case the language field is not displayed at all. File models.py class AvailableLanguage(models.Model): LANGUAGES = ( ('en', 'English'), ('ru', 'Russian'), ) lang = models.CharField(max_length=50, unique=True, choices=LANGUAGES) lang_code = models.CharField(max_length=5, unique=True) slug = models.SlugField() class Question(models.Model): title = models.CharField(max_length=250) language = models.ForeignKey(AvailableLanguage, on_delete=models.CASCADE, default='') body = models.TextField() ...