【问题标题】:Django- user posting ErrorsDjango-用户发布错误
【发布时间】:2020-12-26 19:30:59
【问题描述】:

我发现从我的 Django 站点保存用户帖子时出现问题。每当我尝试运行提交表单时,它都会显示表单已提交,但我无法看到帖子已保存在数据库中。

def addPost(request):
    form = hacksform(request.POST or None, request.FILES or None) 
    if request.method == 'POST':
        form = hacksform(request.POST or None, request.FILES or None) 
        if form.is_valid():
            try:
                newpost = form(commit= False)
                image = request.FILES['photo']
                newpost.author = request.user
                newpost.post_image = image
                newpost.save()
                newpost.save_m2m()
            except:
                newposts = form(commit=False)
                newpost.author = request.user
                newposts.save()
                newposts.save_m2m()
            return HttpResponseRedirect('/tweaks/tweaks')
    return HttpResponseRedirect('/tweaks/tweaks')

这是我的 forms.py 文件

class hacksform(forms.ModelForm):
    VIEW_CHOICES = (
    ("Option", "Choose Option"),
    ("Public", "To Public"),
    ("Channels", "To Channels"),
    )
    title = forms.CharField(widget=forms.TextInput(attrs={'class': 'user-title', 'placeholder': 'Title'}) ,required=True)
    content = forms.CharField(widget=forms.Textarea(attrs={'class': 'user-text', 'placeholder': 'Questions'}) ,required=False)
    tags = forms.CharField(widget=forms.TextInput(attrs={'class': 'input-tag', 'placeholder': 'Add Tag'}) ,required=False)
    audience_privacy = forms.CharField(widget=forms.Select(choices=VIEW_CHOICES,attrs={'id': 'selector'}) ,required=False)
    class Meta: 
        model = hacks
        fields = [
            'title',
            'author',
            'tags',
            'content',
            'post_image',
            'audience_privacy'
        ]

关于我不能发帖的任何想法

【问题讨论】:

    标签: python python-3.x django django-forms


    【解决方案1】:
    def addPost(request):
    if request.method == 'POST':
        form = hacksform(request.POST or None, request.FILES or None) 
        if form.is_valid():
            try:
                newpost = form(commit= False)
                image = request.FILES['photo']
                newpost.author = request.user
                newpost.post_image = image
                newpost.save()
                newpost.save_m2m()
            except:
                newposts = form(commit=False)
                newpost.author = request.user
                newposts.save()
                newposts.save_m2m()
            return HttpResponseRedirect('/tweaks/tweaks')
        else:
            print("errors",form.errors) # Print the errors on console
    return HttpResponseRedirect('/tweaks/tweaks')
    

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 2018-01-05
      • 1970-01-01
      • 2015-02-15
      • 2018-08-05
      • 1970-01-01
      • 2014-07-01
      • 2014-05-06
      • 2012-06-07
      相关资源
      最近更新 更多