【问题标题】:Django error on contact form - join() argument must be str, bytes, or os.PathLike object,联系表单上的 Django 错误 - join() 参数必须是 str、bytes 或 os.PathLike 对象,
【发布时间】:2021-03-26 22:43:55
【问题描述】:

我正在尝试为我的学校项目创建一个联系表单,但收到此错误并且不知道它是什么意思。

我正在根据另一个可以正常工作的表单创建此表单。

我试过谷歌搜索,但无法理解问题所在。

请问有人能解释一下吗?

错误:


Traceback (most recent call last):
  File "c:\users\01\appdata\local\programs\python\python39\lib\ntpath.py", line 91, in join
    for p in map(os.fspath, paths):

During handling of the above exception (expected str, bytes or os.PathLike object, not dict), another exception occurred:
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\Project\bsp\store\contact\views.py", line 11, in get
    return render("contact.html", context)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string
    template = get_template(template_name, using=using)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\template\loader.py", line 15, in get_template
    return engine.get_template(template_name)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\template\backends\django.py", line 34, in get_template
    return Template(self.engine.get_template(template_name), self)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\template\engine.py", line 143, in get_template
    template, origin = self.find_template(template_name)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\template\engine.py", line 125, in find_template
    template = loader.get_template(name, skip=skip)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\template\loaders\base.py", line 18, in get_template
    for origin in self.get_template_sources(template_name):
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources
    name = safe_join(template_dir, template_name)
  File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\utils\_os.py", line 17, in safe_join
    final_path = abspath(join(base, *paths))
  File "c:\users\01\appdata\local\programs\python\python39\lib\ntpath.py", line 117, in join
    genericpath._check_arg_types('join', path, *paths)
  File "c:\users\01\appdata\local\programs\python\python39\lib\genericpath.py", line 152, in _check_arg_types
    raise TypeError(f'{funcname}() argument must be str, bytes, or '

admin.py

class ContactAdmin(admin.ModelAdmin):
    list_display = ['firstname', 'lastname', 'email', 'subject']
    list_per_page = 20

admin.site.register(Contact, ContactAdmin)

forms.py

class ContactForm(forms.Form):
    firstname=forms.CharField()
    lastname=forms.CharField()
    email = forms.EmailField()
    subject = forms.Textarea()

models.py

class Contact(models.Model):
    firstname=models.CharField(max_length=200)
    lastname=models.CharField(max_length=200)
    email=models.EmailField(null=False)
    subject=models.TextField()

    def __str__(self):
        return f'{self.lastname}, {self.firstname}, {self.email}'

urls.py

urlpatterns = [
    path('', ContactView.as_view(), name='contact'),
]

views.py

class ContactView(View):
    def get(self, *args, **kwargs):
        form = ContactForm()
        context = {'form': form}
        return render("contact.html", context)
        
    def post(self, *args, **kwargs):
        form = ContactForm(self.request.POST) 
        if form.is_valid():
            firstname = form.cleaned_data.get('firstname')
            lastname = form.cleaned_data.get('lastname')
            email = form.cleaned_data.get('email')
            subject= form.cleaned_data.get('subject')
            contact = Contact()
            contact.firstname = firstname
            contact.lastname = lastname 
            contact.email = email
            contact.subject = subject
            contact.save()
            messages.info(self.request, "Your message has been received.")
            return render('thanks_contact.html')

项目网址

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('',include('shop.urls')),
    path('search/',include('search_app.urls')),
    path('cart/', include('cart.urls')),
    path('contact/', include('contact.urls')),
    path('order/',include('order.urls')),
    path('blog/', include('blog.urls')),
    path('vouchers/',include('vouchers.urls',namespace='vouchers'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

contact.html

{% extends "base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block title %}
    Contact 
{% endblock %}
{% block content %}
    <div class = "container">
    <h2>Contact</h2>
    <form method="POST">
    {% csrf_token %}
    {{ form|crispy }}
    <button type='submit' class="btn btn-primary my-3">Submit</button> 
    </form>
    </div>
        
{% endblock content%}

【问题讨论】:

  • 你让我们猜测错误在哪里。请更新问题以包含完整的错误回溯消息。
  • 是的,对不起,它是说问题的代码太多。我已经包含了完整的回溯
  • 我认为在 urls.py 中你想要ContactView.as_view(),而不仅仅是ContactView
  • 我试过了,但没有成功

标签: python django django-views django-forms django-templates


【解决方案1】:

这是您需要添加的更改

在网址中:

    from django.urls import path
    from .views import ContactView


    urlpatterns = [
        path('', ContactView.as_view(), name='contact'), #add as_view()
    ]

在视图中:

    from django.shortcuts import render
    from .forms import ContactForm
    from django.views import View
    from .models import Contact
    from django.contrib import messages



    class ContactView(View):
        def get(self,request, *args, **kwargs): #add request
            form = ContactForm()
            context = {'form': form}
            return render(request,"contact.html", context) #add request 
        pass
        def post(self,request, *args, **kwargs): #add request
            form = ContactForm(self.request.POST) 
            if form.is_valid():
                firstname = form.cleaned_data.get('firstname')
                lastname = form.cleaned_data.get('lastname')
                email = form.cleaned_data.get('email')
                subject= form.cleaned_data.get('subject')
                contact = Contact()
                contact.firstname = firstname
                contact.lastname = lastname 
                contact.email = email
                contact.subject = subject
                contact.save()
                messages.info(self.request, "Your message has been received.")
                context = {'form':form} #add context
                return render(request,'thanks_contact.html',context) #add request and context

在表格中:

    from django import forms

    class ContactForm(forms.Form):
        firstname=forms.CharField()
        lastname=forms.CharField()
        email = forms.EmailField()
        subject = forms.CharField(widget=forms.Textarea) # pass textarea as widget

【讨论】:

  • 我重新构建了您的这部分代码,并验证了它,您是否更改了我添加的所有注释行?
  • 好的,那么错误现在说什么?因为 -join() 参数必须是 str、bytes 或 os.PathLike 对象,是由于缺少 'request'
  • 什么forma/contact.html,试过了,forms/
  • 我的错,这只是我的 html 文件路径,坚持使用你的,以便它可以工作,我会在答案中纠正它们
  • 确定表单呈现,但提交未定义名称“上下文”
猜你喜欢
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
  • 2022-12-08
相关资源
最近更新 更多