Home > Net >  How to display property method as a message in class based view?
How to display property method as a message in class based view?

Time:12-03

I have a property method defined inside my django model which represents an id.

status_choice = [("Pending","Pending"), ("In progress", "In progress")  ,("Fixed","Fixed"),("Not Fixed","Not Fixed")]
class Bug(models.Model):
    name = models.CharField(max_length=200, blank= False, null= False)
    info = models.TextField()
    status = models.CharField(max_length=25, choices=status_choice, 
default="Pending")
    assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= 
                    models.CASCADE, related_name='assigned', null = True, blank=True)
    phn_number = PhoneNumberField()
    uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= 
          models.CASCADE, related_name='user_name')
    created_at = models.DateTimeField(auto_now_add= True)
    updated_at = models.DateTimeField(blank= True, null = True)
    updated_by = models.CharField(max_length=20, blank= True)
    screeenshot = models.ImageField(upload_to='pics')


   @property
   def bug_id(self):
      bugid = "BUG{:03d}".format(self.id)
      return bugid

What I wanted is I need to show this id as a message after an object is created.

corresponding views.py file.

class BugUpload(LoginRequiredMixin, generic.CreateView):
    login_url = 'Login'
    model = Bug
    form_class = UploadForm
    template_name = 'upload.html'
    success_url = reverse_lazy('index')
    
    def form_valid(self, form):
    
        form.instance.uploaded_by = self.request.user
        return super().form_valid(form)

CodePudding user response:

Assuming that your UploadForm is a ModelForm it's worth noting that calling .save() on it will return an instance of your model.

If you have:

class UploadForm(ModelForm):
    class Meta:
        model = Bug

This means that your .save() will return an instance of a Bug

Now that everything went well and you have your new instance, you can use django's messages framework to build the success message for your users:

def form_valid(self, form):
    instance = form.save(commit=True)
    my_message = f"Hello {instance.bug_id}"
    messages.add_message(self.request, messages.SUCCESS, my_messages)
    return instance
  • Related