Django标签保存相关对象

时间:2019-02-22 22:33:03

标签: python django python-3.x

大家好! 我正在尝试使用某种字段创建保存表单,其中每个字段都有自己的标签,只有一个。

但是当我保存表单时,我有一个字段不保存一个标签,而是一次保存两个标签。虽然这不应该。请帮我解决问题。

/models.py

class Post(models.Model): # Books
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = VersatileImageField(
    'Image',
    upload_to='media_my/',null=True,
     blank=True
)
title = models.CharField(max_length=150, db_index=True)
slug = models.SlugField(max_length=150, unique=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True, related_name='posts')
b1 = models.ManyToManyField('B1', blank=False, related_name='bo1')
b2 = models.ManyToManyField('B2', blank=False, related_name='bo2')
b3 = models.ManyToManyField('B3', blank=False, related_name='bo3')
b4 = models.ManyToManyField('B4', blank=False, related_name='bo4')

date_pub= models.DateTimeField(auto_now_add=True)

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

def save(self, *args, **kwargs):
    if not self.id:
        self.slug= gen_slug(self.title)
    super().save(*args, **kwargs)

def __str__(self):
    return self.title

class Meta:
    ordering = ['-date_pub']

 class Tag(models.Model): # Tags of books
title=models.CharField(max_length=50)
slug=models.SlugField(max_length=50, unique=True)

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

def __str__(self):
    return self.title


class B1(models.Model):
b1 = models.CharField(max_length=286)
tags = models.ManyToManyField('Tag', blank=True, related_name='t1')
date_save= models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.b1

class B2(models.Model):
b2 = models.CharField(max_length=286)
tags = models.ManyToManyField('Tag', blank=True, related_name='t2')
date_save= models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.b2

class B3(models.Model):
b3 = models.CharField(max_length=286)
tags = models.ManyToManyField('Tag', blank=True, related_name='t3')
date_save= models.DateTimeField(auto_now_add=True)


def __str__(self):
    return self.b3

class B4(models.Model):
b4 = models.CharField(max_length=286)
tags = models.ManyToManyField('Tag', blank=True, related_name='t4')
date_save= models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.b4

/forms.py

class TagForm(forms.ModelForm):
class Meta:
    model = Tag
    fields = ['title','slug']

    widgets= {
    'title':forms.TextInput(attrs={'class':'form-control'}),
    'slug':forms.TextInput(attrs={'class':'form-control'}),
    }


def clean_slug(self):
    new_slug=self.cleaned_data['slug'].lower()

    if new_slug== 'create':
        raise ValidationError('Slug may not be "Create"')
    if Tag.objects.filter(slug__iexact=new_slug).count():
        raise ValidationError('Slug must be unique. We have "{}" slug already'.format(new_slug))
    return new_slug

class PostForm(forms.ModelForm):
class Meta:
    model = Post
    fields = [ 'image','title','tags']

    widgets = {
    'image':forms. ClearableFileInput(attrs={'class':'form-control'}),
    'title': forms.TextInput(attrs={'class':'form-control'}),
    'tags': forms.SelectMultiple(attrs={'class':'form-control'}),
    }


def clean_slug(self):
    new_slug = self.cleaned_data['slug'].lower()

    if new_slug =='create':
        raise ValidationError('Slug may not be "Create"')
    return new_slug

class B1Form(forms.ModelForm):
class Meta:
    model = B1
    fields = ['b1','tags']

    widgets = {
    'b1': forms.TextInput(attrs={'class':'form-control'}),
    'tags': forms.SelectMultiple(attrs={'class':'form-control'}),
    }


class B2Form(forms.ModelForm):
class Meta:
    model = B2
    fields = [ 'b2','tags']

    widgets= {
    'b2': forms.TextInput(attrs={'class':'form-control'}),
    'tags': forms.SelectMultiple(attrs={'class':'form-control'}),
    }

class B3Form(forms.ModelForm):
class Meta:
    model = B3
    fields = [ 'b3','tags']

    widgets= {
    'b3': forms.TextInput(attrs={'class':'form-control'}),
    'tags': forms.SelectMultiple(attrs={'class':'form-control'}),
    }

class B4Form(forms.ModelForm):
class Meta:
    model = B4
    fields = [ 'b4']

    widgets= {
    'b4': forms.TextInput(attrs={'class':'form-control'}),
    }

/ HTML

{% extends 'face/base_face.html'%}

{% block title %}
Create Post - {{ block.super}}
{% endblock %}

{% block content %}
<form class="" action="{% url 'post_create_url' %}" method="post" enctype="multipart/form-data">
  {% csrf_token%}

      <!-- forma of Post -->
  {% for field in form %}

  <div class="form-group">

      {% if field.errors %}
        <div class="alert alert-danger">
            {{ field.errors }}
        </div>
      {% endif %}
      {{ field.label }}
      {{ field }}
  </div>
  {% endfor %}

    <!-- forma of B1 -->
  {% for field in forma %}

  <div class="form-group">

      {% if field.errors %}
        <div class="alert alert-danger">
            {{field.errors}}
        </div>
      {% endif %}
      {{ field.label }}
      {{ field }}
  </div>
  {% endfor %}

      <!-- forma of B2 -->
  {% for field in formb %}

  <div class="form-group">

      {% if field.errors %}
        <div class="alert alert-danger">
            {{field.errors}}
        </div>
      {% endif %}
      {{ field.label }}
      {{ field }}
  </div>
  {% endfor %}
        <!-- forma of B3 -->
      {% for field in formc %}

      <div class="form-group">

          {% if field.errors %}
            <div class="alert alert-danger">
                {{field.errors}}
            </div>
          {% endif %}
          {{ field.label }}
          {{ field }}
      </div>
      {% endfor %}
      <!-- forma of B4 -->
      {% for field in formd %}

      <div class="form-group">

          {% if field.errors %}
            <div class="alert alert-danger">
                {{field.errors}}
            </div>
          {% endif %}
          {{ field.label }}
          {{ field }}
      </div>
      {% endfor %}

/utils.py

def get(self, request):
    form= self.model_form()
    forma= self.modb1()
    formb= self.modb2()
    formc= self.modb3()
    formd= self.modb4()


    context = {
    'form':form,
    'forma':forma,
    'formb':formb,
    'formc':formc,
    'formd':formd,
    }
    return render (request, self.template, context)

def post(self, request):
    bound_form = self.model_form(request.POST or None, request.FILES or None)
    bp1=self.modb1(request.POST or None)
    bp2=self.modb2(request.POST or None)
    bp3=self.modb3(request.POST or None)
    bp4=self.modb4(request.POST or None)

    context = {'form':bound_form,'forma':bp1,
            'formb':bp2,'formc':bp3,
            'formd':bp4,}

    if bound_form.is_valid() and bp1.is_valid()  and bp2.is_valid() and bp3.is_valid() and bp4.is_valid():
                new_obj=bound_form.save(commit=False)
                new_obj.user = request.user

                new_obj.b1.add(a)
                new_obj.b2.add(b)
                new_obj.b3.add(c)
                new_obj.b4.add(d)

                a=bp1.save()
                b=bp2.save()
                c=bp3.save()
                d=bp4.save()

                new_obj.save()

                return redirect(new_obj)

请仔细查看forms.py中的代码 也许B1,B2,B3,B4字段中的标签不正确?

0 个答案:

没有答案