NoReverseMatch 错误:在视图中使用 POST 请求未找到带参数 ‘my_url’ 的反向匹配。

huangapple go评论78阅读模式
英文:

Django HTMX NoReverseMatch Reverse for 'my_url' with arguments '('',)' not found using POST-request in view

问题

It appears that you're encountering a Django reverse URL resolution issue with your create_cv_workexp view. The error message suggests that the URL reverse for create_cv_workexp is being called with empty arguments.

One common reason for this issue is that the pk argument is not being passed correctly when you make a POST request to the create_cv_workexp view. In your JavaScript or HTML form, make sure you include the pk value as part of the POST request to this view. Double-check that the position.id value is correctly passed when making the POST request.

Here's a checklist to help you troubleshoot:

  1. Verify that position.id is correctly passed when making the POST request to create_cv_workexp.
  2. Check the JavaScript or HTML form that generates the POST request to ensure it includes the pk value.
  3. Make sure there are no typos or errors in the JavaScript or HTML form that could lead to incorrect URL construction.
  4. Ensure that the position.id is available in the context when rendering the template that contains the form.

If you've checked these points and the issue persists, please provide more information about how you're making the POST request and how the position.id is being passed, so I can offer more specific guidance.

英文:

I ran into the following issue on the Django framework using HTMX: django.urls.exceptions.NoReverseMatch: Reverse for 'create_cv_workexp' with arguments '('',)' not found. 1 pattern(s) tried: ['create\\-cv\\-workexp/(?P<pk>[0-9]+)/\\Z']

