Categories
Python Answers

How to get request data in a Python Django form?

Sometimes, we want to get request data in a Python Django form.

In this article, we’ll look at how to get request data in a Python Django form.

How to get request data in a Python Django form?

To get request data in a Python Django form, we can pass the request object into the form.

For instance, we write

from django import forms

class UserForm(forms.Form):
    email_address = forms.EmailField(
        widget=forms.TextInput(
            attrs={
                'class': 'required'
            }
        )
    )

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(UserForm, self).__init__(*args, **kwargs)

    def clean_email_address(self):
        email = self.cleaned_data.get('email_address')

        if self.user and self.user.email == email:
            return email

        if UserProfile.objects.filter(email=email).count():
            raise forms.ValidationError(
                u'That email address already exists.'
            )

        return email

to create the UserForm form class.

Then in our view, we write

def someview(request):
    if request.method == 'POST':
        form = UserForm(request.POST, user=request.user)
        if form.is_valid():
            # ...
            pass
    else:
        form = UserForm(user=request.user)

to create the UserForm instance with the user argument set to request.user to populate the form with user data.

And we pass in request.POST to populate the form with POST data.

Conclusion

To get request data in a Python Django form, we can pass the request object into the form.

Categories
Python Answers

How to display a field that is marked as editable=False’ in the model with Python Django admin?

Sometimes, we want to display a field that is marked as editable=False’ in the model with Python Django admin.

In this article, we’ll look at how to display a field that is marked as editable=False’ in the model with Python Django admin.

How to display a field that is marked as editable=False’ in the model with Python Django admin?

To display a field that is marked as editable=False’ in the model with Python Django admin, we add them to the readonly_fields tuple.

For instance, we write

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields=('first',)

to add the 'first' read only field into our model admin class.

Conclusion

To display a field that is marked as editable=False’ in the model with Python Django admin, we add them to the readonly_fields tuple.

Categories
Python Answers

How to use regular expressions with Python Flask URL routing?

Sometimes, we want to use regular expressions with Python Flask URL routing.

In this article, we’ll look at how to use regular expressions with Python Flask URL routing.

How to use regular expressions with Python Flask URL routing?

To use regular expressions with Python Flask URL routing, we can create our own convert class.

For instance, we wrire

from flask import Flask
from werkzeug.routing import BaseConverter

app = Flask(__name__)

class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]


app.url_map.converters['regex'] = RegexConverter

@app.route('/<regex("[abcABC0-9]{4,6}"):uid>-<slug>/')
def example(uid, slug):
    return "uid: %s, slug: %s" % (uid, slug)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

to create the RegexConverter class that sets self.regex to the first items entry.

Then we register the regex converter with

app.url_map.converters['regex'] = RegexConverter

Then if our URL starts with <regex and ends with > then RegexConverter will be used to match URLs.

Conclusion

To use regular expressions with Python Flask URL routing, we can create our own convert class.

Categories
Python Answers

How to fix the Flask ImportError: No Module Named Flask error with Python Flask?

Sometimes, we want to fix the Flask ImportError: No Module Named Flask error with Python Flask.

In this article, we’ll look at how to fix the Flask ImportError: No Module Named Flask error with Python Flask.

How to fix the Flask ImportError: No Module Named Flask error with Python Flask?

To fix the Flask ImportError: No Module Named Flask error with Python Flask, we install the flask package.

We create a new virtualenv with

virtualenv flask

then we cd to the virtualenv with

cd flask

And then we activate it with

source bin/activate

Then we install flask in the virtualenv with

pip install flask

Conclusion

To fix the Flask ImportError: No Module Named Flask error with Python Flask, we install the flask package.

Categories
Python Answers

How to change the host and port that the Python flask command uses?

Sometimes, we want to change the host and port that the Python flask command uses.

In this article, we’ll look at how to change the host and port that the Python flask command uses.

How to change the host and port that the Python flask command uses?

To change the host and port that the Python flask command uses, we can use the -h flag to change the host and the -p flag to change the port.

For instance, we write

flask run -h localhost -p 3000

to run our flask app with the host set to localhost and the port set to 3000.

Conclusion

To change the host and port that the Python flask command uses, we can use the -h flag to change the host and the -p flag to change the port.