【问题标题】:How to modify a form when returning it?返回时如何修改表单?
【发布时间】:2021-09-13 22:18:56
【问题描述】:

我希望修改用户的表单并在 django 中返回不同的表单,但是我尝试了许多不同的方法,都在 views.py 中,包括:

  1. 直接修改str(form) += "modification"
  2. newform = str(form) + "modification" 返回一个新表单
  3. 在模型中创建不同的帖子,但后来我意识到这行不通,因为我只想要一个帖子

以上都产生了SyntaxError: can't assign to function callTypeError: join() argument must be str or bytes, not 'HttpResponseRedirect'AttributeError: 'str' object has no attribute 'save'等错误,还有一个权限错误说我不能修改表单之类的。

这是来自views.py的sn-p:

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['content']
    title = ['title']   #
    template_name = 'blog/post_new.html'
    success_url = '/'

    def form_valid(self, form):
        #debugging 
        tempvar = (str(form).split('required id="id_content">'))[1].split('</textarea></td>')[0]  #url
        r = requests.get(tempvar)
        tree = fromstring(r.content)
        title = tree.findtext('.//title')
        print(title)

        form.instance.author = self.request.user
        if "http://" in str(form).lower() or "https://" in str(form).lower():
            if tempvar.endswith(' '):   
                return super().form_valid(form)
            elif " http" in tempvar:   
                return super().form_valid(form)
            elif ' ' not in tempvar:
                return super().form_valid(form)
            else:
                return None

models.py:

class Post(models.Model):
    content = models.TextField(max_length=1000)
    title = models.TextField(max_length=500, default='SOME STRING')  #

    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    likes= models.IntegerField(default=0)
    dislikes= models.IntegerField(default=0)

    def __str__(self):
        return (self.content[:5], self.title[:5]) #

    @property
    def number_of_comments(self):
        return Comment.objects.filter(post_connected=self).count()

在 home.html 中,应该显示帖子(连同标题和内容):

                    <a
                            style="color: rgba(255, 255, 255, 0.5) !important;"
                            href="{% url 'post-detail' post.id %}">
                        <p class="mb-4">
                            {{ post.content }}
                            {{ post.title }}  #
                        </p>
                    </a>

我正在修改的原始模板可以在here找到。

非常感谢您的帮助,我很乐意接受任何建议!

Ps:我使用的是 Python 3.7.4

【问题讨论】:

  • formdjango model forms object,它不作为 str 处理。你能在你的问题中解释期望的结果是什么吗?没有它就很难形成有用的答案。
  • @damon 我想自动获取文章的标题并将其显示为标题,而不仅仅是发布链接/内容。不幸的是,我不知道如何将标题添加到表单中以便可以显示... :(

标签: python python-3.x django forms


【解决方案1】:

在您正在谈论的应用程序中创建一个forms.py 文件,它应该如下所示:

from django import forms
from . import models

class YourFormName(forms.ModelForm):
  class Meta:
    model = models.your_model_name
    fields = ['field1', 'field2' ,...] # Here you write the fields of your model, this fields will appear on the form where user post data

然后您将该表单调用到您的 views.py 中,以便 Django 可以将其呈现到您的模板中,如下所示:

def your_view(request, *args, **kwargs):
    if request.method == 'POST':
        form = forms.YourFormName(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user= request.user
            instance.save()
            return redirect('template.html') # To redirect if the form is valid
    else:
        form = forms.YourFormName()
    return render(request, "template.html", {'form': form}) # The template if the form is not valid

最后要做的是创建template.html

{% extends 'base.html' %}

{% block content %}

    <form action="{% url 'the_url_that_renders_this_template' %}" method='POST' enctype="multipart/form-data">
        {% csrf_token %}
        {{ form }}
        <button type="submit">Submit</button>
    </form>

{% endblock content %}

如果您想从以该表单提交的 DB 中获取数据,您可以使用 views.py 中的新函数:

def show_items(request, *args, **kwargs):
    data = YourModelName.objects.all()
    context = {
        "data": data
    }
    return render(request, "show_items.html", context)

然后在show_items.html:

{% extends 'base.html' %}
{% block content %}

{% for item in data %}

{{item.field1}}
{{item.field2}}
...
{{The items you want to show in that template}}

{% enfor %}

{% endblock content %}

这就是你想要做的?如果没有,请添加关于您实际想要做什么的进一步说明

【讨论】:

  • 非常感谢!!澄清一下,这段代码允许我修改用户的输入,对吧? (比如允许我接受用户的表单输入,在用户的输入中添加动态文本,并将用户的输入与添加的文本一起显示)
  • 添加动态文本是什么意思?一个例子可以帮助我理解你真正想要什么
  • 那么您知道 twitter 在链接文章时如何显示文章标题吗?我想这样做,如果用户提交一个链接作为“内容”,我会在链接中添加文章的标题。我已经在 views.py 中编写了其中的手册部分,不过,我只是想知道如何将解析后的标题返回到模板。
  • 我认为您可以调用模板中的对象,例如{{ obj.link }},并且使用某种 JS,甚至使用 HTML 标签,您将能够解析链接并根据该链接显示文本,但我认为这不必处理 Django 本身
  • 非常感谢!!我不太确定如何做一个 JS 或 HTML 标签……你能链接我一些资源或编辑你的答案吗?另外你确定它与请求兼容(它可以导入模块)?
猜你喜欢
  • 1970-01-01
  • 2017-03-23
  • 2023-01-05
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
相关资源
最近更新 更多