Home > Mobile >  How To Update Specific Model Field From Django View Before Saving A Form
How To Update Specific Model Field From Django View Before Saving A Form

Time:04-22

So, How can I update some Model Fields automatic, without the user having to input the values? In Models:

class Url(models.Model):
    long_url = models.CharField("Long Url",max_length=600)
    short_url = models.CharField("Short Url",max_length=7)
    visits = models.IntegerField("Site Visits",null=True)
    creator = models.ForeignKey(CurtItUser,on_delete=models.CASCADE,null=True)
    def __str__(self):
        return self.short_url

In Views:

def home(request):
    """Main Page, Random Code Gen, Appendage Of New Data To The DB"""
    global res,final_url
    if request.method == 'POST':
        form = UrlForm(request.POST)
        if form.is_valid():
            res = "".join(random.choices(string.ascii_uppercase,k=7))
            final_url = f"127.0.0.1:8000/link/{res}"
            form.save()
            redirect(...)
    else:
        form = UrlForm
    return render(...)

Sow how can for exapmle set from my view the value of short_url to final_url ???

CodePudding user response:

You can get the data you need from the form. you need to get the specific instance first, then you can use that instance to save values from the form. And do not forget to save!

url_instance = get_object_or_404(Url, pk=pk)
url_instance.short_url = form.cleaned_data['short_url']
url_instance.long_url = form.cleaned_data['long_url']
url_instance.visits = form.cleaned_data['visits']
url_instance.save()

You can find more detailed infromations in the Django Documentation.

  • Related