Django'str'对象没有属性'save'

时间:2018-11-26 18:24:14

标签: python django django-models request django-views

我在views.py中使用Django时遇到问题.......行中的错误

post = text_headlines.save(commit = False)

异常值:
'str'对象没有属性'save'

下面是我在form.py,models.py和views.py

中的代码

谢谢您,我是Django新手,仍然需要时间学习

forms.py

from django import forms
from .models import Post

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('URL',)

models.py

from django.db import models

# Create your models here.
from django.conf import settings
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    URL = models.URLField(max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

views.py

from django.shortcuts import render, redirect
from .forms import PostForm
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from .models import Post
from urllib.request import Request, urlopen as uReq 
from bs4 import BeautifulSoup as soup

#Post.objects.get(pk=pk)
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'post_detail.html', {'post': post})

def make_soup(website) :

    req =  Request(website,headers = {'User-Agent' : 'Mozilla/5.0'})
    uClient = uReq(req)
    page_html = uClient.read()
    uClient.close()
    page_soup = soup(page_html, 'html.parser')
    return page_soup

def post_new(request) :
    if request.method == "POST":
        form = PostForm(request.POST)
        print(form)
        if form.is_valid():
            url = form.cleaned_data['URL']
            website = make_soup(url)
            headlines = website.findAll('h3')
            for item in headlines :
                top = item.a
                text_headlines = top.text
                print(text_headlines)
                print()
                post = text_headlines.save(commit=False)
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
        return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()

    return render(request, 'post_edit.html', {'form':form})

0 个答案:

没有答案