models.py:

  1. class Position(models.Model):
  2. position_name = models.CharField(max_length=255, blank=True, verbose_name='Position')
  3. created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user by', blank=True, null=True)
  4. date_create = models.DateTimeField(auto_now_add=True)
  5. date_update = models.DateTimeField(auto_now=True)
  6. class Meta:
  7. ordering = ['date_create']
  8. def __str__(self):
  9. return self.position_name
  10. class WorkExperience(models.Model):
  11. pos = models.ForeignKey('Position', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Position Relative')
  12. company = models.CharField(max_length=50, verbose_name='Company', blank=True)
  13. position_work = models.CharField(max_length=50, verbose_name='Position', blank=True)
  14. link_company = models.URLField(verbose_name="Company's link", blank=True)
  15. date_of_employment = models.DateField(blank=True, verbose_name='Date of employment')
  16. date_of_dismissal = models.DateField(blank=True, verbose_name='Date of dismissal')
  17. def __str__(self):
  18. return self.company
  19. class Meta:
  20. ordering = ["-date_of_employment"]

Here are two models two models linked by a ForeignKey.

forms.py:

  1. class CreateCVWorkExperienceForm(forms.ModelForm):
  2. ''' form for WorkExperience object '''
  3. class Meta:
  4. model = resume.models.WorkExperience
  5. fields = ('company',
  6. 'position_work',
  7. 'link_company',
  8. 'date_of_employment',
  9. 'date_of_dismissal')

views.py:

  1. @login_required(login_url='/users/login/')
  2. def create_cv_workexp(request, pk):
  3. ''' main views for displaying form for to add WorkExperience to CV and redirect to HTMX template '''
  4. position = Position.objects.get(id=pk)
  5. workexps = WorkExperience.objects.filter(pos=position)
  6. form = CreateCVWorkExperienceForm(request.POST or None)
  7. if request.method == "POST":
  8. if form.is_valid():
  9. workexp = form.save(commit=False)
  10. workexp.pos = position
  11. workexp.save()
  12. pk = workexp.pk
  13. return redirect("resume:detail-workexp", pk=pk)
  14. else:
  15. return render(request, "resume/partials/workexp_form.html", context={
  16. "form": form
  17. })
  18. context = {
  19. "form": form,
  20. "position": position,
  21. "workexps": workexps,
  22. 'title': 'Add company'
  23. }
  24. return render(request, "resume/create_cv_workexp.html", context)
  25. @login_required(login_url='/users/login/')
  26. def create_workexp_form(request, pk):
  27. ''' view for rendering form of WorkExperience object for adding instnce during creating CV '''
  28. form = CreateCVWorkExperienceForm()
  29. position = {"id": pk}
  30. context = {
  31. "form": form,
  32. "position": position,
  33. }
  34. return render(request, "resume/partials/workexp_form.html", context)
  35. @login_required(login_url='/users/login/')
  36. def detail_workexp(request, pk):
  37. ''' view for rendering added WorkExperience to DB and displaying it on 'resume/create_cv_workexp.html' template '''
  38. workexp = get_object_or_404(WorkExperience, pk=pk)
  39. context = {
  40. "workexp": workexp,
  41. 'pk': pk
  42. }
  43. return render(request, "resume/partials/workexp_detail.html", context)
  44. @login_required(login_url='/users/login/')
  45. def update_workexp(request, pk):
  46. ''' view for updating added WorkExperience '''
  47. workexp = WorkExperience.objects.get(id=pk)
  48. form = CreateCVWorkExperienceForm(request.POST or None, instance=workexp)
  49. if request.method == "POST":
  50. if form.is_valid():
  51. form.save()
  52. return redirect("resume:detail-workexp", pk=workexp.id)
  53. context = {
  54. "form": form,
  55. "workexp": workexp
  56. }
  57. return render(request, "resume/partials/workexp_form.html", context)
  58. @login_required(login_url='/users/login/')
  59. def delete_workexp(request, pk):
  60. ''' view for delete instance of WorkExperience object '''
  61. workexp = get_object_or_404(WorkExperience, id=pk)
  62. if request.method == "POST":
  63. workexp.delete()
  64. return HttpResponse("")
  65. return HttpResponseNotAllowed(
  66. [
  67. "POST",
  68. ]
  69. )

Here in view create_cv_workexp after POST-request i do redirect to url 'resume:detail-workexp' and pass to url the parameter pk which refers to id just saved the instance of object WorkExperience. Then the view create_cv_workexp must be rendres 'resume/create_cv_workexp.html' template because 'resume:detail-workexp' uses dynamic template (about this is next).

urls.py:

  1. app_name = 'resume'
  2. urlpatterns = [
  3. ...
  4. # paths for working with WorWorkExperience objects during creating CV
  5. path('create-cv-workexp/<int:pk>/', views.create_cv_workexp, name='create_cv_workexp'), # here
  6. path('htmx/workexp/<int:pk>/', views.detail_workexp, name="detail-workexp"), # and here
  7. path('htmx/workexp/<int:pk>/update/', views.update_workexp, name="update-workexp"),
  8. path('htmx/workexp/<int:pk>/delete/', views.delete_workexp, name="delete-workexp"),
  9. path('htmx/create-workexp-form/<int:pk>/', views.create_workexp_form, name='create-workexp-form'),
  10. ]

The detail-workexp url calls view detail_workexp in views.py:

  1. @login_required(login_url='/users/login/')
  2. def detail_workexp(request, pk):
  3. ''' view for rendering added WorkExperience to DB and displaying it on 'resume/create_cv_workexp.html' template '''
  4. workexp = get_object_or_404(WorkExperience, pk=pk)
  5. context = {
  6. "workexp": workexp,
  7. 'pk': pk
  8. }
  9. return render(request, "resume/partials/workexp_detail.html", context)

This view rendres template workexp_detail.html:

  1. <div hx-target="this" class="mt-3 py-3 px-3 bg-white shadow border border-gray-100">
  2. <h3 class="text-lg leading-6 font-medium text-gray-900">
  3. Company: {{ workexp.company }}
  4. </h3>
  5. <p class="text-gray-600">Position: {{ workexp.position_work }}</p>
  6. <div class="mt-2">
  7. <button hx-get="{% url 'resume:update-workexp' workexp.id %}" hx-swap="outerHTML"
  8. class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
  9. Update
  10. </button>
  11. <button hx-post="{% url 'resume:delete-workexp' workexp.id %}" hx-swap="outerHTML swap:1s"
  12. class="ml-2 inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-red-700 bg-red-100 hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
  13. Delete
  14. </button>
  15. </div>
  16. </div>

Here is template create_cv_workexp.html:

  1. {% extends 'resume/base.html' %}
  2. {% block content %}
  3. <h2>Add work experience for {{ position.position_name }}</h2>
  4. <hr>
  5. <div class="container">
  6. <button type="button" hx-get="{% url 'resume:create-workexp-form' position.id %}" hx-target="#workexpform" hx-swap="beforeend">
  7. Add work experience
  8. </button>
  9. </div>
  10. <div id="workexpform" class="container"></div>
  11. <div class="container">
  12. {% for workexp in workexps %}
  13. {% include 'resume/partials/workexp_detail.html' %}
  14. {% endfor %}
  15. </div>
  16. {% endblock content %}

Here is template workexp_form.html:

  1. {% load tailwind_filters %}
  2. <div hx-target="this" hx-swap="outerHTML" class="mt-3 py-3 px-3 bg-white shadow border border-gray-100">
  3. <form method="POST">
  4. {% csrf_token %}
  5. {{ form|crispy }}
  6. {% if workexp %}
  7. <button type="submit" hx-post="{% url 'resume:update-workexp' workexp.id %}"
  8. class="inline-flex items-center px-3 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
  9. Submit
  10. </button>
  11. <button hx-get="{% url 'resume:detail-workexp' workexp.id %}" type="button"
  12. class="ml-2 inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
  13. Cancel
  14. </button>
  15. {% else %}
  16. <button type="submit" hx-post="{% url 'resume:create_cv_workexp' position.id %}"
  17. class="inline-flex items-center px-3 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
  18. Submit
  19. </button>
  20. {% endif %}
  21. </form>
  22. </div>

I think i passed all parameters from views to templates and urls, but when i mare POST-request from create_cv_view view i get exception:

  1. Reverse for 'create_cv_workexp' with arguments '('',)' not found. 1 pattern(s) tried: ['create\\-cv\\-workexp/(?P<pk>[0-9]+)/\\Z']

I dont know why reverse for create_cv_workexp view is not working because i pass to url the id of Position object

Next is some screens about this exception:

NoReverseMatch 错误:在视图中使用 POST 请求未找到带参数 ‘my_url’ 的反向匹配。

NoReverseMatch 错误:在视图中使用 POST 请求未找到带参数 ‘my_url’ 的反向匹配。

NoReverseMatch 错误:在视图中使用 POST 请求未找到带参数 ‘my_url’ 的反向匹配。

The headers of request and response:

NoReverseMatch 错误:在视图中使用 POST 请求未找到带参数 ‘my_url’ 的反向匹配。

NoReverseMatch 错误:在视图中使用 POST 请求未找到带参数 ‘my_url’ 的反向匹配。

NoReverseMatch 错误:在视图中使用 POST 请求未找到带参数 ‘my_url’ 的反向匹配。

Here is full traceback of exception:

  1. Internal Server Error: /create-cv-workexp/3/
  2. Traceback (most recent call last):
  3. File "D:\virtualenv\mysite\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
  4. response = get_response(request)
  5. ^^^^^^^^^^^^^^^^^^^^^
  6. File "D:\virtualenv\mysite\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
  7. response = wrapped_callback(request, *callback_args, **callback_kwargs)
  8. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  9. File "D:\virtualenv\mysite\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view
  10. return view_func(request, *args, **kwargs)
  11. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  12. File "D:\python_projects\my_site\mysite\resume\views.py", line 286, in create_cv_workexp
  13. return render(request, "resume/partials/workexp_form.html", context={
  14. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  15. File "D:\virtualenv\mysite\Lib\site-packages\django\shortcuts.py", line 24, in render
  16. content = loader.render_to_string(template_name, context, request, using=using)
  17. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  18. File "D:\virtualenv\mysite\Lib\site-packages\django\template\loader.py", line 62, in render_to_string
  19. return template.render(context, request)
  20. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  21. File "D:\virtualenv\mysite\Lib\site-packages\django\template\backends\django.py", line 61, in render
  22. return self.template.render(context)
  23. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  24. File "D:\virtualenv\mysite\Lib\site-packages\django\template\base.py", line 175, in render
  25. return self._render(context)
  26. ^^^^^^^^^^^^^^^^^^^^^
  27. File "D:\virtualenv\mysite\Lib\site-packages\django\template\base.py", line 167, in _render
  28. return self.nodelist.render(context)
  29. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  30. File "D:\virtualenv\mysite\Lib\site-packages\django\template\base.py", line 1005, in render
  31. return SafeString("".join([node.render_annotated(context) for node in self]))
  32. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  33. File "D:\virtualenv\mysite\Lib\site-packages\django\template\base.py", line 1005, in <listcomp>
  34. return SafeString("".join([node.render_annotated(context) for node in self]))
  35. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  36. File "D:\virtualenv\mysite\Lib\site-packages\django\template\base.py", line 966, in render_annotated
  37. return self.render(context)
  38. ^^^^^^^^^^^^^^^^^^^^
  39. File "D:\virtualenv\mysite\Lib\site-packages\django\template\defaulttags.py", line 321, in render
  40. return nodelist.render(context)
  41. ^^^^^^^^^^^^^^^^^^^^^^^^
  42. File "D:\virtualenv\mysite\Lib\site-packages\django\template\base.py", line 1005, in render
  43. return SafeString("".join([node.render_annotated(context) for node in self]))
  44. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  45. File "D:\virtualenv\mysite\Lib\site-packages\django\template\base.py", line 1005, in <listcomp>
  46. return SafeString("".join([node.render_annotated(context) for node in self]))
  47. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  48. File "D:\virtualenv\mysite\Lib\site-packages\django\template\base.py", line 966, in render_annotated
  49. return self.render(context)
  50. ^^^^^^^^^^^^^^^^^^^^
  51. File "D:\virtualenv\mysite\Lib\site-packages\django\template\defaulttags.py", line 471, in render
  52. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  53. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  54. File "D:\virtualenv\mysite\Lib\site-packages\django\urls\base.py", line 88, in reverse
  55. return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  56. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  57. File "D:\virtualenv\mysite\Lib\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix
  58. raise NoReverseMatch(msg)
  59. django.urls.exceptions.NoReverseMatch: Reverse for 'create_cv_workexp' with arguments '('',)' not found. 1 pattern(s) tried: ['create\\-cv\\-workexp/(?P<pk>[0-9]+)/\\Z']
  60. [17/May/2023 21:00:03] "POST /create-cv-workexp/3/ HTTP/1.1" 500 150333

So i really don't know what's wrong... I didn't find the solution in Stack Overflow and other sources... Please help!!!

答案1

得分: 0

workexp_form.html 中还使用了 position,但上下文中未提及:

  1. {% else %}
  2. <button type="submit" hx-post="{% url 'resume:create_cv_workexp' position.id %}"
  3. class="inline-flex items-center px-3 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
  4. 提交
  5. </button>
  6. {% endif %}
  1. else:
  2. return render(request, "resume/partials/workexp_form.html", context={
  3. "form": form
  4. })
英文:

in workexp_form.html you also use position but it is not in the context:

  1. {% else %}
  2. <button type="submit" hx-post="{% url 'resume:create_cv_workexp' position.id %}"
  3. class="inline-flex items-center px-3 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
  4. Submit
  5. </button>
  6. {% endif %}
  1. else:
  2. return render(request, "resume/partials/workexp_form.html", context={
  3. "form": form
  4. })

huangapple
  • 本文由 发表于 2023年5月18日 03:12:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定