Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
changing login redirect url from django view
i'm trying to solve a test that wants me to change just view of a written django project. the test says to (1) change the view to redirect to login page if user is not logged in and (2) redirect to a specific page. i have solved the first part by using @login_required decorator but it takes me back to the previous url but i want it to take me to for example "list_seats" named url just with changing view. here is the view i'm working on: @login_required(login_url = '/login') def reserve_seat(request, movie_id, seat_id): if(request.user.is_authenticated): movie = get_object_or_404(Movie,pk=movie_id) seat = get_object_or_404(Seat,pk=seat_id) ticket = Ticket.objects.create(user = request.user,movie = movie,seat = seat) return redirect('list_seats',movie_id = movie_id) else: return redirect('login') i guess i should add add redirect_field_name argument but i don't know how exactly i should do that. -
Overriding get method in class based view with super()
I created a view that manages the products which belong to the current log-in user (so the current user can watch its own products): class product_list(View): def get(self, request, *args, **kwargs): products = Product.objects.get(user=self.request.user) #... I would like to subclass another view from it, which manages the products that belong to a user specified as a GET parameter in the url (probably different to the current user). Is it possible to do it with super() and overriding the method in product_list? Something like this: class product_list_from_user(product_list): def get(self, request, *args, **kwargs): #not sure what code if necessary to put here... super().get(self, request, *args, **kwargs): #or here #... Basically, how can I override the get method from product_list , changing only "self.request.user" by the parameter taken from the URL -
How to set a max/min length to django regex url parameter? [duplicate]
This question already has an answer here: Reference - What does this regex mean? 1 answer I want to set a min length of 9 chars to my django (1.11) url. url(r'^book/(?P<slug>\w.+)', views.bookDetails), I tried this: url(r'^book/(?P<slug>\w{9,}.+)', views.bookDetails), It doesn't work. How can I set what I want to my group (slug)? -
Why is it not recommended to change settings specified in settings.py in running Django website?
When working on my Django-Website I came across Djangos recommendation to explicitly NOT change settings specified in the settings.py file, while your website is running. Out of curiosity I would like to know, whats the reason behind this. -
Pillow not installed in heroku server
After I include the command "release: python manage.py migrate" in my Procfile I am getting the following error when I push the files to heroku: Cannot use ImageField because Pillow is not installed. remote: HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". Then I added Pillow to my Pipfile: [[source]] url = "https://pypi.python.org/simple" verify_ssl = true [packages] django = "*" gunicorn = "*" django-heroku = "*" django-crispy-forms = "*" django-multiselectfield = "*" django-session-timeout = "*" Pillow = "*" [requires] python_version = "3.6" I did run the command "git add Pipfile Pipfile.lock" and pushed to heroku and the error still there. -
Django Query: get() returns multiple values for unique entry
So perhaps it's the way I've coded this. I am making a basic translation app. Im using djongo to have django work with mongo db. On a post request, I take in a from_language, a to_language and a text_to_translate. The following query returns results where text_to_translate is an substring. I just want it to get the result that fits EXACTLY "Hey", nothing more or less. translation = models.Translation.objects.get(**{from_language: text_to_translate}) e.g. If I search with: text_to_translate : Hey from_language : english I get: hey, hey how are, hey are you ... as results. So basically every result where text_to_translate is a substring for a given language. I've tried the code below, and it works to get the correct result. translation = models.Translation.objects.filter(**{from_language: text_to_translate}) but this is REALLY slow at even 1700 translations stored. -
Django import-export KeyError: u'id'
Couldn't able to exclude the ID, even tried with the existing question in stackoverflow: django-import-export: cannot exclude id field during import : KeyError: u'id' #resource.py from import_export import resources from .models import Bugdata class BugDataResource(resources.ModelResource): class Meta: model = Bugdata skip_unchanged = True report_skipped = True exclude = ('id',) import_id_fields = ['Created_date', 'BugID', 'ID_Link', 'Summary', 'Status', 'Severity', 'Tags'] #models.py from django.db import models class Bugdata(models.Model): Created_date = models.DateField() BugID = models.CharField(max_length=50,primary_key=True) ID_Link = models.URLField(max_length=300) Summary = models.CharField(max_length=600) Status = models.CharField(max_length=10) Severity = models.CharField(max_length=10) Tags = models.CharField(max_length=10) def __str__(self): return self.Summary #admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import Bugdata # Register your models here. @admin.register(Bugdata) class NewtaskAdmin(ImportExportModelAdmin): pass Error: Traceback (most recent call last): File "C:\Users\gomathis\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django_import_export-1.0.1-py3.6.egg\import_export\resources.py", line 453, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\gomathis\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django_import_export-1.0.1-py3.6.egg\import_export\resources.py", line 267, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\gomathis\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django_import_export-1.0.1-py3.6.egg\import_export\resources.py", line 261, in get_instance return instance_loader.get_instance(row) File "C:\Users\gomathis\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django_import_export-1.0.1- py3.6.egg\import_export\instance_loaders.py", line 31, in get_instance field = self.resource.fields[key] KeyError: 'id' -
Python/Django duplicated data ins xls when i click second time
I have a form where i can generate 2 xls based in information of other 2 xls. In the first time i click in "Gerar", works fine ( the xls's are generate with the correct data). But if i click in this button again, the data in the xls generated looks duplicated, and if i click again, triplicated, and continue with this behavior while i not restart the page. I tried all the ways to erase this of memory after click, but unsucefully. (sorry for my bad english) the view class Generate(LoginRequiredMixin, SessionMixin, TemplateView, base.View): def post(self, request, *args, **kwargs): empresas = { 'emp1': '4738', 'emp2': '', 'emp3': '1781', 'emp4': '559', } recarga = None utilizacao_1 = None utilizacao_2 = None empresa_nome = None data_inicio_utilizacao = None data_termino_utilizacao = None recarga = request.FILES.get('file_recarga_upload', False) utilizacao_1 = request.FILES.get('file_utilizacao_1_upload', False) utilizacao_2 = request.FILES.get('file_utilizacao_2_upload', False) empresa_nome = request.POST.get('empresa', False) data_inicio_utilizacao = request.POST.get('data_inicio', False) data_termino_utilizacao = request.POST.get('data_termino', False) data_inicio_utilizacao = datetime.datetime.strptime(data_inicio_utilizacao, '%Y-%m-%d') data_termino_utilizacao = datetime.datetime.strptime(data_termino_utilizacao, '%Y-%m-%d') if empresa_nome: empresa_codigo = empresas[empresa_nome] if recarga and utilizacao_1: if utilizacao_2: arquivo_recarga = ArquivoUpload(recarga, 'tmp/planilha_recarga.xls') arquivo_utilizacao_1 = ArquivoUpload(utilizacao_1, 'tmp/planilha_utilizacao_1.xls') arquivo_utilizacao_2 = ArquivoUpload(utilizacao_2, 'tmp/planilha_utilizacao_2.xls') zipped_file = get_arquivo_zip_com_planilhas_sitpass( empresa_nome=empresa_nome, empresa_codigo=empresa_codigo, dia_inicio_utilizacao=data_inicio_utilizacao, dia_termino_utilizacao=data_termino_utilizacao, path_recarga=arquivo_recarga.path, path_utilizacao_1=arquivo_utilizacao_1.path, path_utilizacao_2=arquivo_utilizacao_2.path ) os.remove(arquivo_recarga.path) os.remove(arquivo_utilizacao_1.path) os.remove(arquivo_utilizacao_2.path) os.remove(zipped_file.name) … -
Script behaves differently when run from cron job and from command line using django manage.py when using a cron supervisor
I know crons run in a different environment than command lines, but I'm using absolute paths everywhere and I don't understand why my script behaves differently. I believe it is somehow related to my cron_supervisor which runs the django "manage.py" within a sub process. Cron: 0 * * * * /home/p1/.virtualenvs/prod/bin/python /home/p1/p1/manage.py cron_supervisor --command="/home/p1/.virtualenvs/prod/bin/python /home/p1/p1/manage.py envoyer_argent" This will call the cron_supervisor, and it's call the script, but the script won't be executed as it would if I would run: /home/p1/.virtualenvs/prod/bin/python /home/p1/p1/manage.py envoyer_argent Is there something particular to be done for the script to be called properly when running it through another script? Here is the supervisor, which basically is for error handling and making sure we get warned if something goes wrong within the cron scripts themselves. import logging import os from subprocess import PIPE, Popen from django.core.management.base import BaseCommand from command_utils import email_admin_error, isomorphic_logging from utils.send_slack_message import send_slack_message CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = CURRENT_DIR + '/../../../' logging.basicConfig( level=logging.INFO, filename=PROJECT_DIR + 'cron-supervisor.log', format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) class Command(BaseCommand): help = "Control a subprocess" def add_arguments(self, parser): parser.add_argument( '--command', dest='command', help="Command to execute", ) parser.add_argument( '--mute_on_success', dest='mute_on_success', action='store_true', help="Don't post any massage on success", ) def handle(self, *args, **options): … -
Django Rest Framework: How to implement a nested logic?
Let's say I have three models as: class User(AppModel): name = models.CharField(max_length=255) class Business(AppModel): owner = models.ForeignKey("User", related_name="businesses", on_delete=models.CASCADE) legal_name = models.CharField(max_length=255) class Invoice(AppModel): business = models.ForeignKey("Business", related_name="invoices", on_delete=models.CASCADE) amount = models.integerField() As you can see, a user can have multiple businesses and a business can have multiple invoices. My serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields= ('name') class BusinessSerializer(serializers.ModelSerializer): owner = UserSerializer(many=False) class Meta: model = Business fields= ('owner','legal_name') class InvoiceSerializer(serializers.ModelSerializer): business= BusinessSerializer(many=False) class Meta: model = Invoice fields= ('business','amount') views.py: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class BusinessViewSet(viewsets.ModelViewSet): queryset = Business.objects.all() serializer_class = BusinessSerializer class InvoiceViewSet(viewsets.ModelViewSet): queryset = Invoice.objects.all() serializer_class = InvoiceSerializer urls.py: router = DefaultRouter() router.register('user', UserViewSet, base_name='users') router.register('business', BusinessViewSet, base_name='businesses') router.register('invoice', InvoiceViewSet, base_name='invoices') urlpatterns = router.urls http://example.com/api/user returns all users. Not a problem. But the functionality I'm looking for is: http://example.com/api/business/ returns [ { "legal_name": "1business", "owner": 1, }, { "legal_name": "2business", "owner": 1, },] http://example.com/api/business/1/ returns { "legal_name": "1business", "owner": 1, } The above is ok. But I also need: http://example.com/api/business/1/invoices/ should return [ { "business": 1, "amount": 100, }, { "business": 1, "amount": 999, },] As well I should be able to create update delete those invoices there. Any Help? … -
base.html isnt accessing the static files in django
I am encountering an error with accessing my static files when i make different request from the nav of my website . it basically accessing the static files when i load the index page www.xxxx.com/static_url(from my settings.py) but when i make a request from www.xxxx.com/path it goes to www.xxxx.com/path/static_url which is 404 i have nothing there. how can i maintain this ? in the base.html <link rel="stylesheet" href="{% static 'css/main.css' %}"> header.html <li class="nav-item"><a class="nav-link" href="{% url 'files:documents' %}">name</a></li> -
apache + mod_wsgi restart keeping active tasks
Im running my django project using apache + mod_wsgi in daemon mode. When I have to make the server notice changes in the source code, I touch the wsgi.py file, but I have an issue with this approach. Some tasks that are triggered from the front-end take 10 minutes to complete. If I touch the wsgi file while one of this long tasks are running, they get killed by the restart. Is there any way to make the server to refresh the code, but keeping the previous unfinished tasks running until the are done? Thanks! -
Going fullstack with the following: Bootstrap, ReactJS, Django (Python)
I browsed around a lot here on stackoverflow and many other pages, blogs, articles. I am relatively new to web development, what I feel comfortable right now after a year investing are the web languages HTML, CSS, plain JS (currently on jQuery) and basic usage of Pyhton (currently trying to understand ajax - not as easy as thought initially... ). I found many topics regarding which framework is better than another and why not. My question however is, which frameworks suit best to fit in my current knowledge-base. To redefine this a bit more: What I want to do is, to create a neat, but basic site with bootstrap (status: check), and generate all different pages (about, contact, etc.) through the backend, not linking html files to each other as I do now [this is the missing link, which framework here? Which one is "easy to understand"]. If, one day, I am able to do so, I would like to render the html content through ReactJS. Could any of you recommend a framework that helps to organise couple of sites for easier site maintenance (flask? django? nodejs? non of this at all?). Feel free to refer to wrong associations in … -
Django how to render dictionary in the template
i have this dictionary data={'user': user.username, 'punti_capitano': {'nome_capitano':team.capitano.display_name,'lista_punti':point_cap_list}, 'punti_rider2': {'nome_rider2':team.rider_2.display_name,'lista_punti':point_rider2_list}, 'punti_rider3': {'nome_rider3':team.rider_3.display_name,'lista_punti':point_rider3_list}, 'punti_rider4': {'nome_rider4':team.rider_4.display_name,'lista_punti':point_rider4_list}, 'punti_rider5': {'nome_rider5':team.rider_5.display_name,'lista_punti':point_rider5_list}, 'punti_rider6': {'nome_rider6':team.rider_6.display_name,'lista_punti':point_rider6_list}, 'punti_rider7': {'nome_rider7':team.rider_7.display_name,'lista_punti':point_rider7_list}, 'punti_rider8': {'nome_rider8':team.rider_8.display_name,'lista_punti':point_rider8_list}, 'punti_rider9': {'nome_rider9':team.rider_9.display_name,'lista_punti':point_rider9_list}, } how can i create a table with all these elements? -
Using a single form in the template to check the answers for multiple questions in django
Introduction I am trying to build a website with Django where the users can answer questions based on a particular topic. The Problem There is a model Question which holds the question along with the choices and the answer for the question. So if the topic is Food and there are 5 questions with the same topic in the database. Using pagination the questions are displayed in HTML (There's a single question per page). I am not able to figure out how to check for the answer for multiple questions submitted at the end of the quiz in the view when I am using just a single form in the template. Models.py class Question(models.Model): sl_num = models.IntegerField(blank=True) question = models.TextField(max_length=2000, blank=False) answer = models.CharField(max_length=500, blank=False) option_A = models.CharField(max_length=500, blank=False) option_B = models.CharField(max_length=500, blank=False) option_C = models.CharField(max_length=500, blank=False) option_D = models.CharField(max_length=500, blank=False) subject = models.CharField(max_length=100, blank=True) topic = models.CharField(max_length=100, blank=True) def __str__(self): return self.question The Template {% block body %} <h1>Questions for {{ exam }}</h1> <p><a href="#">Here are the questions</a></p> {% for question in questions_list %} <p>{{question.sl_num}}. {{ question.question }}</p> <form> <input type="radio" name="answer" value="{{ question.option_A }}"> {{ question.option_A }}<br> <input type="radio" name="answer" value="{{ question.option_B }}"> {{ question.option_B }}<br> <input type="radio" … -
Query/Create an Notification system of User Actions, where hierarchical FK keys (as parent/owners) exist
I have the following Models: class Prod(models.Model): acc = models.ForeignKey(Acc,on_delete=models.CASCADE) class Acc(models.Model): user = models.OneToOneKey(User,on_delete=models.CASCADE) class Note(models.Model): action = models.CharField( max_length=35) sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) receiver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) status = models.BooleanField(blank=True, null=True) class Item(models.Model): note = models.ForeignKey(Note, on_delete=models.CASCADE, ) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) acc = models.ForeignKey(Acc, blank=True, null=True, on_delete=models.CASCADE) prod = models.ForeignKey(Prod, blank=True, null=True, on_delete=models.CASCADE) def save(self, *args, **kwargs): ...... Note.objects.filter(id=self.note_id).update(recipient=self.parent) In a utility/function I'm creating the instances of the Model above: note = Note.objects.create(action=action, sender=sender) transaction.on_commit(lambda: Item.objects.create(note=note,target=target) The issue that I have is that are situations when the 'same' Note is created again. I want to create a new Note, if a Note with the same action, receiver doesn't exist. In db: Item id | note_id | user_id | acc_id | prod_id 1 1 1 2 5 2 2 2 - - 3 3 2 3 - Note id | sender_id | receiver_id | action | status 1 1 1 c true 1 2 2 u null 1 3 2 c false If a new Note/ActionObject has: the same action status not True if prod_id exist, prod_id not to be the same if prod_id doesn't exist, but exist acc_id, acc_id not to be the … -
Django download file set correct name
Right now I use the following function for downloading files: def download_xlsx(request): user = request.user file_name = request.GET['file_name'] file_path='main_app/static/xlsx/' + str(user.id) + '/' + file_name if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = "inline; filename=%s" % file_name return response Using the following url http://127.0.0.1:8000/download_xlsx?file_name=test.xlsx I downloaded file named 'download_xlsx' I tried to write something like this: response['Content-Disposition'] = "inline; filename='+ file_name But didn't help. How do I rename my file to file_name var ? -
Django: Getting models with apps.get_model on models.py
On circular import of Django Is their any way i can grab a model object with myModel = apps.get_model('app_name', 'model_name') inside models.py file ? I know i can use models.ForeignKey('app.model',....) But in my case i am making a query in the models.py for custom function. So that i need to grab the model object. Also can't import it in normal way as already imported this file class in the other file. So must be a circular import. This code myModel = apps.get_model('app_name', 'model_name') works fine on views.py but in models.py doesn't. Since according to django the all models.py get called after settings.py and after that views and others. so while trying to use get_model inside models.py getting this error File "/home/mypc/.virtualenvs/VSkillza/lib/python3.6/site-packages/django/apps/registry.py", line 132, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Thanks in advance :) -
Django SQLite view returns Empty Queryset []
Hi I'm new to Django / SQLite and i'm getting an empty qurty set when i read from a view. Other tables and views that i've created are behaving normally. when i use DB Browser for SQLite, I can see the data is there. #nmsdb_app.models.py class V_WSW_Table_People_Chooser(models.Model): Username = models.CharField(max_length=31) Record_ID = models.CharField(max_length=11) Display_Text = models.CharField(max_length=255) objects = UserManager() def __str__(self): return self.Username #stop django from trying to treat sql views as tables class Meta: managed = False python manage.py shell: from nmsdb_app.models import V_WSW_Table_People_Chooser V_WSW_Table_People_Chooser.objects.all() <QuerySet []> to make the view on the SQLite server: 1. do the model 2. makemigrations 3. migrate 4. drop the SQLIte table and replace with the view 5. add managed = False to the model class I've tried the Record_ID field as Text and Integer but it makes no difference. When i use DB Browser for SQLite, the view data appears correctly. Any help received with thanks. -
Django tenant how work with gunicorn and nginx?
I have a django application on my nginx server. I use gunicorn to run it. In my nginx.conf i set: location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } Well at this point i install django-tenant-schemas for manage tenants, i create my two tenants, 'public' for localhost e 'tenant1' for test.mydomain.com (with relative postgrees schemas) Now, in every case i reach my website django propose ever my public schema, wheter i reach it using mydomain.com or test.mydomain.com. Is because nginx use as location for / 127.0.0.1:8000 (localhost)? How can i use tenants correctly in my application? Thanks in advance -
Do I have to define var as Decimal?
I know, platform_fee_percentage will always be an decimal (called form the database). Is it necessary that I define Decimal explicitly, or will pyhton always give it the type Decimal? If not, the function quantize would fail. def calculate_application_fee(platform_fee_percentage, total_gross): calculate_application_fee = Decimal(platform_fee_percentage * total_gross) application_fee = quantize(calculate_application_fee, '1') return application_fee -
What should I test in a CreateView?
I'm currently writing some tests in Django. I have a CreateView which creates a new product. The product has fields like: Name Price Currency Start product sale at Description etc. I'm a bit confused what I should test here. I have a test_views.py file and a test_forms.py file Should I place tests like "Is the price greater than 0" and "Is the start date not in the past" in the test_views.py or in the test_forms.py or both? -
Wagtail add page between two existing pages
I'm using wagtail in a django application with a graphql interface. Wagtail is only the backend and I'm implementing an editor with vuejs and a graphql interface using graphene. I'd like to add a new page between two existing pages. The page order depends on the path parameter of the page. Is it possible to achieve this without manipulating the path param? I can change the path param of the pages in wagtail, but this seems to me to be error prone and not as the creators of wagtail intended to be done. -
Django "settings.DATABASES is improperly configured" and "ImproperlyConfigured at /i18n/setlang/"
I wrote a django web application and now I need to translate it to english. I followed the documentation but I keep getting this strange error: ImproperlyConfigured at /i18n/setlang/ settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Request Method: POST Request URL: http://192.92.149.139:8000/i18n/setlang/ Django Version: 2.0.3 Exception Type: ImproperlyConfigured Exception Value: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Exception Location: /home/mwon/venvs/arquivo/lib/python3.6/site-packages/django/db/backends/dummy/base.py in complain, line 20 Python Executable: /home/mwon/venvs/arquivo/bin/python3.6 Python Version: 3.6.4 Python Path: ['/home/mwon/digitalocean/website_dev', '/home/mwon/venvs/arquivo/lib/python36.zip', '/home/mwon/venvs/arquivo/lib/python3.6', '/home/mwon/venvs/arquivo/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/mwon/venvs/arquivo/lib/python3.6/site-packages', '/home/mwon/venvs/arquivo/lib/python3.6/site-packages/django_styleguide-1.2.5-py3.6.egg', '/home/mwon/venvs/arquivo/lib/python3.6/site-packages/Markdown-2.6.11-py3.6.egg', '/home/mwon/venvs/arquivo/lib/python3.6/site-packages/bs4-0.0.1-py3.6.egg', '/home/mwon/venvs/arquivo/lib/python3.6/site-packages/beautifulsoup4-4.6.0-py3.6.egg', '/home/mwon/venvs/arquivo/lib/python3.6/site-packages/duc_preprocess-1.0-py3.6.egg', '/home/mwon/venvs/arquivo/lib/python3.6/site-packages/simple_cnlp-1.0-py3.6.egg', '/home/mwon/venvs/arquivo/lib/python3.6/site-packages/django_mongoengine-0.3-py3.6.egg'] Server time: Qua, 5 Set 2018 11:21:17 +0000 This is my urls.py: urlpatterns = [ path('i18n/',include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('admin/',admin.site.urls), path('',include('arquivo.urls')), prefix_default_language = True ) and settings.py: LANGUAGE_CODE = 'pt' LANGUAGES = ( ('en', 'English'), ('pt', 'Portuguese'), ) USE_I18N = True LOCALE_PATHS = [ os.path.join(BASE_DIR,'locale') ] The translation seems to be working fine. The problem was when I included a form to select the language. I used the example code from documentation: {% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% … -
Mongoengine python3 Embedded Document has no attribute _is_document
I am creating my a document having a field as EmbeddedDocument using mongoengine. But I am getting the following error : AttributeError: 'EmbeddedDocument' object has no attribute '_is_document' Doing some reasearch I found that the code of mongoengine is written in python 2 and do make it work properly install it using pip3. Did the same still not working. class DataImportNodeInfo(EmbeddedDocument): provider_id = fields.IntField(required=False) carrier_name = fields.StringField(required=False) basepath = fields.StringField(required=False) log_tobe_imported = fields.ListField(required=False) class DataImportConnectionInfo(EmbeddedDocument): host = fields.StringField(required=True) user_login = fields.StringField(required=False) user_pwd = fields.StringField(required=False) class DataImportNode(DynamicDocument): # Meta variables meta = { 'collection': str(KonnectDAConstants.DATA_IMPORT_NODES) } cmd = fields.StringField(required=True) import_source = fields.StringField(required=True) import_type = fields.StringField(required=True) active = fields.BooleanField(required=True) info = fields.EmbeddedDocument(DataImportNodeInfo, required=True) connection = fields.EmbeddedDocument(DataImportConnectionInfo, required=True) AttributeError: 'EmbeddedDocument' object has no attribute '_is_document'