[Answered ]-Get the default value from a list django

0πŸ‘

βœ…

to do this you can create a field call status inside your database so that by default the value will be default = STEP1 something like this:

 class Photo(models.Model):
        STEP1 = "Received"
        STEP2 = "Cleaning"
        STEP3 = "Leak"
        STEP4 = "Loss Pressure Test"
    
        STATUS = (
            (STEP1, 'Received'),
            (STEP2, 'Cleaning'),
            (STEP3, 'Leak '),
            (STEP4, 'Loss Pressure Test'),
    
        )
    
        Datetime = models.DateTimeField(auto_now_add=True)
        #i add the status here so by default it is just "Received"
        status  = models.CharField(max_length=20,choices=STATUS,
            default=STEP1)
    
        serialno = models.TextField()  # serialno stand for serial number
        partno = models.TextField()  # partno stand for part number
        reception = models.TextField()
        Customername = models.TextField()
    
        def __str__(self):
            return self.reception

After that
1) run makemigrations and migrate
Now inside your templates you can just call "your_instance.status" .

1πŸ‘

An answer for your other question:
how do i make it so that when the user edit the table, the action done will show step2?

let us do something like this.
forms.py:

from .models import Photo


class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = ['serialno','partno','reception','Customername']

views.py

from .forms import PhotoForm
from .models import Photo
from django.shortcuts import render,get_object_or_404,redirect
def editphoto(request,photo_id):
    photo = get_object_or_404(Photo,pk=photo_id)
    if request.method == 'POST':
        form = PhotoForm(request.POST or None)
        if form.is_valid():
            form.save()
            #we can do something like this to check that serial number has changed 
            if form.serialno != photo.serialno:
                form.serialno = 'Cleaning'
                form.save()
            return redirect('***somewhere***')
    else:
        form = PhotoForm(instance=photo)
    return render(request,'your-template',{'form':form})

but note that there is a security concerns here i did not actually checks that the user is the author of that post.so basically now any user can edit a post,that is so bad.to avoid this you can just create a foreign key to User(model) inside Photo and inside your views.py you can check that just do something like:photo = get_object_or_404(Photo,pk=photo_id,author_id=request.user.pk) now when the user is not the author of the post it will raise Not Found Page,That is it.
Happy Coding.

Leave a comment