Home > Back-end >  django: how to override the save() function in a model class so that it displays the saved informati
django: how to override the save() function in a model class so that it displays the saved informati

Time:11-11

I am new to the django world and web development in general

what I want to do is to preview the data that is saved in one of the created models "Tool"

in models.py

class Tool(models.Model):
    text1 = models.CharField(max_length=255)
    text2 = models.CharField(max_length=255)
    text3 = models.CharField(max_length=255)

    def save(self, *args, **kwargs):
        #override code
        super(Tool, self).save(*args, **kwargs)

now I know that I need to override the save() method inside the class Tool but I don't know how it is done?

in veiws.py I did the following

from .models import Tool

def preview(request):
    context = {
    "Tools": Tool.object.all()
    }
    
    return render (request,'myApp/preview.html',context)

and in preview.html I have the following

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p>{{Tools.text1}}</p>
    <p>{{Tools.text2}}</p>
    <p>{{Tools.text3}}</p>
</body>
</html>

now from here, how can I render the html inside save() in Tool class?

CodePudding user response:

From your comments it seems you are using Django Admin to add or change Tool objects. What you want is to redirect the user to the preview view after adding and/or changin a Tool. You need to add below methods to your ToolAdmin class:

def response_add(self, request, obj, post_url_continue=None):
    return redirect('preview')

def response_change(self, request, obj):
    return redirect('preview')

CodePudding user response:

You need to iterate over like that :

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
{% for tool in Tools %}
    <p>{{tool.text1}}</p>
    <p>{{tool.text2}}</p>
    <p>{{tool.text3}}</p>
{% endfor %}
</body>
</html>
  • Related