简体   繁体   中英

How to edit & save contents from front-end in Django?

I'm using Django 1.8 to build a new web app. The app has a simple model which gets a name and a url. Then in the views I have a function that read the content of given url, then scrapes some data from it using BeautifulSoup package and assign them to local variables(article name, published date, etc.) in this function. Then I show these variables in templates.

Now I want to add new feature which allows logged in users to edit these contents. I've found some third party packages which do this, but since it's an educational project, I prefer to understand the logic of doing this myself.

So the question is how can I let logged in users to manipulate data captured from a function in views (and not a model field)and save the edited data in the database (without using Admin area)? Obviously I don't want any codes, I want to know the implementation idea to do this task.

views.py

def detail(request, article_id):
    article = get_object_or_404(Article, pk=article_id)

    html = article.article_url
    read = requests.get(html)
    soup = BeautifulSoup(html)
    title = soup.title.string

    return render(request, 'detail.html', {'article': article, 'title':title})

I find it easiest to start with how the data should be stored in a db. Start with a Article model:

def Article(models.Model):
    url = models.UrlField()
    title = models.CharField(max_length=200, blank=True)
    html = models.TextField(blank=True)

Than we want title and html be filled if url is given. Write a signal receiver to handle scraping:

@receiver(pre_save, instance, sender=Article)
def scrape(sender, **kwargs):
    if instance.url and not instance.title and not instance.html:
        data = requests.get(instance.url)
        instance.html = BeautifulSoup(data)
        instance.title = instance.html.title.name

If you add a admin, you're done. But views to display and update the data are also easy to create:

class ArticleDetailView(DetailView):
    model = Article

class ArticleUpdate(UpdateView):
    model = Article

Note: The code needs some work. You also need to write imports, urls and templates.

Finally: there is nothing wrong with third party apps. I don't own Python, Django, Requests, Beautiful Soup, etc... Even if this is a learning project, it a good thing to NOT reinvent the wheel. Be as lazy as possible. Use tools that do the job for you.

  1. find wysiwyg editor like froala, modify field
  2. update with ajax.
  3. check permissions on server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM