简体   繁体   中英

How to design models.py in django to Insert QueryDict

My forms.py

from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from item.models import *
from django import forms


class catalogForm(forms.Form):
    title = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Catalog Title"))
    #item = forms.ModelMultipleChoiceField(queryset=Item.objects.exclude(user=1), widget=forms.SelectMultiple)

    #def __init__(self, userId, *args, **kwargs):
        #super(catalogForm, self).__init__(*args, **kwargs)
        #self.fields['item'].queryset = Item.objects.filter(user = userId)
    def __init__(self, qs=None, *args, **kwargs):
        super(catalogForm, self).__init__(*args, **kwargs)
        if qs:
            self.fields['item'] = forms.ModelMultipleChoiceField(queryset=qs, widget=forms.CheckboxSelectMultiple())

My models.py

from django.db import models
from item.models import Item
from django.contrib.auth.models import User


class Catalog(models.Model):
    title = models.CharField(max_length=200)
    item = models.ManyToManyField(Item, blank=True, null=True)
    user = models.ForeignKey(User)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.title

My views.py

def catalog(request):
    # if this is a POST request we need to process the form data
    qs = Item.objects.filter(user = request.user)
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = catalogForm(qs,request.POST)
        # check whether it's valid:
        if form.is_valid():
            title=form.cleaned_data['title']
            item=form.cleaned_data['item']
            user= request.user
            q = Catalog(title=title, pub_date=timezone.now(),user=user)
            q.save()
            q.item = item.values()
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = catalogForm(qs)

    return render(request, 'catalog/catalog.html', {'form': form}) 

So I want to select multiple Items from Combo box and insert their ID against a particular catalog . Also want to retrieve later each Items Id for a particular catalog . What is the best way to design models.py for this in django

Right now if I try to insert with this code I am able to insert into catalog_catalog only , how to insert into selected item into catalog_catalog_item table

Thanks for help in advance.

You need this model field instead (remember to run migrations):

item = models.ManyToManyField(Item)

then upon saving form, you firstly save the catalog object and then you add related items:

items = form.cleaned_data['items']

q = Catalog(title=title, pub_date=timezone.now(), user=user)
q.save()
q.items = items.values()

Use items.values() to get ids from items querydict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM