如何保存多个选择

时间:2017-11-11 17:57:15

标签: javascript jquery html django modal-dialog

我的问题是如何在admin和localhost上保存标签。目前,我的管理员只能添加新标签,但无法保存我选择的任何选项。

Admin

localhost/story/3/edit/

另外,我不知道如何使ModelMultipleChoiceField的格式看起来像 一个普通的文本字段,但是一旦字段有焦点,我可以选择任何选项,它将被添加到字段中,再次单击,我可以选择另一个选项,构建任意数量的选项。

example

models.py

class Tag(models.Model):
    name = models.CharField(max_length=20)
    slug = models.SlugField(unique=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('story:tag_detail', kwargs={'tag_name': self.slug})


class Story(models.Model):
    author = models.ForeignKey(StoryAuthor, related_name='stories',null=True)
    title = models.CharField(max_length=30,null=True)
    content = models.CharField(max_length=30,null=True)
    summary = models.CharField(max_length=30,null=True)
    tags = models.ManyToManyField('Tag', blank=True)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.sb_name

forms.py

from django import forms
from .models import Story,Tag

class StoryForm(forms.ModelForm):
    title = forms.CharField(widget=forms.TextInput(attrs={'class':'abc1 el-input__inner el-input__inner_m'}))
    content = forms.CharField(widget=forms.TextInput(attrs={'class':'abc2 el-input__inner el-input__inner_m'}))
    summary = forms.CharField(widget=forms.TextInput(attrs={'class':'abc3 el-input__inner el-input__inner_s'}))
    tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())


    def __init__(self, *args, **kwargs):
        super(StoryForm, self).__init__(*args, **kwargs)

        for field_name in self.fields:
            field = self.fields.get(field_name)
            field.widget.attrs['placeholder'] = field.label
            field.label =''

    class Meta:
        model = Story
        fields = (
            'title',
            'content',
            'summary',
            'tags',
        )

views.py

from .models import Story, StoryAuthor, Tag

def story_new(request):
    if request.method == "POST":
        form = StoryForm(request.POST)
        if form.is_valid():
            story = form.save(commit=False)
            story.author, _ = StoryAuthor.objects.get_or_create(user=request.user)
            story.published_date = timezone.now()
            story.save()
        return redirect('story_detail', pk=story.pk)
    else:
        form = StoryForm()
    return render(request, 'story/story_create.html', {'form': form})

story_edit.html

<div class="container">
<h1>Edit story</h1>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.errors}}
<p>Title : {{ form.title}}Content : {{ form.content}}Summary : {{ form.summary}}Tags : {{ form.tags}}</p>
<button type="submit" class="save btn">Save</button>
</form>
</div>

0 个答案:

没有答案