Django复选框数据库连接

时间:2018-09-03 13:35:58

标签: django

最近,我开始学习Django,并且尝试通过浏览器访问数据库中的BooleanField

这是我的表格

class NewTopicForm(forms.ModelForm):
 slot1 = forms.BooleanField(required=False)
 slot2 = forms.BooleanField(required=False)
 slot3 = forms.BooleanField(required=False)

 message = forms.CharField(
     widget=forms.Textarea(
         attrs={'rows': 5, 'placeholder': 'explanation'}
     ),
     max_length=4000,
     help_text='The max length of the text is 4000.'
 )

class Meta:
     model = Topic
     fields = ['subject', 'message', 'slot1', 'slot2', 'slot3']`

这是我的观点。当我说“ board.slot2 = True”时,将我的slot2 False更改为True。但是如何更改浏览器中的slot2

@login_required
def new_topic(request, pk):
board = get_object_or_404(Board, pk=pk)
if request.method == 'POST':
    form = NewTopicForm(request.POST)
    if form.is_valid():
        topic = form.save(commit=False)
        topic.board = board
        topic.starter = request.user


        board.slot2 = True
        board.save()
        # board.slot3 = False
        # board.save()

        topic.save()
        Post.objects.create(
            message=form.cleaned_data.get('message'),
            topic=topic,
            created_by=request.user
        )
        return redirect('topic_posts', pk=pk, topic_pk=topic.pk)
else:
    form = NewTopicForm()
return render(request, 'new_topic.html', {'board': board, 'form': form})`

这是我的模特

class Board(models.Model):
name = models.CharField(max_length=30, unique=True)
slot1 = models.BooleanField()
slot2 = models.BooleanField()
slot3 = models.BooleanField()

def __str__(self):
    return self.name

def get_posts_count(self):
    return Post.objects.filter(topic__board=self).count()

def get_last_post(self):
    return Post.objects.filter(topic__board=self).order_by('-created_at').first()`

0 个答案:

没有答案