首页 > 解决方案 > 没有可重定向到的 URL

问题描述

我正在尝试创建一个页面,用户可以在其中填写这些参数。此代码允许将数据存储在 mysql 中,但不显示保存的数据。并显示“在 /public/about/ 处配置不正确,没有要重定向到的 URL。提供 url 或在模型上定义 get_absolute_url 方法。”

MODELS

class MedicalInfo(models.Model):
    BLOOD = (
        ('A+', 'A+ Type'),
        ('B+', 'B+ Type'),
        ('AB+', 'AB+ Type'),
        ('O+', 'O+ Type'),
        ('A-', 'A- Type'),
        ('B-', 'B- Type'),
        ('AB-', 'AB- Type'),
        ('O-', 'O- Type'),
    )

    @staticmethod
    def toBlood(key):
        for item in MedicalInfo.BLOOD:
            if item[0] == key:
                return item[1]
        return "None"

    patient = models.ForeignKey(User, on_delete=models.CASCADE, related_name="patiento")
    bloodType = models.CharField(max_length=10, choices=BLOOD)
    allergy = models.CharField(max_length=100)
    alzheimer = models.BooleanField()
    asthma = models.BooleanField()
    diabetes = models.BooleanField()
    stroke = models.BooleanField()
    comments = models.CharField(max_length=700)

    def __str__(self):
        return f'{self.user.username} Medinfo'

    def save(self):
        super().save()

VIEWS.PY

class MedinfoCreateView(LoginRequiredMixin, CreateView):
    template_name = 'all_users/public/medinfo.html'
    model = MedicalInfo
    fields = ['bloodType', 'allergy', 'alzheimer', 'asthma', 'diabetes', 'stroke', 'comments']

    def form_valid(self, form):
        form.instance.patient = self.request.user
        return super().form_valid(form)

HTML

{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="content-section">
            <form method="POST">
                {% csrf_token %}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">
                        Medinfo
                    </legend>
                    {{ form|crispy }}
                </fieldset>
                <div class="form-group">
                    <button class="btn btn-outline-info" type="submit">
                        Submit
                    </button>
                </div>
            </form>
    </div>
{% endblock content %}

标签: pythondjangodjango-views

解决方案


提供success_url,因为用户将被重定向到它。您也可以通过指定 get_success_url() 方法来覆盖它。

class GenView(CreateView):
    # Other code
    # If you want simple url
    success_url = "/url/"

    # If you want to redirect dynamically
    get_success_url(self):
        # Some code
        return url

推荐阅读