0
votes

I am trying to use django forms init features, and for some reason the net seems pretty terse on advanced form features. I just want to take typos like "repo-with-accidental-space " and make it "repo-with-accidental-space". Right now I have:

class BitbucketCreateRepoForm(forms.Form):
    def __init__(self, repo_name=None, *args, **kwargs):
        if repo_name:
            self.repo_name = repo_name.strip()
        super(BitbucketCreateRepoForm, self).__init__()

    username    = forms.ChoiceField(required=True, initial='codyc54321', choices=BITBUCKET_USERNAME_CHOICES)
    repo_name   = forms.CharField(required=True, label='Repo name')
    description = forms.CharField(widget=forms.Textarea, required=False)

The form will load on page, but when I submit:

AttributeError at /bitbucket/create-repo
'QueryDict' object has no attribute 'strip'

Going in ipdb gets hairy, there must be a standard way to do this, but I don't work at the place I saw it done anymore.

This is the view:

def create_repo(request):
    form = BitbucketCreateRepoForm(request.POST or None)
    if form.is_valid():
        repo_name   = request.POST['repo_name']
        username    = request.POST['username']
        description = request.POST['description'] or None            
        create_repo_func(username=username, repo_name=repo_name, description=description)
    return render(request, 'bitbucket/create_repo.html', locals())

How do I process this field only if the form went through a POST, and update that field, leaving it empty on GET request? Thank you

1
What isn't working? are you getting errors? .strip() will remove whitespace at the beginning and end of the string: docs.python.org/2/library/string.html#string.stripBrandon
yes seems i didnt put them, long daycodyc4321
I'm right there with you :)Brandon
Hold on... I see an issue. You're redefining repo_name.Brandon

1 Answers

1
votes

Pass in the request method when you instantiate this form. You can check for request method with:

post = request.method == 'POST'

The you can pass this into the modified __init__ below.

class BitbucketCreateRepoForm(forms.Form):
    def __init__(self, repo_name=None, post=False, *args, **kwargs):
        if repo_name and post:
            self.repo_name = json.dumps(repo_name).strip()
        super(BitbucketCreateRepoForm, self).__init__()

    username    = forms.ChoiceField(required=True, initial='codyc54321', choices=BITBUCKET_USERNAME_CHOICES)
    repo_name   = forms.CharField(required=True, label='Repo name')
    description = forms.CharField(widget=forms.Textarea, required=False)

UPDATE: I was typing as you modified your question. In order to get the string representation of a QueryDict object simply import json then json.dumps(repo_name). Hope that helps.