Django在View中使用ManyToManyField数据

时间:2017-12-18 02:08:47

标签: django

models.py

class Profile(models.Model):
    profile_name = models.CharField(max_length = 255, blank = False)
    extra_profile_text = models.CharField(max_length = 50, blank = False)

class Category(models.Model):
    category_name = models.CharField(max_length = 50, blank = False)
    extra_category_text = models.CharField(max_length = 50, blank = False)

class ProfileCategory(models.Model):
    profile = models.ManyToManyField(Profile)
    category = models.ManyToManyField(Category)

forms.py

class ProfileCategoryForm(forms.ModelForm):

    class Meta:
        model = ProfileCategory
        fields = ('profile', 'category',)

views.py

def task(request): 

    if request.method == "POST":
        form = ProfileCategoryForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user

            #use [profile_name, extra_category_text data] that user selected

            post.save()
            form.save_m2m()
            return redirect('somewhere')
    else:
        form = ProfileCategoryForm()
    context = {'form': form }
    return render(request, 'some_app/somewhere.html', context)

当用户从ProfileCategoryForm中选择时,我想在视图中显示“profile_name”,“extra_category_text”数据。 过程将是 正面:用户选择一个Profile,一个Category>保存 返回:获取用户选择的配置文件,类别数据(例如:profile_name,extra_profile_text)>做一些任务>保存到ProfileCategory模型。

似乎我需要使用queryset但根本没有线索:(

2 个答案:

答案 0 :(得分:0)

You can do this easily using Multiform and MultiModelForm from django better forms.

pip install django-betterforms

Add betterforms to your INSTALLED_APPS and follow the documentation from the link.

答案 1 :(得分:0)

像@gitblame说的那样,你创建了这样一个复杂的模型。 您可以更改模型以便于查询。

前面:用户选择一个Profile,一个Category>保存

我们通常会这样做,将数据返回到html,显示并处理它。

# You can create js file and capture event of class/id changed and request to api server 
#(if you want to check like: 1 Profile and can select only Category relate only)

返回:获取用户选择的配置文件,类别数据(例如:profile_name,extra_profile_text)>做一些任务>保存到ProfileCategory模型。

  

您可以这样做,检查表单何时提交到views.py 检入模型(覆盖保存方法,其他任何内容......)

链接到django override method