NoReverseMatch位于/ create /

时间:2020-02-23 20:22:25

标签: python django

我想创建一个系统。对于这个系统,我需要耐心地创建表格。单击按钮后,我可以保存患者,但是按下按钮后会出现错误页面。

带有关键字参数'{'slug':'title-1'}'的'create'相反 找到了。尝试了1个模式:['create / $']

我的错误在哪里?非常感谢。

views.py

def patient_create(request):

    if not request.user.is_authenticated:
        return render(request, "http404.html")

    form = PatientForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        post = form.save(commit=False)
        post.user = request.user
        post.save()
        messages.Info(request, "Success!!")
        return HttpResponseRedirect(newPatients.get_absolute_url())

    context = {
        'form': form
    }

    return render(request, "patient_form.html", context)

models.py

class newPatients(models.Model):

title = models.CharField(max_length=100)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
created_date = models.DateTimeField(default=timezone.now)
dept = models.TextField()
address = models.TextField()
phone = models.CharField(max_length=15)
notes = RichTextField(verbose_name="notes")
slug = models.SlugField(max_length=100,unique=True, editable=False)

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

def __str__(self):
    return self.title

def get_create_url(self):
    return reverse('post:create', kwargs={'slug': self.slug})

def get_unique_slug(self):
    slug = slugify(self.title.replace('ı', 'i'))
    unique_slug = slug
    counter = 1
    while newPatients.objects.filter(slug=unique_slug).exists():
        unique_slug = '{}-{}'.format(slug, counter)
        counter += 1
    return unique_slug

def get_absolute_url(self):
    return reverse('post:create', kwargs={'slug': self.slug})

def save(self, *args, **kwargs):
    self.slug = self.get_unique_slug()
    return super(newPatients, self).save(*args, **kwargs)

class Meta:
    ordering = ['-created_date']

回溯

    Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/create/

Django Version: 2.2.9
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'users',
 'patients',
 'widget_tweaks',
 'crispy_forms',
 'ckeditor']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\edeni\senior\pharsys\patients\views.py" in patient_create
  31.         return HttpResponseRedirect(newPatients.get_absolute_url())

Exception Type: TypeError at /create/
Exception Value: get_absolute_url() missing 1 required positional argument: 'self'

1 个答案:

答案 0 :(得分:3)

您需要在构造的patient上而不是在newPatients类上调用方法:

from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required

@login_required
def patient_create(request):
    if request.method == 'POST':
        form = PatientForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.user = request.user
            patient = form.save()
            messages.Info(request, "Success!!")
            return redirect(patient)
    else:
        form = PatientForm()
    # …

请注意,通常模型名称不会与特定操作关联,因此newPatients有点 odd Patient可能是一个更好的名字。

此外,您最好在此处使用redirect(..) [Django-doc],因为这会自动为模型实例调用get_absolute_url

最后,您可以使用@login_required decorator [Django-doc]使用统一的方式来强制用户已登录。