用外键保存表格

时间:2019-04-14 07:40:47

标签: django django-models django-forms

我尝试了一些在这里和互联网周围发现的东西,但是我坚持了下来。我试图保存一种形式,该字段之一是foreignKey。问题是我想输入一个charField,所以如果组名不在数据库中,则创建它并保存表单。

我的模特

Classifier

和form.py

from django.db import models
from django.utils import timezone
import datetime

# Create your models here.                                                                                                                                                                                         

class Ideas_Group(models.Model):
    category_text = models.CharField(max_length=30, unique=True)
    # votes = models.IntegerField(default=0)                                                                                                                                                                       

    def __str__(self):
        return self.category_text

class Idea(models.Model):
    idea_title = models.CharField(max_length=30)
    idea_text = models.CharField(max_length=200)
    idea_repo = models.URLField(max_length=80, blank=True, null=True)
    idea_owner = models.CharField(max_length=30, blank=True, null=True)
    idea_status = models.CharField(max_length=30, blank=True, null=True)
    pub_date = models.DateTimeField('date published', auto_now_add=True)
    group = models.ForeignKey(Ideas_Group, on_delete=models.CASCADE)

    def __str__(self):
        return "%s by %s => %s" % (self.idea_title, self.idea_owner, self.idea_text)

    def was_published_recently(self):
        now = timezone.now()
        return now >= self.pub_date >= now - datetime.timedelta(days=1)

和views.py

class IdeasForm(forms.ModelForm):
    idea_title = forms.CharField(widget=forms.TextInput(attrs={
        'class':'form-control',
        'placeholder':"do you have a name for your idea",
       'aria-describedby':"basic-addon1",}))

    idea_text = forms.CharField(widget=forms.Textarea(attrs={
                                    'class':'form-control',
                                    'placeholder':"what s the idea man",
                                    'aria-describedby':"basic-addon1",
                                    'rows':"10"}),
                                max_length=200,)

    group = forms.CharField(widget=forms.TextInput(attrs={
        'class':'form-control',
        'placeholder':"Category",
        'aria-describedby':"basic-addon1",}))

    group_new = forms.CharField(widget=forms.TextInput(attrs={
        'class':'form-control',
        'placeholder':"Category",
        'aria-describedby':"basic-addon1",}))

    idea_repo = forms.URLField(widget=forms.URLInput(attrs={
        'class':'form-control',
        'placeholder':"repo",
        'aria-describedby':"basic-addon1",}),
                               required=False)

    #def __init__(self, *args, **kwargs):                                                                                                                                                                                                                                      
    #    super(IdeasForm, self).__init__(*args, **kwargs)                                                                                                                                                                                                                      
    #    self.fields['group'].required = False                                                                                                                                                                                                                                 

    #idea_repo.widget.attrs.update(                                                                                                                                                                                                                                            
    class Meta:
        model = Idea
        fields = ('idea_title',
                  'idea_text',
                  'group',
                  'idea_repo',)

    #def clean(self):                                                                                                                                                                                                                                                          
    #    # group = self.cleaned_data.get('group')                                                                                                                                                                                                                              
    #    group = Ideas_Group.objects.get_or_create(                                                                                                                                                                                                                            
    #                category_text=self.cleaned_data.get('group0'))                                                                                                                                                                                                            
    #    self.cleaned_data['group'] = group                                                                                                                                                                                                                                    
    #    return super(IdeasForm, self).clean()                                                                                                                                                                                                                                 

    def save(self):
        self.cleaned_data['group'] = group
        return super(IdeasForm, self).save()

最好的方法是什么?

更新: 我将save()更改为与this link中的示例一样近,但是仍然无法正常工作。

def post(self, request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:                                                                                                                                   
        form = IdeasForm(request.POST, instance='Ideas_Group')

        # check whether it's valid:                                                                                                                                                                            
        if form.is_valid():
            #ideapost = form.save(commit=False)                                                                                                                                                                
            #ideapost.pub_date=timezone.now()                                                                                                                                                                  
            print(form.cleaned_data['group'])
            #grp = form.cleaned_data['group']                                                                                                                                                                  
            #ideapost.group = form.cleaned_data.get('group')                                                                                                                                                   
            #ideapost.save()                                                                                                                                                                                   
            form.save()
    latest_ideas_list = Idea.objects.order_by('-pub_date')[:6]
    paginator = Paginator(latest_ideas_list, 10)
    latest_ideas_pages = paginator.page(1)
    context = {
        'latest_ideas_list': latest_ideas_list,
        'ideas_list': latest_ideas_pages,
        'form': IdeasForm(),
    }
    return render(request,
                  self.template_name,
                  context)

且跟踪为:

    def save(self, commit=True):
    group, created = Ideas_Group.objects.get_or_create(
                category_text=self.cleaned_data.get('group'))
    print(11111)
    self.cleaned_data['group'] = group.id
    #self.group = group_new.id                                                                                                                                                                                 
    print(222222)
    return super(IdeasForm, self).save(commit)

0 个答案:

没有答案