Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Images inside conditional template tags
I'm trying to display an image based on certain conditions in a Django template, but Django doesn't seem to like use of the static tag within a condition. Code as follows: <td> {% if result.threshold == "normal" %} <img src="{% static "face-green-small.jpg" %}" alt="Green"/> {% endif %} {% if result.threshold == "high" or result.threshold == "low" %} <img src="{% static "face-amber-small.jpg" %}" alt="Amber"/> {% endif %} {% if result.thresdholf == "vhigh" or result.threshold == "vlow" %} <img src="{% static "face-red-small.jpg" %}" alt="Red"/> {% endif %}"> </td> The error I'm getting is: Invalid block tag on line 32: 'static', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? I'm sure static is registered, because it's being used earlier in the template. Any guidance on what I'm doing wrong would be appreciated. -
Creating docker secrets with user variables within django
I have django application that uses docker to create sessions using some user inputs. The spec for the services look something like this: { "Name": "dummy_service", "TaskTemplate": { "ContainerSpec": { "Image": REGISTRY_HOST + '/' + DEFAULT_IMAGE + ':latest', "Command": ["start-notebook.sh"], "Env": [LIST OF ENV VARS], "User": "root" }, "RestartPolicy": { "Condition": "on-failure", "Delay": 10000000000, "MaxAttempts": 10 }, }, "Mode": { "Replicated": { "Replicas": 1 } }, "EndpointSpec": { "Ports": [ { "Protocol": "tcp", "TargetPort": 8888 } ] } } I would like to create a secret for any variables that the user wants so that if somebody gets hold of my docker credentials they cannot view a users secrets by simply looking at the environment variables of their session. The user would give these to us through a POST request using a password form input. Their secret would be in a variable contained in something like this requests.POST['some_private_name'] in the back end of the application. Is this possible? -
Editing fields in Django admin when "Save as New"
I'm trying to blank some fields when a user in the Django admin clicks "Save as New", but it doesn't seem to be working. Ar first I was just calling obj.save(), but it complained their was no request object, so I passed in the request object. Now the new item saves as expected, but if I don't click "Save as New", and just click "Save", I get an IntegrityError: "duplicate key value violates unique constraint". Leading me to believe it's trying to save the existing object with the same pk? Here is the relevant code that lives in my admin.py: def save_model(self, request, obj, form, change): if '_saveasnew' in request.POST: original_pk = resolve(request.path).args[0] original_obj = obj._meta.concrete_model.objects.get(id=original_pk) for prop, value in vars(original_obj).items(): print(prop) if prop == 'submitter_email_address': setattr(obj, prop, None) if prop == 'submitted_by_id': setattr(obj, prop, None) if isinstance(getattr(original_obj, prop), FieldFile): setattr(obj, prop, getattr(original_obj, prop)) obj.save(request) I got the relevant code from this question and edited it to what I need: Django "Save as new" and keep Image fields -
django-s3-storage: Use protected and public files in one project (AWS_S3_BUCKET_AUTH)
I`m using django-s3-storage. I want to use files with and without authentication in one project. So I created two storage classes and set AWS_S3_BUCKET_AUTH to True or false after initial setup from django_s3_storage.storage import S3Storage class S3StoragePublic(S3Storage): def _setup(self): super()._setup() self.settings.AWS_S3_BUCKET_AUTH = False class S3StorageProtected(S3Storage): def _setup(self): super()._setup() self.settings.AWS_S3_BUCKET_AUTH = True Is there a better way of doing this? Or is this how it should be done? -
Django: Make user email required
For my application the email field of a User should be required. That's not the case for the default User model. So I thought it would make sense to create a custom user model as described in the docs: If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises: from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(_('email address'), blank=False) However, I am not sure if that's the correct way to achieve this. The reason is that here the Django docs say: Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class. It is an error to have fields in the abstract base class with … -
Django: Automatically selecting related UseRProfile when retrieving User model
When showing {{ user }} in a Django template, the default behavior is to show the username, i.e. user.username. I'm changing this to show the user's initials instead, which are stored in a separate (OneToOneField) UserProfile model. So in customsignup/models.py I've overridden the __unicode__ function successfully, with the desired result: # __unicode__-function overridden. def show_userprofile_initials(self): return self.userprofile.initials User.__unicode__ = show_userprofile_initials But of course, the database is hit again because it needs to independently select the UserProfile model every time a user object is asked to show itself as a string. So even though this works, it escalates the number of database hits quite a bit. What I'm trying to do is modify the manager of the User model after it has been defined by the Django library. So I'm in no control over the User model definition itself. I'm attempting to override an existing model manager. So I've tried overriding the objects member of the User model in the same way that I overrode the __unicode__ function, like so: # A model manager for automatically selecting the related userprofile-table # when selecting from user-table. class UserManager(models.Manager): def get_queryset(self): # Testing indicates that code here will NOT run. return super(UserManager, self).get_queryset().select_related('userprofile') … -
Add Properties To Class At Runtime
Is it possible to add a property to an instance of a class at runtime? This is for Django and it'd model objects but it'd be a great tool to have if this would work on any python class outside of Django. e.g. class person(models.Model) firstname=models.CharField(max_length=100) lastname=models.CharField(max_length=100) def main(): p = person() p.fisrtsname="Firsty" p.lastname="Lasty" p.addnewproperty(newtemporaryproperty) p.newtemporaryproperty="This is a new temporary property" when i use person.newtemporaryproperty=property("") i get a "Can't set attribute error" when trying to add a value to it. I may be using it wrong. -
DRF check if an object already exist in DB when receiving a request
I have products defined by their Name and Location. Each product has a unique pair of Name/Location. I'm writing a view to be able to create a product and I would like to first check if it exists in DB. If yes then keep the ID somewhere to return it to my front app. If no then create it and get the ID also. From my research, overriding the perform_create method should be the solution but I can't figure out how to. Any help would be appreciated. urls.py from django.conf.urls import url from main.views import product_view urlpatterns = [ url(r'^products/$', product_view.ProductCreate.as_view()), url(r'^products/(?P<pk>[0-9]+)/$', product_view.ProductDetail.as_view()), ] product_view.py from rest_framework import generics from rest_framework import permissions from main.models import Product from main.serializers import ProductSerializer class ProductCreate(generics.CreateAPIView): """ Create a new product. """ permission_classes = (permissions.IsAuthenticated,) serializer_class = ProductSerializer queryset = Product.objects.all() def perform_create(self, serializer): product_name = serializer.validated_data['product_name'] product_location = serializer.validated_data['product_location'] if product_name != '': product_list = Product.objects.filter( product_name=product_name, product_location=product_location) if not product_list: product = <my function to create the product> else: product = product_list[0] # I have no idea how to handle the following # serializer.save(...) # else: # Raise an error class ProductDetail(generics.RetrieveUpdateAPIView): """ Retrieve, update or delete a product. """ permission_classes … -
How to do price filter in django internetshop?
I downloaded free template for internetshop and there is a price slider: <div class="price-range"><!--price-range--> <h2>Price Range</h2> <div class="well text-center"> <input type="text" class="span2" value="" data-slider-min="0" data-slider-max="600" data-slider-step="5" data-slider-value="[250,450]" id="sl2" ><br /> <b class="pull-left">$ 0</b> <b class="pull-right">$ 600</b> </div> </div><!--/price-range--> How can i re write it with django to filter items with price ? -
Django: Change a model's attribute field with a form
I have rendered a list of objects in my page. Each one has an edit button next to it that you can click on, that brings up a modal window, to change the name of the model field. The model: class SensorParameter(models.Model): sensor = models.ForeignKey(Sensor) parameter = models.ForeignKey(Parameter) parameter_name_userdef = models.CharField(max_length=100, blank=False, default="Parameter") live_value = models.FloatField() Live value comes from somewhere else. Sensor and Parameter are keys to build a unique table of parameters that belong to sensors. The field I need the user to be able to edit is parameter_name_userdef where the end user can change a machine generated string to whatever they want (from "MhzV13.65Hp" to "FOO", for example). I have tried with a form, but I can't quite get it to work. I think the form is not grabbing the particular instance of the object, but instead it's instantiating a new object from the model. The form: class CustomParameterForm(ModelForm): class Meta: model = SensorParameter fields = ['parameter_name_userdef'] I only provide the value they can change. The objects are built into a table, that looks like this in the template: <tbody> {% for parameter in sensor_parameters %} <tr class="text-left"> <td class="text-center"><span>{{parameter.parameter.parameter_name}}</span></td> <td><i data-parameter-id="{{parameter.id}}" data-toggle="modal" data-target="#editCustomParam" class="far fa-edit" title="Edit … -
Tests failed on ForeignKey constraints
I'm creating a custom "upload from csv" function in my Django application, using a custom model.Manager method that receives the result of applying csv.DictReader on the csv data. My tests on normal models are okay, but they are failing on models with ForeignKey constraints. The relevant source codes are as follows models.py class PledgeManager(models.Manager): """Custom manager for model Pledge.""" def from_upload(self, data): """Process data from Pledge upload.""" for obj in data: try: # get the prospect & fund by natural key obj['prospect'] = Prospect.objects.get_by_natural_key( obj['prospect']) obj['pledge_fund'] = Fund.objects.get_by_natural_key( obj['pledge_fund']) obj['pledge_date'] = datetime.strptime( obj['pledge_date'], r'%d/%m/%Y') try: with transaction.atomic(): self.create(**obj) ccall_log.debug('Created Pledge object: %s', obj) except IntegrityError: ccall_log.error('Cannot create Pledge object: %s', obj) except Prospect.DoesNotExist: # no prospect ccall_log.error( 'Cannot create Pledge object, no Prospect: %s', obj) except Fund.DoesNotExist: # no fund ccall_log.error( 'Cannot create Pledge object, no Fund: %s', obj) except BaseException as exc_: ccall_log.exception(exc_) ccall_log.error( 'Exception encountered during processing: %s', obj) class Pledge(models.Model): """Model for a Pledge.""" objects = PledgeManager() pledge_amount = models.DecimalField( verbose_name='Pledge amount', decimal_places=2, max_digits=12, validators=[MinValueValidator(0)]) pledge_fund = models.ForeignKey(Fund, on_delete=models.CASCADE) pledge_date = models.DateField(verbose_name='Pledge date') prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE) test_models.py class TestPledge(TestCase): """Test cases for Pledge.""" @classmethod def setUpTestData(cls): prospect_obj = { 'natural_key': 'Test Prospect', ... } Prospect.objects.create(**prospect_obj) Fund.objects.create(natural_key='Test … -
Django |safe template filter
Is there a way to specify characters that shouldn't be escaped is Django templates. I have the following Copyright® I don't want Django to escape the &reg ; is there a filter to do that? The workaround I've used to prevent XSS attacks is: {{object.title|safe|striptags}} Is there a better solution than this? -
Django forms getlist and valid_form
I am trying to retrieve the list of options in a select multiple (not the values selected but all the items in the choices. I have others have used: request.POST.getlist('assigned_subnets[]') However I am using a updateview and believe I need to get the data in the form_valid function. I have tried a few options to try and get the list (one in the sample below) but none have worked thus far. form valid: def form_valid(self, form): form.instance.site_data = self.site assigned_subnets = form.cleaned_data.getlist('assigned_subnets') print(assigned_subnets) return super(EditDevice, self).form_valid(form) Full form if needed: class EditDevice(UpdateView): model = DeviceData form_class = DeviceForm template_name = "config/device_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_device'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(EditDevice, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("config:device_details", args=(self.site_id,)) def form_valid(self, form): form.instance.site_data = self.site assigned_subnets = form.cleaned_data.getlist('assigned_subnets') print(assigned_subnets) return super(EditDevice, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() kwargs['site_id'] = self.site_id kwargs['device_id'] = self.object.pk return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.site.location context['FormType']='Edit' context['active_devices']='class="active"' context['used_subnets']='class="active"' return context -
change-over system - Rails to Django: how should I treat with `encrypted_password` column in django?
I've decided to move my rails app to django app. What I'd like to know is how to treat with encrypted_password column in django app. In rails, password column is automatically saved as encrypted_password, and there is no password column. I've created User model and in database users table exists. by runnning syncdb method, I could create models.py from existing mysql database. I've set AUTH_USER_MODEL = 'myapp.Users' but mysql_exceptions.OperationalError: (1054, "Unknown column 'users.password' in 'field list'") occurs. -
Django - Generate a pdf with html block text
I'm working on a project with Django (1.12) and python(2.7). I have a function which returns me in a string the content of an html page. I need to create the html page with this string, and after to transform it to pdf (already have the function), but WITHOUT leaving my actual page. I search since this morning on the internet but i don't find something like my case. Does anybody knows if it's possible ? and if yes, how? Thanks, @Nikotine -
Django Template Nested for with If Statement
I'm trying to create a selection box in a HTML table where the given name should be selected in the combo box. In order to do this, I need to create a nested loop. The outer loop creates the rows, whereas the inner loop fills the grid cell with options for "Resources". For this example I'm only showing the code creating the Resource cell. The nested loop creates the items, and contains an if statement comparing the action.owner value with the resource.name value. If the items match, the option value should be selected. The server runs with the code, and I cannot find any hidden problems. However I'm not getting the expected results. No item is being selected. Any idea what I'm doing wrong? {% for action in actions %} <tr> <td> <SELECT class="custom-select" value = "{{action.owner}}"> {% for resource in resources %} <option value = "{{resource.name}}" {% if action.owner == resource.name %}selected="selected"{% endif %}>{{resource.name}}</option> {% endfor %} </SELECT> </td> </tr> {% endfor %} -
Returning information from database through django to UI
Can anyone tell me why information is not being displayed in my html? views.py @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def userprofile(request): data = UserProfile.objects.all() return TemplateResponse(request, 'personalInfo/details.html', {"data": data}) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/$', views.userprofile, name='patient'), ] models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullName = models.CharField(max_length = 250, default='', blank=True) address = models.CharField(max_length = 250, default='', blank=True) gender = models.CharField(max_length = 250, default='', blank=True) dob = models.DateField(blank=True) homePhone = models.CharField(max_length = 250, default='', blank=True) personalPhone = models.CharField(max_length = 250, default='', blank=True) emergencyContact = models.CharField(max_length = 250, default='', blank=True) email = models.CharField(max_length = 250, default='', blank=True) ppsn = models.CharField(max_length = 250, default='', blank=True) maritalStatus = models.CharField(max_length = 250, default='', blank=True) employment = models.BooleanField(blank=True) personalPic = models.CharField(max_length = 250, default='', blank=True) def __str__(self): return self.fullName + ' - ' + self.ppsn I am using {{ userprofile.fullname }} to return the name of the person. I am also using profiles with a one to one link to each user. What I want to happen is when a user is logged in that his own information is displayed of course like a profile. Any help would be appreciated. Thanks. -
How to subtract two django dates in template
I want to get the number of days between today and a model field end_date. I defined today in my view as shown below. I will then use the number of days to check if its less than or equal to 50 which will add a class to the element MY TEMPLATE {% for instance in queryset %} <tr> <td>{{forloop.counter}}</td> <td>{{instance.empnumber}}</td> <td>{{instance.name}}</td> <td>{{instance.be}}</td> <td>{{instance.status}}</td> {% if (today - instance.end_date) <= 50 %} <td class="highlight">{{instance.start_date}}</td> <td class="highlight">{{instance.end_date}} : {{ instance.end_date|timeuntil:today }}</td> {% else %} <td>{{instance.status_start_date}}</td> <td>{{instance.status_end_date}}</td> {% endif %} </tr> {% endfor %} MY VIEW if request.user.is_authenticated(): queryset = Employee.objects.all().order_by('-last_updated') today = date.today() context = { "queryset": queryset, "today": today, } -
Search with ajax + django view
can u please help me. I want to create search using ajax function and django view. There are input and submit button. When I clicked on submit button, jQuery takes value of input and create ajax request. Its good. But in the view, when i want to print serch_by value in console, there is an output: None qwer asdf zxvc <- value of input I think it is a problem. But maybe no. Help me, please. HTML: <form id="searchform" {% csrf_token %} <input name="q" type="text" id="search"> <button type="submit" id="searchsubmit"></button> </form> JS: function initSearchForm(){ $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); updateContentBySearch(q); }); } function updateContentBySearch(q) { var data = {}; data['search_by'] = q data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ url: "/search_products/", type: 'GET', data: data, success: $('.product_content').load(url, function() { ... }), }); } View: def search_products(request): data = request.GET search_by = data.get('search_by') print(search_by) # The console is displayed first 'None' and at the next line value of search_by if search_by: q = Q() for tag in search_by.split(): q |= Q(brand__brand_name__iexact=tag) | Q(model__iexact=tag) products = Product.objects.filter(q) return render(request, 'main/product_content.html', {'products': product}) -
In a tree filter nodes and its childs
I have an app with categories and products, categories and products can be inactive, on inactive category do not show its children, for example: All categories are active, tree looks like this: Category 1-1 Product 1-1 Category 2-1 Product 2-1 Category 3-1 Product 3-1 Category 3-2 Category 2-2 Product 2-2 If I set Category 2-1 to inactive, I want to see result like this: Category 1-1 Product 1-1 Category 2-2 Product 2-2 I have created a method which do a filter, but I am using a recursion, if a tree has a very high deep for example depth=100 and category is inactive in depth = 2, I get max depth recursion error. def filter_category_products(self): inactive_category_ids = get_inactive_categories_ids() queryset = Category.objects.exclude(id__in=inactive_category_ids).prefetch_related(Prefetch('product_set', queryset=Product.objects.filter(is_active=True))) return queryset def get_inactive_categories_ids(): inactive_categories_ids_query = Category.objects.filter(is_active=False).values_list('id', flat=True) inactive_ids = [] for i in inactive_categories_ids_query: inactive_ids.append(i) ids = [] while inactive_ids: for inactive_id in inactive_ids: if(inactive_id not in ids): ids.append(inactive_id) inactive_ids = Category.objects.filter(parent_id__in = inactive_ids).values_list('id', flat=True) return ids My question would be is there any other algorithm how could I filter that without recursion so I would avoid the error and editing max recursion limit in python sys resource. -
Angular 5 + Django - How to handle user permissions
I have an Angular v5 web application backed by Django REST Framework. Previously the application was totally relying on Django templates. Now, I'm using Angular and it is not clear to me how permissions are managed. The application has different sections. Regarding the product section, the permissions can be summed up as follow: Course grain permissions Can the user see a product? Can the user change a product? Can the user delete a product? Can the user create a product? Fine grain permissions Can the user see product SKU? Can the user see product pricing? ... Fine-grained permissions are very important because there're users that can see the product list where on Angular has been implemented as a table, but few users cannot see certain columns. My question is how I can handle permissions on Django and Angular? My idea was, when the user logs in, Angular got from backend all user permissions and then Angular won't show accordingly to the user. Anyway, I don't think this is a safe solution since permissions can easily manipulated by the user from JS console. What's usually the best practice for this? -
Django: foreign key access through related objects
Suppose I have a model Profile that relates to the standard User model through either a ForeignKey with unique=True relationship, or a OneToOne relationship: class Profile(models.Model): user = (either a ForeignKey/OneToOne relationship) ... If I have understood the documentation, the database representation of the column will be user_id, from Django automatically adding _id. This user_id will contain a series of integers. Suppose again I instantiate an object of this model in the shell, and try and access the user attribute: a_profile = Profile() a_profile.user From what I have read, the user attribute should now be a descriptor, and accessing it will invoke it's __ get __ method, giving me access to the related model instance - in this case the User instance. MY QUESTION: I have noticed that I can access the Profile instance through the User instance as well, through: user_profile = User.objects.all()[0] user_profile.profile What is happening here? Is this working the same way as accessing the user attribute of the Profile instance - is the profile attribute on a User instance a descriptor as well? Thank you! -
How to display all session variables in django 2.0?
How to display all session variables in Django 2.0? result, data1 = GetLoginUser(request) request.session['profile']=data1 ipdb> request.session['profile'] [{'address': 'asdfsd', 'email': 'nitesh@scaledesk.com', 'mobile': '9570277820', 'category': 'getpass', 'designation': 'dsfsd', 'name': 'employee'}] ipdb> request.session['profile'][0] {'address': 'asdfsd', 'email': 'nitesh@scaledesk.com', 'mobile': '9570277820', 'category': 'getpass', 'designation': 'dsfsd', 'name': 'employee'} how to print data in template template.html.j2 {{request.session.GET['profile']}} getting error This page isn’t working localhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS -
Django forms - maximum recursion depth exceeded on get_context_data
I'm getting a maximum recursion depth exceeded error on one of my Django forms. The trace is pointing to get_context_data but I am unsure as to why or what the underlying issue is/may be. I use this same code on all my other forms without issue. ive read this is usually due to URLs but I can't seem to find the fault with that either. the add view works which uses almost the same code too traceback is: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/itapp/itapp/circuits/views.py" in dispatch 317. return super(EditFile, self).dispatch(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get 236. return super(BaseUpdateView, self).get(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get 174. return self.render_to_response(self.get_context_data()) ... File "/itapp/itapp/circuits/views.py" in get_context_data 332. context = EditFile().get_context_data(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in __init__ 43. for key, value in six.iteritems(kwargs): Exception Type: RecursionError at /circuits/file/edit/5/7/site_cl Exception Value: maximum recursion depth exceeded my view is as follows: class EditFile(UpdateView): model = CircuitFiles form_class = FileForm … -
Configure codehilite in Django
I'm a beginner to Django, so I haven't had much luck; what I'm trying to do is seemingly simple. I am working with the Django wiki package, and I'm trying to find out where I can modify the config variable in to the highlight function in wiki/core/markdown/mdx/codehilite.py: def highlight(code, config, tab_length, lang=None): code = CodeHilite( code, linenums=config['linenums'], guess_lang=config['guess_lang'], css_class=config['css_class'], style=config['pygments_style'], noclasses=config['noclasses'], tab_length=tab_length, use_pygments=config['use_pygments'], lang=lang, ) html = code.hilite() html = """<div class="codehilite-wrap">{}</div>""".format(html) return html By simply modifying guess_lang=config['guess_lang'], to guess_land=False, the problem is temporarily fixed by simply ignoring the input value. I'm looking for a permanent solution.