如何将在 localHost 页面(使用 Django)上输入的数据存储在 .txt/.json 文件中?

How can I storage data inputted on my localHost page (with Django) in .txt/.json files?

我试过了,Django 仍在工作,但是 .json 文件没有出现在我的路线上。 这是 models.py(Django 脚本)

from django.db import models

class Pizza(models.Model):
    """A pizza in a pizzeria"""

    text=models.CharField(max_length=250)
    date_added=models.DateTimeField(auto_now_add=True)
    filename='C:\Users\dayao\OneDrive\Escritorio\PythonCrashCourse_Ex\Pizzas\pizzotas\name.txt'

    def __str__(self):
        return self.text

        with open(filename,'w') as f:
            f.write(self.text)


class Topping(models.Model):
    """Store n make a hook between Pizza an the toppings"""

    topic=models.ForeignKey(Pizza, on_delete=models.CASCADE)
    text=models.TextField()
    date_added=models.DateTimeField(auto_now_add=True)
    filename="C:\Users\dayao\OneDrive\Escritorio\PythonCrashCourse_Ex\Pizzas\pizzotas\pizza_toppings.txt"

    class Meta:
        verbose_name_plural ='Toppings'

    def __str__(self):
        if len(self.text)>=50:
            return f"{self.text[:50]}..."
        else:
            return self.text

        with open(filename,'w') as f:
            f.write(self.text)

修正你的缩进。您的 with 语句不合适,因为它们在 returns 之后永远不会被击中。而filename不属于不用的地方。试试这个:

from django.db import models

class Pizza(models.Model):
    """A pizza in a pizzeria"""

    text=models.CharField(max_length=250)
    date_added=models.DateTimeField(auto_now_add=True)
    

    def __str__(self):
        filename='C:\....name.txt'
        with open(filename,'w') as f:
            f.write(self.text)

        return self.text


class Topping(models.Model):
    """Store n make a hook between Pizza an the toppings"""

    topic=models.ForeignKey(Pizza, on_delete=models.CASCADE)
    text=models.TextField()
    date_added=models.DateTimeField(auto_now_add=True)
    

    class Meta:
        verbose_name_plural ='Toppings'

    def __str__(self):
        if len(self.text)>=50:
            return f"{self.text[:50]}..."
        else:
            filename="C:\....\pizza_toppings.txt"
            with open(filename,'w') as f:
                f.write(self.text)

            return self.text