Django:如何在Form中使用ManytomayField保存对象

时间:2015-12-03 00:37:41

标签: python django forms

我有一个表单,提交后我想将其保存到数据库。我为此创建了一个模型。如果我保存简单字段,CharField等等,那一切都很好。 但是模型具有多对多fileld并且可以添加指定主键的tis字段,即1或2。 但是如何插入数据,这已不在数据库中了?

在views.py中的表单:

def vk_get_wallposts(request):
sys_project_name = ''
internet_source_type = ''  #
success = False
number_to_get = ''
group_url = ''
forum_urls = ''
date_saved = datetime(2015, 9, 26)
filter_posts = ''
print('vk_get_wallposts form')

if request.method == 'POST':
    vkwallpostget_form = VkwallpostgetForm(request.POST)
    if vkwallpostget_form.is_valid():
        print('vk_get_wallposts form is_valid')
        success = True
        sys_project_name = vkwallpostget_form.cleaned_data[
            'sys_project_name']
        internet_source_type = vkwallpostget_form.cleaned_data[
            'internet_source_type']
        number_to_get = vkwallpostget_form.cleaned_data['number_to_get']
        # domain = vkwallpostget_form.cleaned_data['domain']
        group_url = vkwallpostget_form.cleaned_data['group_url']
        forum_urls = vkwallpostget_form.cleaned_data['forum_urls']
        filter_posts = vkwallpostget_form.cleaned_data['filter_posts']

        if 'Vk.com' in internet_source_type:
            get_wallposts_by_owner_id(group_url, sys_project_name, date_saved, number_to_get,
                                      filter_posts=filter_posts)  # 81099158  @staticmethod из класса VkuserListView

        pr = Userproject.objects.create(name=sys_project_name, description='test description', user=request.user, date_updated=date_saved,
                                  date_until=date_saved)
        pr.vk_groups.add(1,2)
        #pr.vk_groups.add('https://vk.com/southitpark', 'https://vk.com/graphgrail') - this is dont work

else:
    vkwallpostget_form = VkwallpostgetForm()
    success = False

ctx = {'vkwallpostget_form': vkwallpostget_form, 'sys_project_name': sys_project_name,
       'internet_source_type': internet_source_type, 'forum_urls': forum_urls,
       'group_url': group_url, 'number_to_get': number_to_get, 'filter_posts': filter_posts, 'success': success}
return render_to_response('vk_get_wallposts.html', ctx, context_instance=RequestContext(request))

所以线条有效:          pr = Userproject.objects.create(name = sys_project_name,description =' test description',user = request.user,date_updated = date_saved,                                   date_until = date_saved)         pr.vk_groups.add(1,2)

但是我需要动态地将数据插入到多对多字段,这个数据是字符串列表,所以 pr.vk_groups.add(' https://vk.com/south',' https://vk.com/graph') - 这是行不通的

2 个答案:

答案 0 :(得分:1)

我猜你的模型应该是这样的:

class VKGroup(Model):
  vk_url = ManyToManyField(VKURL, ...)
class VKURL(Model):
  url = CharField / or URLField

然后,如果您使用视图(如提到的那样),您只需执行以下操作:

url1 = VKURL(url="https://vk.com/south")
url1.save()
url2 = VKURL(url="https://vk.com/graph")
url2.save()
VKGroup = VKgroup(...)
VKGroup.add(url1,url2)

就是这样!

NB。如果您处理表单see this,则在处理表单数据时会有一个特殊的Form.save_m2m()方法。我个人试图避免这种情况并直接在视图中处理。

答案 1 :(得分:0)

With this code i was able to solve:

        url1 = Vkgroupstomonitor(vk_group_name="https://vk.com/south3")
        url1.save()
        url2 = Vkgroupstomonitor(vk_group_name="https://vk.com/graph3")
        url2.save()
        project = Userproject(name=sys_project_name, description='test description', user=request.user, date_updated=date_saved,
                                  date_until=date_saved)
        project.save()
        project.vk_groups.add(url1,url2)

Also I prefer to rewrite this with for cycle, without saving one by one