开发者

how to add to a FORM in views with django?

I've posted back a form and within my vi开发者_JS百科ew I'd like to add a a field.

Editing the slug field. It is the slug field which I've decided to hide in the form and automatically generate it in the view. How can I append the slug field to the form?

if form.is_valid():            
    form.[want_to_add_slug_field_here] = slugify(form.cleaned_data['title'])
    form.save()

I'm using (this is to hide the fields from the front end users completely as I want to automate these.

class LinkForm(forms.ModelForm):
    class Meta:
        model = Link
        exclude = ('pub_date', 'slug', 'posted_by',)

So these fields are not on my form when it's generating. I'm wanting to add these fields into the FORM before the save. Is this even possible?


There are many ways to deal with that (I assume you use ModelForm):

  1. Use form's clean method:

    class MyForm(forms.models.ModelForm):
        """ This is a form for your model. It includes all fields, but you
            won't display the slug field to the user. """
    
        def clean(self):
            cleaned_data = self.cleaned_data
            cleaned_data["slug"] = slugify(form.cleaned_data["title"])
            return cleaned_data
    
  2. Add the slug to the model before commiting:

    if form.is_valid():
         instance = form.save(commit=False)
         instance.slug = slugify(form.cleaned_data["title"])
         instance.save()
    
  3. Override your model's save method:

    class MyModel(models.Model):
    
        def save(self, *args, **kwargs):
             self.slug = slugify(self.title)
             return super(MyModel, self).save(*args, **kwargs)
    
  4. Use a 3rd party autoslug field, for example django-autoslug

I personally use the 4th way.


Are you looking for:

Default value when displaying form:

form.fields['slug_field'].initial = slugify(form.fields['title'].value)

Default value with no input from user, ever: You need to override the save method on the model itself:

def save(self,*args,**kwargs):
    self.slug_name = slugify(self.title)
    return super(MyModel,self).save(*args,**kwargs)


Override the form's save method as explained here: how to add the slugified field

If you slugify fields on a regular basis and on several models you could also consider writing a wrapper around the slugify-function that you can trigger with a pre_save signal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