django 允许用户使用CreateView和ManyToMany字段创建成分

k4emjkb1  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(193)

我有一个表单,用户可以在其中使用Custom Tags的jQuery插件创建成分。
提交表单会导致错误Field 'id' expected a number but got 'b'.,其中配料(相对于单词)中的每个字母都被作为预期已存在于数据库中的项目拾取。
第一个
编辑1:发布配料模型

class Ingredient(models.Model):
    id = models.BigAutoField(primary_key=True, editable=False)
    name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name
xfb7svmp

xfb7svmp1#

我创建了一个不属于ModelForm的表单字段,对它进行了处理,然后将它与帖子关联起来。

# models.py

class Ingredient(models.Model):
    id = models.BigAutoField(primary_key=True, editable=False)
    name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name

class Allergen(models.Model):
    id = models.BigAutoField(primary_key=True, editable=False)
    name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name

class Eat(models.Model):

    MEAL_CHOICES = (
        ("breakfast", "Breakfast"),
        ("lunch", "Lunch"),
        ("dinner", "Dinner"),
        ("supper", "Supper"),
        ("snack", "Snack"),
        ("drink", "Drink"),
    )

    id = models.BigAutoField(primary_key=True, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    notes = models.CharField(max_length=255, blank=True, null=True)
    meal = models.CharField(choices=MEAL_CHOICES, max_length=20)
    ingredient = models.ManyToManyField(Ingredient,blank=True)
    allergen = models.ManyToManyField(Allergen,blank=True)
    favorite = models.BooleanField(default=False)
    datetime = models.DateTimeField()

# form.py
class EatForm(forms.ModelForm):

    notes = forms.CharField(widget=forms.Textarea(attrs={"rows":3}),required=False)
    ingredient_names = forms.CharField(widget=forms.TextInput(),required=False)
    allergen_names = forms.CharField(widget=forms.TextInput(),required=False)

    class Meta:
        model = Eat
        fields = ["name", "notes", "meal","ingredient_names","allergen_names","favorite","datetime"]

# view.py

class EatFormAddView(LoginRequiredMixin, CreateView):
    model = Eat
    template_name = "dashboard.html"
    success_url = reverse_lazy("core:activity")
    form_class = EatForm

    # determine which submit button was pressed
    def form_valid(self, form):        

        ingredient_ids = []
        allergen_ids = []

        add_record = form.save(commit=False)
        
        # associate user to post
        add_record.user = self.request.user
        
        # get or create ingredients
        ingredients = form.cleaned_data['ingredient_names'].split(',')
        for ingredient in ingredients:
            record = Ingredient.objects.get_or_create(name=ingredient)
            ingredient_ids.append(record[0].id)

        # get or create allergens
        allergens = form.cleaned_data['allergen_names'].split(',')
        for allergen in allergens:
            record = Allergen.objects.get_or_create(name=allergen)
            allergen_ids.append(record[0].id)

        # save post
        add_record.save()
        
        # associate ingredients to saved post
        add_record.ingredient.set(ingredient_ids)
        
        # associate allergens to saved post
        add_record.allergen.set(allergen_ids)
        
        # save the post with ManyToMany populated
        add_record.save()
        
        return super().form_valid(form)

相关问题