Mypy: Returning Any from function declared to return “str” in django form methods

In every Django form method I try to return a str or other type and I obtain:

error: Returning Any from function declared to return "str"
    return password2
    ^    

forms.py

class UserAdminCreationForm(forms.ModelForm):
    def clean_password2(self) -> str:
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        passwords = password1 and password2
        passwords_not_match = password1 != password2
        if passwords and passwords_not_match:
            raise forms.ValidationError("Passwords don't match")
        return password2

Unique solution acepted for mypy is to change the str method for Any type, there is a reason to obtain this error or a way to solve it?

the only way I’ve been able to silence this mistake

class UserAdminCreationForm(forms.ModelForm):
    def clean_password2(self) -> Any:
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        passwords = password1 and password2
        passwords_not_match = password1 != password2
        if passwords and passwords_not_match:
            raise forms.ValidationError("Passwords don't match")
        return password2

mypy configuration in setup.cfg

(mypy)
python_version = 3.8
ignore_missing_imports = True
show_column_numbers = True
pretty = True
warn_unused_ignores = True
warn_redundant_casts = True
warn_return_any = True
warn_unused_configs = True
warn_unreachable = True
warn_no_return = True
disallow_any_unimported = True
disallow_any_generics = True
disallow_subclassing_any = True
disallow_untyped_calls = True
disallow_untyped_defs = True
disallow_incomplete_defs = True
check_untyped_defs = True
disallow_untyped_decorators = True
strict_optional = True
no_implicit_optional = True
strict_equality = True
ignore_errors = False

plugins = mypy_django_plugin.main

(mypy.plugins.django-stubs)
django_settings_module = "config.settings.test"

(mypy-*.migrations.*)
ignore_errors = True

embed – Why does my custom html code (for a donation form) appear in a preview but not in the published post?

I have tried to add the following code using a ‘Custom html’ block (to embed a GiveNow donation form). It shows as a preview on the page however when I attempt to view it on the live website, it is not visible:

<div style="padding:1px;max-width: 700px"><iframe class="gn-iframe" src="https://www.givenow.com.au/embed/Y2F1c2VpZD04MTImZG9tYWluPWxpZmUtZ2F0ZS5vcmcmdG9rZW49ODEyOjZhMGFhNmQyYzZiZTM2ZTk%3D" height="870" style="width: 100%" frameborder="0"></iframe></div>

I have read through other help responses to similar issues but can’t figure out what I’m doing wrong.

Thanks in advance, Lauryn

html – Save all input from form into txt and add text

I am trying to save my input from HTML form. It seems easy, but I am stuck at the very beginning.

By far, this is my code:

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>

