如何将字符串转换为CharField

时间:2019-02-25 14:54:04

标签: django django-views

在我的项目中,即使是未经授权的用户也有机会对帖子发表评论。所以,我有commentForm:

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('author', 'text',)

和型号:

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
    author = models.CharField(max_length=200)
    text = models.TextField()

如果用户被授权,我想替换为作者fileld用户名,而不在页面上显示输入,否则站点访问者应自己填写此输入。我试图以适当的观点写这个:

if request.user.is_authenticated:
   form = CommentForm(request.POST, initial={'author': request.user.username}) 

但是form.is_valid为false。 然后我尝试了:

if request.user.is_authenticated:
    form.fields['author'] = request.user.username

在表单验证出现的“字符串”对象期间,没有属性“已禁用”。 问题是如何正确对待它?谢谢。

post_detail.html

{% extends 'blog/base.html' %}

{% block content %}
    <div class="post">
      {% if post.published_date %}
        <div class="date">
          {{ post.published_date }}
        </div>
      {% else %}
        <a class="btn btn-default" href="{% url 'post_publish' post_id=post.pk blog_id=blog.pk %}">Publish</a>
      {% endif %}
      {% if user.is_authenticated and user == post.blog.author%}
        <a class="btn btn-default" href="{% url 'post_remove' post_id=post.pk blog_id=blog.pk %}">удалить</a>
        <a class="btn btn-default" href="{% url 'post_edit' post_id=post.pk blog_id=blog.pk %}">редактировать</a>
      {% endif %}
      <h1>{{ post.title }}</h1>
      <p>{{ post.text|safe|linebreaks }}</p>
    </div>
    <hr>
    <p>New comment</p>
    <form method="POST" class="post-form">{% csrf_token %}
      <!-- HERE I HIDE AUTHOR FIELD FROM LOGGED IN USERS -->
      {% if user.is_authenticated %}
        {{ form.text }}
        {{ form.text.errors }}
      {% else %}
        {{ form.as_p }}
      {% endif %}
        <button type="submit" class="save btn btn-default">Send</button>
    </form>
    {% for comment in post.comments.all %}
        <div class="comment">
          <div class="date">
            {{ comment.created_date }}
              <!--  {% if not comment.approved_comment %} -->
              <a class="btn btn-default" href="{% url 'comment_remove' post_id=post.pk blog_id=blog.pk com_id=comment.pk %}">удалить</a>
              <!--  {% endif %}-->
          </div>
          <strong>{{ comment.author }}</strong>
          <p>{{ comment.text|linebreaks }}</p>
        </div>
        {% empty %}
        <p>No comments here yet :(</p>
      {% endfor %}
{% endblock %}

views.py

from .models import Post, Comment, Blog
from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from .forms import PostForm, CommentForm, BlogForm
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout, login
from django.contrib.auth.models import User

def post_detail(request, blog_id, post_id):
    blog = get_object_or_404(Blog, pk=blog_id)
    post = get_object_or_404(Post, pk=post_id)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            if request.user.is_authenticated:
                comment.author = request.user.username
            comment.post = post
            comment.save()
            return redirect('post_detail', blog_id=blog_id, post_id=post.pk)
    else:
        form = CommentForm()
    return render(request, 'blog/post_detail.html', {'post': post, 'blog': blog, 'form': form})

@login_required
def post_publish(request, blog_id, post_id):
    post = get_object_or_404(Post, pk=post_id)
    post.publish()
    return redirect('post_detail', blog_id=blog_id, post_id=post.pk)

@login_required
def post_remove(request, blog_id, post_id):
    post = get_object_or_404(Post, pk=post_id)
    post.delete()
    return redirect('post_list', blog_id=blog_id)

@login_required
def comment_remove(request, blog_id, post_id, com_id):
    comment = get_object_or_404(Comment, pk=com_id)
    comment.delete()
    return redirect('post_detail', blog_id=blog_id, post_id=post_id)

@login_required
def post_edit(request, blog_id, post_id):
    post = get_object_or_404(Post, pk=post_id)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('post_detail', blog_id = blog_id, post_id=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})

def post_list(request, blog_id):
    blog = get_object_or_404(Blog, pk=blog_id)
    posts = blog.posts.all().filter(published_date__isnull=False).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts, 'blog': blog})

1 个答案:

答案 0 :(得分:0)

我不知道这是否是解决我的问题的最佳方法,但它可以帮助: change a form value before validation in Django form