如何在Django中的View中获取manytomanyfield模型数据

时间:2017-12-18 13:13:55

标签: python django view many-to-many

models.py

class Account(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE, default='auth.User')
    id = models.CharField(max_length=50, unique=True)
    pw = models.CharField(max_length=200)
    nick = models.CharField(max_length=50, blank=True)
    blog = models.URLField(null=True, blank=True)
    published_date = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        self.published_date = timezone.now()
        self.pw = make_password(self.pw)
        super(Account, self).save(*args, **kwargs)

    def __str__(self):
        return self.id

    class Meta:
        ordering = ["-published_date"]

class Task(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE, default='auth.User')
    account = models.ManyToManyField(Account)
    published_date = models.DateTimeField(default=timezone.now)

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

forms.py

classAccountForm(forms.ModelForm):
    class Meta:
        model = NaverAccount
        fields = ('id', 'pw', 'nick','blog',)

class TaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = ('account',)

task.html

<form action="#" class="form-horizontal" method="POST">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-success" type="submit">Save</button>

views.py

def task(request): 
    if request.method == 'POST':
        form = TaskForm(request.POST) 

        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()

            #1. id = str(from Account model)
            #2. pw = str(from Account model)

            post.save()
            form.save_m2m()
            return redirect('task')
    else:
        form = TaskForm()
    context = {'form': form}
    return render(request, 'work/task.html', context)

我正在制作小型任务应用程序 我想从视图中的模板中获取用户选择的模型数据(帐户) ex)用户可以选择id1&#39;,&#39; id2&#39;。
我希望得到id,pw值 所以我可以在视图中使用id,pw来完成小任务 我尝试在视图中测试一些代码,如print(post.account),但不能再进一步。

            1. id = str(from Account model)
            2. pw = str(from Account model)

0 个答案:

没有答案