Saturday, February 27, 2021

Re: Class Base View Foreign key

I think choices is causing the problem. Try limit_choices_to instead:

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

On February 27, 2021 8:06:26 AM CST, "sebasti...@gmail.com" <sebastian.jung2@gmail.com> wrote:
Hello,

I have a CBV with Createview. Now i have a Foreign Key from Box to Tabs model. When i submit request then i get error: Cannot assign "1": "Box.tabs_link" must be a "Tabs" instance. This happens on form.is_valid

I understand this error but i don't know how can i fix this. 

Models.py:
class Box(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200, default="", blank=False, null=False) #Überschrift der Box
    tabs_link = models.ForeignKey(Tabs, on_delete=models.CASCADE, null=False,blank=False,choices=[
                                (c.id, c.name) for c in Tabs.objects.all()]
                                   )

    column = models.PositiveIntegerField(choices=column_choices,blank=False, null=False,default=0) #linke oder rechte Seite
    position = models.PositiveIntegerField(default=1,blank=False, null=False) #position auf der linken/rechten Seite
    modul = models.PositiveIntegerField(choices=Modul_Auswahl,
                                        default=0)  

    class Meta:
        ordering = ["position","column"]
    def __str__(self):
        return self.name

Views.py:
class BoxCreateView(CreateView):
    model = Box
    template_name = 'marketing/boxcreate.html'
    form_class = Boxform
    success_url = reverse_lazy('boxlist')

    def post(self, request, *args, **kwargs):
        formbox = Boxform(self.request.POST)
        if (formbox.is_valid()):
           pass

Forms.py
class Boxform(forms.ModelForm):
    class Meta:
        model = Box
        exclude = ('',)

        labels = {
            'tabs_link': 'Tabulator',
            'column': 'Spalte',
        }
        widgets = {
            'name': textinputfeld,
            'position': integerfeld,
            'column': integerfeld,
            'modul': selectfield,
            'tabs_link': selectfield,
        }

Regards


No comments:

Post a Comment