<script language="Javascript" >
function download(filename, text1, text2, text3) {
  var pom = document.createElement('a');
  
  pom.setAttribute('href', 'data:text1/plain;charset=utf-8,' + encodeURIComponent(text1));
  pom.setAttribute('href', 'data:text2/plain;charset=utf-8,' + encodeURIComponent(text2));
  pom.setAttribute('href', 'data:text3/plain;charset=utf-8,' + encodeURIComponent(text3));
  
  pom.setAttribute('download', filename);
  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>

</head>

<body>

<form onsubmit="download(this('name').value, this('userInfo').value, this('otherInfo').value, this('text').value)">
  <div>
  <label for="name">File Name</label>
  <input type="text" name="name" value="test.txt">
  </div>
  <div>
  <label for="userInfo">User Info</label>
  <input type="text" name="userInfo" value="Name Surname">
  </div>
  <div>
  <label for="userInfo">Other Info</label>
  <input type="text" name="otherInfo" value="95">
  </div>
  <div>
  <label for="userInfo">Text area</label>
  <textarea rows=3 cols=50 name="text">Insert your text here</textarea>
  </div>
  
  <div>
  <input type="submit" value="Download">
  <div>
</form>

</body>
</html>

I am having trouble in multiple steps:

  1. The .txt output is:
Insert your text here
  1. I would like to add some extra text between all the input data

How can I do that?

So, my example input/form would be:

File name
example.txt

User Info
Name Surname

Other Info 
95

and, if I am lucky enough, my desired output would be the file example.txt containing:

Hello, this is my example text page!
-----------------------------------------
User Info:            (comp1)      Name Surname
-----------------------------------------

°Information

-----------------------------------------
Other Info:           (numb)       95
-----------------------------------------

This file was generated through HTML and Javascript.
Modify it or recompile it...

html – Como aceitar um valor submit de um radioButton num form?

Tenho este form com RadioButtons numa view e depois coloco um botão submit que submete a resposta selecionada. A ‘RespostaDoJogador’ é uma propriedade de um Model chamado Jogo. E o objetivo seria, quando seleciono uma opção e a submeto, a propriedade ‘Resposta do Jogador’ assume aquele valor do RadioButton selecionado. O que estarei a fazer mal? :

@if (Model.Casa40 == true)

{

@Model.PerguntaEscolhida

    @if (@Model.PerguntaEscolhida == "Qual destes frutos é vermelho?")

    {
        <input type="radio" id="banana" name="opcao" value="banana" onclick="this.RespostaDoJogador.submit();">

        <label for="banana">Banana</label><br>

        <input type="radio" id="laranja" name="opcao" value="laranja" onclick="this.RespostaDoJogador.submit();">

        <label for="laranja">Laranja</label><br>

        <input type="radio" id="melao" name="opcao" value="melao" onclick="this.RespostaDoJogador.submit();">

        <label for="melao">Melão</label>

        <input type="radio" id="tomate" name="opcao" value="tomate" onclick="this.RespostaDoJogador.submit();">

        <label for="tomate">Tomate</label>
        <button type="submit" form="form1" value="Submit">submit</button>
    }


    @if (@Model.PerguntaEscolhida == "Qual destes alimentos é um fruto?")

    {
        <input type="radio" id="banana" name="opcaoo" value="banana" onclick="this.RespostaDoJogador.submit();">

        <label for="banana">Banana</label><br>

        <input type="radio" id="carapau" name="opcaoo" value="carapau" onclick="this.RespostaDoJogador.submit();">

        <label for="carapau">Carapau</label><br>

        <input type="radio" id="francesinha" name="opcaoo" value="francesinha" onclick="this.RespostaDoJogador.submit();">

        <label for="francesinha">Francesinha</label>

        <input type="radio" id="bifana" name="opcaoo" value="bifana" onclick="this.RespostaDoJogador.submit();">

        <label for="bifana">Bifana</label>
        <button type="submit" form="form1" value="submit">Submit</button>
    }

   

@if (@Model.PerguntaEscolhida == “Qual destes alimentos é peixe?”)

    {
        <input type="radio" id="morango" name="gender" value="morango" onclick="this.RespostaDoJogador.submit();">

        <label for="morango">Morango</label><br>

        <input type="radio" id="leitao" name="gender" value="leitao" onclick="this.RespostaDoJogador.submit();">

        <label for="leitao">Leitão</label><br>

        <input type="radio" id="sardinha" name="gender" value="sardinha" onclick="this.RespostaDoJogador.submit();">

        <label for="sardinha">Sardinha</label>

        <input type="radio" id="lasanha" name="gender" value="lasanha" onclick="this.RespostaDoJogador.submit();">

        <label for="lasanha">Lasanha</label>
        <button type="submit" form="form1" value="submit">Submit</button>
    }
</form>

}

interaction design – Should I prevent a user from navigating away from a form while it is being processed?

I’m designing a CRM which has a lot of forms in order to edit everything.
Currently, when you save a form, the Save button transforms into a loading-gif and is disabled (more clicks won’t do anything) and if successful back to the save button with a success message.
It should be mentioned that the user edits detail-information inside the form. So the same form can be edited multiple times consecutively.

Normally, the user doesn’t has to wait more than 1 second until the form is processed and saved. But what if it takes longer?
Currently the user is able to navigate away before the form is saved, if the processing takes a long time. The saving-process is asynchronous, so it still will be saved. But if an error occurs, and the user is on a whole different page, the error message won’t be displayed.

So should I stop the user from navigating away while the form is still processed?
If yes, how? Overlay over the navigation? Over the whole screen? Info-Message that if navigating away, he won’t be notified if there is an error?
If I shouldn’t stop the user, how should I inform him, if the save-process was successfull or failed?

Magento 2 add Estimate Shipping Form on Product Page

Following this post

Magento 2 : How to display Shipping Rates on a Product Page

i can get shipping rates for current product, tested with curl:

curl -ik -X POST -H "Content-Type: application/json" -d "{""address"":{""country_id"": ""IT""}}" https://example.com/rest/V1/shipping/estimate/51003PRI

got the following response:

[{"carrier_code":"tablerate","method_code":"bestway","carrier_title":"Shipping Method","method_title":"Express Delivery","amount":0,"base_amount":0,"available":true,"error_message":"","price_excl_tax":0,"price_incl_tax":0}]

Now i need to display a form in product page like the “Estimate Shipping and Tax” in cart page to pass the address in post action.

I would like to do it using ui form and ajax and need to update region field depending country field.

Any suggestions?

javascript – Contact Form 7 Conditional redirect

As per this ticket on WordPress forum, I have added the below code to my contact form for conditional redirect.

<script type="text/javascript">
inputs = event.detail.inputs;
inputs.forEach( function(el) {
    if ( el.name == "menu-52" ) {
        if ( el.value == "Below $10,000" ) {
            location.href = "https://www.facebook.com";
        } else if ( el.value == "Above $10,000" ) {
            location.href = "https://google.co.in";
        }
    }
});
</script>

But this is not working for me on my contact form and there are some errors on the console also.

Can someone please have a look and let me know where I am making mistake?

Thank you.

interaction design – Should I prevent a user from navigating away from a form while it is being proccessed?

I’m designing a CRM which has a lot of forms in order to edit everything.
Currently, when you save a form, the Save button transforms into a loading-gif and is disabled (more clicks won’t do anything) and if successful back to the save button with a success message.
It should be mentioned that the user edits detail-information inside the form. So the same form can be edited multiple times consecutively.

Normally, the user doesn’t has to wait more than 1 second until the form is proccessed and saved. But what if it takes longer?
Currently the user is able to navigate away before the form is saved, if the proccessing takes a long time. The saving-process is asynchronous, so it still will be saved. But if an error occurs, and the user is on a whole different page, the error message won’t be displayed.

So should I stop the user from navigating away while the form is still proccessed?
If yes, how? Overlay over the navigation? Over the whole screen? Info-Message that if navigating away, he won’t be notified if there is an error?
If I shouldn’t stop the user, how should I inform him, if the save-proccess was successfull or failed?

8 – Is there a way to pass custom data to a form template?

I have been tasked to customize a view, and I have been struggling with its exposed form, because I need to display some informations. Here is how it should look:

tags

These elements act as a checkbox, but the number on the right is the number of nodes that have this tag linked.

So far, I have nothing code related, because I simply don’t know how to handle this. The theme itself would accept an array of array, each of them containing the checkbox’s text, its value, and this number, like so:

tabs: [
    {
      label: "Topics",
      filtersType: "tag",
      filterName: "loremField[]",
      filters: [
        {
          id: "lorem1",
          label: "Loremi",
          items: "5"
        },
        {
          id: "lorem2",
          label: "Loremi",
          items: "15"
        }
    }
]

However, I’m not able to either pass this “items” key to either the form, and I’m not sure at all that I can customize the input from the hook form alter. For a reference, here is the template:

<div class="c-tag-filters">
  {% for item in filters %}
    <div class="c-tag-filters__item">
      <input id="{{item.id}}" name="{{ filters.filterName }}" class="c-tag-filters__item__input" type="checkbox">
      <div class="c-tag-filters__item__content">
        <label for="{{item.id}}">{{item.label}} <span class="c-tag-filters__item__content--nb">{{ item.items }}</span></label>
      </div>
    </div>
  {% endfor %}
</div>

So, how should I proceed in this case?

Thank you in advance

8 – Displaying another entity’s form on a node

Drupal::formBuilder()->getForm() already returns a render array, see the FormBuilder::getForm() documentation.

To render the form, you just need to pass the results of getForm() to your $build array, then render it in your template.

In hook_ENTITY_TYPE_view():

function MYMODULE_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  // ...
  $build('my_flagging_form') = $form_obtained;
}

Then in your twig template:

{{ content.my_flagging_form }}

Or, if you’re already rendering content in its entirety, you may not need to update your twig template at all.

As @4k4 noted in the comments, you can also add the appropriate meta data in hook_entity_extra_field_info to make your flagging form addition configurable (reorderable, etc) on your node’s Manage Display screen. See Creating pseudo-fields in Drupal 8 for an example.