Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I deployed one Django project on two Elastic Beanstalk servers. Why does one have no images/access to the static file?
I deployed the same application (I know it's the same because the directory structures are exactly the same and I checked every file with the diff command) on two Elastic Beanstalk environments. I checked the settings and they appear identical except for Security Groups and one is not synced with my key (so I currently can't get into it's EC2 instance). Do you have any advice as to why they are behaving differently. Both are Python 3.6 running on 64bit Amazon Linux/2.7.7 servers and I am running Django 1.1.1. Here is my config file: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTING_MODULE: "ecs_site.settings" PYTHONPATH: "/opt/python/current/app/ecs_site:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: "ecs_site/ecs_site/wsgi.py" It's located in the .ebextensions directory. I think it's a problem with my static directory. Here's the pertinent information from the settings.py file. STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ecs_site/static')] I'm sure you'll have environmental questions. I'm here. -
Cannot import function from mysite.views in Django
mysite is the app name i created in my django project. below is the hierarchy of my app. mysite --- views.py --- tasks.py --- urls.py --- __init__.py I have a normal function(there is no request parameter, hence no entry in urls.py as well) in views.py as shown below. def function1(param1,param2): return something I am trying to import this function1 in tasks.py by using from .views import function1 but its throwing an error saying ImportError: cannot import name 'function1' from 'mysite.views' Is there any way to get rid of this error. -
Django qsessions - __init__() got an unexpected keyword argument 'ip'
When I try to install django qsessions, I get this error: Traceback (most recent call last): File "/.../lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/.../lib/python3.8/site-packages/sentry_sdk/integrations/django/middleware.py", line 131, in __call__ return f(*args, **kwargs) File "/.../lib/python3.8/site-packages/sentry_sdk/integrations/django/middleware.py", line 92, in sentry_wrapped_method return old_method(*args, **kwargs) File "/.../lib/python3.8/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/.../lib/python3.8/site-packages/qsessions/middleware.py", line 10, in process_request request.session = self.SessionStore( Exception Type: TypeError at /home/ Exception Value: __init__() got an unexpected keyword argument 'ip' Thank you for any suggestions -
Problem With Django POST Request in Google Cloud Endpoint
My iOS app sends POST requests to my Cloud Run service. I've implemented ESP for security. So here is the setup: Cloud Endpoints (ESPv2) (deployed on public Cloud Run instance) as a gateway for my private Cloud Run instance. I'm using firebase security definition. While sending POST requests to Cloud Endpoint I was getting 401. I thought the problem was with authentication. But I was wrong. Further testing in Postman: I disabled all security definitions in open api file. GET requests to Public ESP which calls Private Cloud Run Container work fine POST requests to Public ESP which calls Private Cloud Run Container result in 404 then I enabled all my previous security definitions: GET request with JWT to Public ESP which calls Private Cloud Run Container works fine POST request with JWT to Public ESP which calls Private Cloud Run Container result in 404 then I made my Private Cloud Run Container public (all_users) both POST and GET requests directly to Public Cloud Run work fine My Private Cloud Run Container runs on Django Rest Framework. Clearly the problem is in that EPS is not able to route POST requests to Private Cloud Run Container or Django is somehow … -
How to fetch data after selecting the item from dropdown, without reloading the page ,
I am trying to build the an invoice system,I have put all the models and views The problem that i am facing is when select the option from dropdown, I want it to fetch all field of that product from the database without reloading, and also I want this same step in next line with different product. [Views.py][1] [1]: https://i.stack.imgur.com/bVQhF.png Invoice.html <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <meta charset="UTF-8"> <title>Entry</title> </head> <body> <div class=""> <select name="" id="select_path" ONCHANGE="location = this.options[this.selectedIndex].value;"> {% for product in Products %} <option value="{% url 'book' product.id %}">{{ product.Name }} </option> {% endfor %} </select> {{productInfo.Name}} </div> </body> </html> Views.py from django.http import HttpResponse,Http404,HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import Product # Create your views here. def index(request): context={ 'Products':Product.objects.all(), } return render(request,'invoices/index.html', context) def query(request): context={ 'Products':Product.objects.all(), } return render(request,'invoices/invoice.html',context) def book(request,product_id): context={ 'Products':Product.objects.all(), 'productInfo':Product.objects.get(pk=product_id) } return render(request,'invoices/invoice.html',context) URL from django.urls import path from . import views urlpatterns =[ path('',views.index,name="invoice"), path('invoice/',views.query,name='detail'), path('<int:product_id>/book',views.book,name='book') ] Models from django.db import models # Create your models here. class Product(models.Model): id = models.AutoField(primary_key=True) Name=models.CharField(max_length=50) HSN_code= models.CharField(max_length=15,unique=True) Rate=models.DecimalField(max_digits=11,decimal_places=2) def __str__(self): return f" {self.id} {self.Name} {self.HSN_code} {self.Rate}" -
Django Storing Payment Method
I'm tasked with providing users the ability to store multiple payment methods (Credit Cards) within their profile. What's the best way to validate credit card entry and have it encrypted when saved to the database? This is a personal project and will only be used locally. -
How to play song from its object [closed]
Okay, so, I have two objects in django, two songs, and I want if I click on Frank Sinatra example, I want to play his song, if I click some other song, to play exactly that song, here is my code: Django models: class Song(models.Model): art_name = models.CharField(max_length=30) song_name = models.CharField(max_length=70) cover_image = models.ImageField(upload_to='images/') file = models.FileField(upload_to='musics/') Django views: def index(request): all_objects = Song.objects.all() json_data = serializers.serialize("json", Song.objects.all()) context = { 'json': json_data, 'all_objects': all_objects } return render(request, 'index.html', context) Javascript: var data = {{json|safe}} function playSong(){ console.log(data) } HTML: <div class="box"> <div class="arrowLeft">prev</div> <div class="arrowRight">next</div> <div class="img"><img src="{{ song.cover_image.url }}" alt="" onclick="playSong()"></div> <p class="title">{{ song.art_name }}</p> <p class="desc">{{ song.song_name }}</p> </div> -
How can i display my RadioSelect Widget in django
I have a model, form, view and i cannot seem to actually display the RadioSelect widget. it doesnt show anything, i think everything is fine except the views, however, i am unsure. I basically want someone to choose and option from the two radio buttons, submit to then be able to register as one of the two options but like i said i cant even get the buttons to show. views.py def registration(request): reg = Registration.objects.all() return render(request, 'HTML/Registration.html', {"reg":reg}) models.py class Registration(models.Model): OPTIONS = ( ('COUNS','Counsellor'), ('CLIENT','Client'), ) SELECT = models.CharField(max_length=15, choices=OPTIONS) forms.py class Registration(forms.ModelForm): class Meta: model = Registration fields = '__all__' widgets = {'SELECT': forms.RadioSelect} HTML <form method="POST"> {% csrf_token %} <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <h1 class="h2">Registration</h1> </div> {% render_field reg.SELECT %} <div class="form-row"> <div class="col pt-md-2"> <input type="submit" value="Next" class="btn btn-primary" style="float: right;"> </div> </div> </form> -
Update several fields in model instance using select_for_update in Django
I have model class named DataObj and some copmlex method that fetches DataObj isntance in the beginning, performs some calculations and updates it's fields. For integrity in concurrent environment it utilizes optimistic locking using integer version field. In order not to wrap all calculations in @atomic, I have short and fast save_changes function: @transaction.atomic def save_changes(DataObj dataObj): db_instance = DataObj.objects.select_for_update().get(id=dataObj.id, version=dataObj.version) # copy all changes from dataObj to db_instance db_instance.save() and I call it from my complex method def long_update_func(dataobj_id): obj = DataObj.objects.get(id=dataobj_id) # perform several calculations, update fields obj.field1 = result_of_calc1() ... try: save_changes(obj) except: # whoops, version changed notify_data_changed_during_calculations() Question: copying fields is really annoying. Can I avoid copying fields in save_changes function? I have nice modified dataObj with exactly same id, that I use to lock database rows in select_for_update call. Can I simply rewrite like this (or similar): @transaction.atomic def save_changes(DataObj dataObj): db_instance = DataObj.objects.select_for_update().get(id=dataObj.id, version=dataObj.version) # save our instance, because it has same id as db_instance and therefore its row in db table is locked db_instance.save() ? -
Django dev server using old version of views.py
For some reason, the changes I make on the views.py file are not being reflected. I initially made a function inside view.py to return HttpResponse(request.POST.items()). Even after making changes to the function, it's still performing the same thing. I tried clearing the cache of the browser, restarted the server, and also tried deleting the pyc files. Nothing worked. Any guess on why this is happening? -
How to add a value for a ModelMultipleChoiceFilter to queryset?
I need to add a field 'All' to choices of ModelMultipleChoiceFilter. In MultipleChoiceFilter I just use: shops = Shop.objects.filter(is_active=True) SHOP_CHOICES = [('All', 'All')] for x in shops: SHOP_CHOICES.append((x.address, x)) SHOP_CHOICES = tuple(SHOP_CHOICES) but in ModelMultipleChoiceFilter I have queryset instead of tuple. My filter: def departments(request): if request is None: return Shop.objects.none() curr_user = request.user if curr_user.role == 'SV': return Shop.objects.filter(is_active=True) else: return Shop.objects.filter(is_active=True, custom_user=curr_user) class ShopFilter(django_filters.FilterSet): address = django_filters.ModelMultipleChoiceFilter(queryset=departments) -
Django Rest / Sum the response values of identical coins
from api, I get multiply records on one coin. How can I summarize and add them to the Wallet.objects() correctly? Now I have such a code and it just overwrites the old value with a coin zero. Example i have response {"coin":"BIP","value":"5"} {"coin":"ZERO","value":"4"} {"coin":"BIP","value":"15"} {"coin":"INSIDER","value":"24"} {"coin":"BIP","value":"41"} I want add in database from this response: "coin":"BIP","value":"61" "coin":"ZERO","value":"4" "coin":"INSIDER","value":"24" Its sum all BIP (5+15+41). And other coins. How? My Wallet.objects now cant sum this amount obj, created = Wallet.objects.update_or_create(user=user, coin_id_id=coin.id, defaults={'amount_d': amount_d, 'amount_w': 0, 'cap_w': 0, 'cap_d': capitalize_d},) obj.save() i have this code: views.py def load_user_balance(request, wallet_id, imei): try: user = User.objects.get(imei=imei) except ObjectDoesNotExist: create = User.objects.create(imei=imei, wallet_mx=wallet_id) create.save() url_wallet = f"https://explorer-api.minter.network/api/v1/addresses/Mx6884bf2637f4efe8dc061132b9cfed03622dfc30" url_delegated = f"https://explorer-api.minter.network/api/v1/addresses/Mx6884bf2637f4efe8dc061132b9cfed03622dfc30/delegations" response_wallet=requests.get(url_wallet).json()['data'] response_delegated=requests.get(url_delegated).json()['data'] for coin in response_wallet['balances']: coin_w = coin['coin'] amount_w = coin['amount'] coin = Coins.objects.get(symbol=coin_w) user = User.objects.get(imei=imei) obj, created = Wallet.objects.update_or_create(user=user, coin_id_id=coin.id, amount_d=0, cap_w=0, cap_d=0, defaults={'amount_w': amount_w},) obj.save() for coin in response_delegated: coin_d = coin['coin'] amount_d = coin['value'] capitalize_d = coin['bip_value'] coin = Coins.objects.get(symbol=coin_d) user = User.objects.get(imei=imei) if Wallet.objects.filter(coin_id=coin).exists(): obj = Wallet.objects.filter(coin_id=coin).update(amount_d=amount_d, cap_d=capitalize_d) else: obj, created = Wallet.objects.update_or_create(user=user, coin_id_id=coin.id, defaults={'amount_d': amount_d, 'amount_w': 0, 'cap_w': 0, 'cap_d': capitalize_d},) obj.save() models.py class Coins(models.Model): name = models.CharField(max_length=150) symbol = models.CharField(max_length=45) crr = models.CharField(max_length=3) class Wallet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) … -
Django: automatically detect the tenant media folder when reading csv in Views.py
In my multi-tenant django app, the user needs to upload a file to the server. this file is then used in a view. my view uses pd.read_csv() to read the file uploaded, however I cannot find anywhere what to use inside of the brackets to automatically look inside of this particular tenant media folder. Thanks to django documentation, I was able to seperate my tenants within the media folder but I still don't how to write the path inside of the pandas.read_csv() Any help would be appreciated, thank you! -
Original exception text was: 'QuerySet' object has no attribute 'name' using django rest framework
I'm learning Django and i got to this error and I couldn't find the solution. Here are my models class Retailer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) website = models.CharField(max_length=255) def __str__(self): return str(self.id) class Product(models.Model): id = models.AutoField(primary_key=True) price = models.IntegerField(default=None, null=True) name = models.CharField(max_length=255) retailer = models.ForeignKey(Retailer,on_delete=models.CASCADE,related_name='retailer_info') is_active = models.BooleanField(default=False) def __str__(self): return str(self.id) And here are my serializers class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class RetailerSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True, read_only=True) class Meta: model = Retailer fields = ['name', 'website', 'products'] And here's my view class RetailerList(APIView): def get(self, request): retailer = Retailer.objects.all() serializer = RetailerSerializer(retailer) return Response(serializer.data) And here's my url path('retailer', views.RetailerList.as_view()), But when I submit a get request on 127.0.0.1:8000/retailer i get this error: AttributeError at /product Got AttributeError when attempting to get a value for field name on serializer RetailerSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'name'. What's the problem? -
Django creating .row for every post
i first time writing in django. When i trying to post-template, this code create a new <div class="row"></div> for every post. How i fix that? <div class="container news-card"> {% for post in post_list %} <div class="row" stlye="max-width"> <div class="card" style="width: 300px; height: 440px; margin-top: 60px; margin-left: 20px;"> <div class="card-img-top m-fix"><img src="https://telgrafs.com/assets/src/news-col1-row1-card-image.png"></div> <div class="card-text news-category">Ekonomi</div> <div class="card-title news-ct">{{ post.title }}</div> <div class="ccard-text news-ctext up-fix">{{post.content|slice:":200" }}</div> <div class="card-img-bottom author-image"><img src="https://telgrafs.com/assets/src/profile-kaa.png"></div> <div class="card-author-name">{{ post.author }}</div> <div class="card-post-time">{{ post.created_on}} </div> <a href="{% url 'post_detail' post.slug %}" class="card-text pb-more">DEVAMINI OKU &rarr;</a> </div> </div> {% endfor %} </div> {%endblock%} -
How to get a selected object in a form.Models using ModelChoiceField object
from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin from bootstrap_modal_forms.forms import BSModalForm from django.contrib.auth import get_user_model class CommentForm(BSModalForm, PopRequestMixin, CreateUpdateAjaxMixin,): created_by = forms.ModelChoiceField(label="", widget=forms.HiddenInput, queryset=get_user_model().objects.all(), disabled=True,) paragraph = forms.ModelChoiceField(label="", required=False, queryset=MeetingReportContent.objects.none(), to_field_name="pk", disabled=False,) def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) self.fields['paragraph'].queryset = MeetingReportContent.objects.filter(pk=PARAGRAPH_SELECTED_HERE) class Meta: model = MeetingReport_Comment fields = ['paragraph', 'created_by', 'content_comment', ] exclude = [ 'accepted', 'timestamp'] I'm trying to get only the paragraph selected for the queryset, but get many errors... -
How can I temporarily save selected data from one table to another without overwriting the previous data?
I have an html table where I need to transfer or copy a row of data from this table to another table of the same structure that I call cart in my database. To do this, I would like that when I click on the button (+) of a given row, to add the corresponding data in the cart table. This is my template <form type="post" action="" style="margin: 0" > <label for="code" class="nav-link">Référence </label> <div class="col-sm-9"> <input id="productCode" type="text" name="productCode" placeholder="Entez le code du produit ..." onkeyup="myFunction()"> </div> </form> <table class="table table-bordered" id="productsTable" width="400"> <thead> <tr> <th>ID</th> <th width="10%">Code</th> <!-- <th width="16%">Catégorie</th> --> <th width="50%">Libéllé</th> <!-- <th width="12%">Marque</th> --> <th width="11%">Date entrée </th> <th width="11%">Qté initiale </th> <!-- <th width="12%">Quantity </th> --> <!-- <th width="12%">Qtité finale </th> --> <th>PU</th> <!-- <th>Statut</th> --> <th style="align-self: center;">Actions</th> </tr> </thead> <tbody> {% if products|length < 1 %} <tr> <td colspan="20" class="text-center">Aucune donnée trouvée, veuillez ajouter quelques données!</td> </tr> {% else %} {% for product in products %} <tr> <td>{{ forloop.counter }}</td> <td>{{ product.code }}</td> <!-- <td>{{ product.category }}</td> --> <td>{{ product.name }}</td> <!-- <td>{{ product.brand }}</td> --> <td>{{ product.date_entry }}</td> <td>{{ product.quantity_entry }}</td> <!-- <td>{{ product.quantity }}</td> --> <!-- <td>{{ product.final_stock }}</td> --> … -
Adding filtering options in Django - does not work properly
I'm trying to flirt my queryset depending on what I have in the database. I created a function in which query is my all queryset and filters my object (conditions). query = Shop.objects.all() filters = get_object_or_404(Filters, id=1) def shop_filters(query, filters): if filters.category_car: query.filter(category=1) if filters.category_computer: query.filter(category=2) if filters.category_phone: query.filter(category=3) return query It seems my function is not working at all. Despite the conditions, none of them works. My queryset still remains the same length. It seems that my queryset that I let into the function comes out the same. How to solve this problem? -
Range of models ORM django
how can I add range base ORM of some models? from .models import UsersLog if request.method == 'POST': login = request.POST.get('flogin') response_data = {} response_data['result'] = 'Failed' lengthBase = UsersLog.objects.get() for i in lengthBase: // I got 3 users so I want lengthBase equal 3 -
intellisense python suggestion
hey everybody i'm just started learning django and have a problem with vs-code it's seems that vs-code dosent suggest me some of the modules which i called in the program enter image description here as you can see vs-code should start to suggesting me name of the lists that i wrote before in the modules but it wont do the job ps: my cousin doing same thing but his vs-code seems to do the job perfectly -
Parse the request data in viewset and send it to different serializers in Django REST Framework
I have a problem with parsing request.data in viewset. I have a model that can add multiple images depending on a product. I want to split the image from the incoming data, send product data to ProductSerializer, and after that send image to its serializer with product data and save it. I have two model, simply like this: def Product(models.Model): name = models.CharField(max_length=20) color = models.ForeignKey(Color, on_delete=models.CASCADE) def Color(models.Model): name = models.CharField(max_length=15) def Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='product_pics/') The request I want to send to the Product (127.0.0.1:8000/products/) is simply like: { "name": "strawberry", "color": { "name": "red" }, "productimage_set": [ {"image": "<some_encode_image_data>"} ] } There is nothing special in the serializer, it just extracts the tags link, so I did not write it. How do I send multipart/form-data and how can I parse it in the viewset? or what is the solution? -
Why user_permissions does not return any thing?
Here is my scenario: from django.contrib.auth import get_user_model from django.contrib.auth.model import Permission, Group from django.contrib.contenttypes.models import ContentType user = get_user_model().objects.create(email='example@google.com') group = Group.objects.create(name='group1') content_type = ContentType.objects.get( app_label=get_user_model()._meta.app_label, model=get_user_model()._meta.model_name ) permission = Permission.objects.create( name='perm1', codename='perm1', content_type=content_type ) group.permissions.add(permission) user.groups.add(group) Question: So why this query doesn't have any results: user.user_permissions.all() Output <QuerySet []> settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
ModelAdmin method stops when I reference too deeply
My model has a bunch of websites, each referencing a set of email_addresses. An email should be sent to the email_address of each website, so the email_message and email_address objects share a ManytoMany relationship. I would like to access the properties of the website of the email_address of the email_message, and I would like to do this in the ModelAdmin of an email_message. So there are multiple levels of references being used here. This is a highly simplified version of my code so please let me know if you need to see something I've omitted. models.py class Email_message(models.Model): email_addresses = models.ManyToManyField(Email_address, related_name='email_messages') subject = models.CharField(max_length=50) body = models.TextField() date_time = models.DateTimeField(null=True, blank=True) class Email_address(models.Model): address = models.EmailField() contact_name = models.CharField(max_length=50, null=True, blank=True) website = models.ForeignKey(Website, on_delete=models.CASCADE, related_name='email_addresses', null=True) class Website(models.Model): domain = models.URLField(default=None) searches = models.ManyToManyField(Search, related_name='websites', blank=True) def __str__(self): return self.domain @property def get_likely_location(self): searches = self.searches.all() locations = [] for search in searches: if search.location is not None: locations.append(search.location) return max(set(locations), key = locations.count) admin.py class Email_messageAdmin(admin.ModelAdmin): fields = ['id', 'email_addresses', 'date_time', 'subject', 'body', 'preview_random_email'] readonly_fields = ['id', 'preview_random_email'] def preview_random_email(self, obj): print("This always prints") test = obj.email_addresses.first().searches.all() print("If things are working, this will print") return format_html(test) I'd … -
Django. Where from my forms.py shall know, that the user has changed the application language?
I have a working application in English. I have started translating it into second language. I have created a language selection menu, which changes the language and it works for templates. In order to translate the fields in the tables (models) I have installed django-modeltranslation and translated all the fields via admin interface. The problem is that my forms.py returns always english text and does not switch to the second language irrespective of the language settings. from django import forms from .models import Application from django.utils.translation import gettext as _ class InputDataWaterForm(forms.Form): '''Application''' choices = list(Application.objects.values_list('id','application')) application = forms.ChoiceField(choices = choices, initial="1", label=_("Specify application:")) ... With the function translation.get_language() in the forms.py I see that the language setting within my forms.py is always en-us. When I force language change within the forms.py via translation.activate("ru"), it perfectly works. Where from my forms.py shall know, that the user has changed the application language? Thank you. -
Cyrillic turned to a question mark | Django template HTML metatags
So after deployment my cyrillic description in html metatags turned into question marks. It works fine on my localhost. Im passing html metatags through admin panel as a model so I can change my metatags after deployment easily, in addition to internationalization purposes. Using MySQL Django 2.2.5/Python 3.7.5 models.py class Metatags(models.Model): metatags_en = models.TextField(verbose_name='English Metatags', null=True) metatags_ru = models.TextField(verbose_name='Russian Metatags', null=True) metatags_uz = models.TextField(verbose_name='Uzbek Metatags', null=True) metatags_oz = models.TextField(verbose_name="O'zbek Metatags", null=True) metatags_en_blog = models.TextField(verbose_name='English Blog Metatags', null=True) metatags_ru_blog = models.TextField(verbose_name='Russian Blog Metatags', null=True) metatags_uz_blog = models.TextField(verbose_name='Uzbek Blog Metatags', null=True) metatags_oz_blog = models.TextField(verbose_name="O'zbek Blog Metatags", null=True) class Meta: verbose_name_plural = _("Metatags") base.html {% for x in metatags %} {% if current_lang == 'en' %}{{x.metatags_en|safe}} {% elif current_lang == 'ru' %}{{x.metatags_ru|safe}} {% elif current_lang == 'uz' %}{{x.metatags_uz|safe}} {% elif current_lang == 'oz' %}{{x.metatags_oz|safe}} {%else%}{{x.metatags_ru}} {%endif%} {%endfor%} metatags I'm using in cyrillic <!-- Primary Russian Meta Tags --> <meta name="title" content="Лорем ипсум долор"> <meta name="description" content="Лорем ипсум долор сит амет, пер цлита поссит ех."> <meta name="keywords" content="Лорем ипсум долор сит амет"> <meta name="robots" content="index, follow"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="revisit-after" content="1 days"> <meta name="author" content="Лорем">