Aakash Bhaikatti
Aakash Bhaikatti

Reputation: 156

How to set the fields in Django based on inputs?

models.py

class NewsImage(models.Model):
    IMAGE_TYPE = (('Attachments','Attachments'),('URL','URL'))
    news = models.ForeignKey(Post, related_name='News', on_delete=models.CASCADE)
    image_type = models.CharField(max_length=12, verbose_name='Image Type', choices=IMAGE_TYPE)
    attachments = models.ImageField(upload_to='media/news_images', verbose_name='Image Attachments', blank=True)
    url = models.CharField(max_length=255, verbose_name='Image url', blank=True)

    def __str__(self):
        return (self.news)+ ' - ' +self.image_type

So, based on the image_type the choices should work. For eg: If choice = attachments then url field should be blank or If choice = url then attachment field should be blank I'm working on Django Rest Framework ModelViewSets So anyone can please help me solving these. Thanks alot

Upvotes: 0

Views: 43

Answers (1)

user11516203
user11516203

Reputation:

you can implement your logic in the create view, for instance

class BlankCreateView(CreateView):
    ....
    def __init__(self, **kwargs):
        self.object = None
        super().__init__(**kwargs)

    def form_valid(self, form):
    
        form.instance.author = self.request.user
        articles = form.save(commit=False)
        articles.author = self.request.user
    
        if articles.image_type = 'A':
            # do you logic here
        
        elif articles.image_type = 'B' :
            # do you logic here
        else:
            # do you logic here
        return super().form_valid(form)

Upvotes: 1

Related Questions