Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django is throwing TypeError: _wrapped_view() missing 1 required positional argument: 'request'

Can someone please help me fix this error: _wrapped_view() missing 1 required positional argument: 'request'? I am still learning. I am not even what the error means other than that I am missing a request somewhere.

If it helps, what I am trying to do is create a ModelForm that allows users to add content to the site, once they are logged in.

Any help and explanation of what I am doing wrong will be greatly appreciated. Thank you in advance.

Here are my models:

from django.db import models
from cloudinary.models import CloudinaryField

import numpy as np


class Model(models.Model):
    name = models.CharField(max_length=200)
    instagram = models.CharField(max_length=200, default='')
    twitter = models.CharField(max_length=200, default='')
    pinterest = models.CharField(max_length=200, default='')
    snapchat = models.CharField(max_length=200, default='')
    likes = models.IntegerField(default=0)
    views = models.IntegerField(default=0)

    def average_rating(self):
        all_ratings = map(lambda x: x.rating, self.review_set.all())
        return  np.mean(all_ratings)

    def __str__(self):
        return self.name

class Review(models.Model):
    RATING_CHOICES = (
    (1, '1'),
    (2, '2'),
    (3, '3'),
    (4, '4'),
    (5, '5'),
    (6, '6'),
    (7, '7'),
    (8, '8'),
    (9, '9'),
    (10, '10'),
    )
    model = models.ForeignKey(Model)
    pub_date = models.DateTimeField('date published')
    user_name =  models.CharField(max_length=100)
    comment = models.CharField(max_length=200)
    rating = models.IntegerField(choices=RATING_CHOICES)

class Index(models.Model):
    model = models.ForeignKey(Model)
    review = models.ForeignKey(Review)

    class Meta:
        verbose_name = 'index'
        verbose_name_plural = 'indices'

Views:

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from cloudinary.forms import cl_init_js_callbacks      

from .models import Review, Model, Index
from .forms import ReviewForm, ModelAddForm
import datetime

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from django.template import RequestContext

def index(request):
    context = RequestContext(request)
    model_list = Model.objects.order_by('-likes')
    context_dict = {'models': model_list}
    return render(request, 'reviews/index.html', context_dict, context)

def review_list(request):
    latest_review_list = Review.objects.order_by('-pub_date')[:9]
    context = {'latest_review_list':latest_review_list}
    return render(request, 'reviews/review_list.html', context)

def review_detail(request, review_id):
    review = get_object_or_404(Review, pk=review_id)
    return render(request, 'reviews/review_detail.html', {'review': review})

def model_list(request):
    model_list = Model.objects.order_by('-name')
    context = {'model_list':model_list}
    return render(request, 'reviews/model_list.html', context)

def model_detail(request, model_id):
    model = get_object_or_404(Model, pk=model_id)
    return render(request, 'reviews/model_detail.html', {'model': model})

@login_required
def add_review(request, model_id):
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            rating = form.cleaned_data['rating']
            comment = form.cleaned_data['comment']
            user_name = form.cleaned_data['user_name']
            user_name = request.user.username
            review = Review()
            review.model = model
            review.user_name = user_name
            review.rating = rating 
            review.pub_date = datetime.datetime.now()
            review.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return HttpResponseRedirect('reviews:model_detail', args=(model.id,))

        else:
            form = ReviewForm()

        return render(request, 'reviews/model_detail.html', {'form': form})

@method_decorator(login_required)
def add_model(request):

    if request.method == 'POST':
        form = ModelAddForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            likes = form.cleaned_data['likes']
            views = form.cleaned_data['views']
            instagram = form.cleaned_data['instagram']
            twitter = form.cleaned_data['twitter']
            snapchat = form.cleaned_data['snapchat']
            pinterest = form.cleaned_data['pinterest']

            return HttpResponseRedirect('reviews:model_review')

    else:
            form = ModelAddForm

    return render(request, 'reviews/add_model_detail.html', {'form': form})

def user_review_list(request, username=None):
    if not username:
        username = request.user.username
    latest_review_list = Review.objects.filter(user_name=username).order_by('-pub_date')
    context = {'latest_review_list':latest_review_list, 'username':username}
    return render(request, 'reviews/user_review_list.html', context)

def upload(request):
    context = dict( backend_form = PhotoForm())

    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        context['posted'] = form.instance
        if form.is_valid():
            form.save()

    return render(request, 'upload.html', context)

URLs:

from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    url(r'^$', views.review_list, name='review_list'),
    url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),
    url(r'^model/$', views.model_list, name='model_list'),
    url(r'^model/(?P<model_id>[0-9]+)/$', views.model_detail, name='model_detail'),
    url(r'^model/(?P<model_id>[0-9]+)/add_review/$', views.add_review, name='add_review'),
    url(r'^review/user/(?P<username>\w+)/$', views.user_review_list, name='user_review_list'),
    url(r'^review/user/$', views.user_review_list, name='user_review_list'),
    url(r'^model/add_model/$', views.add_model, name='add_model'),
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Template:

{% extends 'review/base.html' %}
{% load static %}
{% load cloudinary %}

{% block content %}
<h1>Add a Category</h1>

        <form id="category_form" method="post">

            {% csrf_token %}

            {{ form }}

            <input type="submit" name="submit" value="Add Model" />
        </form>

{% endblock %}

Traceback:

    Environment:


    Request Method: GET
    Request URL: http://localhost:8000/reviews/model/add_model/

    Django Version: 1.9.1
    Python Version: 3.5.1
    Installed Applications:
    ['django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'reviews']
    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.auth.middleware.SessionAuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware']


Traceback:

    File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\core\handlers\base.py" in get_response
      149.                     response = self.process_exception_by_middleware(e, request)

    File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\core\handlers\base.py" in get_response
      147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

    File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\utils\decorators.py" in _wrapper
      67.             return bound_func(*args, **kwargs)

    Exception Type: TypeError at /reviews/model/add_model/
    Exception Value: _wrapped_view() missing 1 required positional argument: 'request'

Edit: Added missing single quote.

I've changed the decorator. However, I've gotten a new error.

Traceback:

Environment:


Request Method: GET
Request URL: http://localhost:8000/reviews/model/add_model/

Django Version: 1.9.1
Python Version: 3.5.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'reviews']
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.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template C:\Users\xxxxx\Desktop\Apps\thots\templates\reviews\add_model_detail.html, error at line 0
   Reverse for 'model_detail' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['reviews/model/(?P<model_id>[0-9]+)/$']   1 : {% extends 'reviews/base.html' %}
   2 : {% load static %}
   3 : 
   4 : {% block content %}
   5 : <h1>Add a Model</h1>
   6 : 
   7 :         <form id="add_model_form" method="post">
   8 : 
   9 :             {% csrf_token %}
   10 : 

Traceback:

File "C:\Users\xxxx\Anaconda3\lib\site-packages\django\core\urlresolvers.py" in reverse
  586.                 extra, resolver = resolver.namespace_dict[ns]

During handling of the above exception ('thots.reviews'), another exception occurred:

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\defaulttags.py" in render
  507.                               current_app=current_app)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\core\urlresolvers.py" in reverse
  596.                                          key)

During handling of the above exception ('thots.reviews' is not a registered namespace), another exception occurred:

File "C:\Users\xxxxxx\Anaconda3\lib\site-packages\django\core\handlers\base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\core\handlers\base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\Users\xxxxx\Desktop\Apps\thots\reviews\views.py" in add_model
  83.   return render(request, 'reviews/add_model_detail.html', {'form': form})

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\shortcuts.py" in render
  67.             template_name, context, request=request, using=using)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\loader.py" in render_to_string
  97.         return template.render(context, request)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\backends\django.py" in render
  95.             return self.template.render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in render
  206.                     return self._render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in _render
  197.         return self.nodelist.render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in render
  988.                 bit = node.render_annotated(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in render_annotated
  955.             return self.render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in _render
  197.         return self.nodelist.render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in render
  988.                 bit = node.render_annotated(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in render_annotated
  955.             return self.render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in render
  988.                 bit = node.render_annotated(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\base.py" in render_annotated
  955.             return self.render(context)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\defaulttags.py" in render
  513.                         six.reraise(*exc_info)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\utils\six.py" in reraise
  686.         raise value

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\template\defaulttags.py" in render
  499.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\core\urlresolvers.py" in reverse
  600.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "C:\Users\xxxxx\Anaconda3\lib\site-packages\django\core\urlresolvers.py" in _reverse_with_prefix
  508.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /reviews/model/add_model/
Exception Value: Reverse for 'model_detail' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['reviews/model/(?P<model_id>[0-9]+)/$']
like image 625
user2901792 Avatar asked Feb 01 '16 02:02

user2901792


1 Answers

Change @method_decorator(login_required) to @login_required

The method_decorator decorator is used to transform a function decorator into a method decorator.

@login_required
def add_review(request, model_id):
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            rating = form.cleaned_data['rating']
            comment = form.cleaned_data['comment']
            user_name = form.cleaned_data['user_name']
            user_name = request.user.username
            review = Review()
            review.model = model
            review.user_name = user_name
            review.rating = rating 
            review.pub_date = datetime.datetime.now()
            review.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return HttpResponseRedirect('reviews:model_detail', args=(model.id,))

        else:
            form = ReviewForm()

        return render(request, 'reviews/model_detail.html', {'form': form})

@login_required
def add_model(request):

    if request.method == 'POST':
        form = ModelAddForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            likes = form.cleaned_data['likes']
            views = form.cleaned_data['views']
            instagram = form.cleaned_data['instagram']
            twitter = form.cleaned_data['twitter']
            snapchat = form.cleaned_data['snapchat']
            pinterest = form.cleaned_data['pinterest']

            return HttpResponseRedirect('reviews:model_review')

    else:
            form = ModelAddForm

    return render(request, 'reviews/add_model_detail.html', {'form': form})
like image 138
Anoop Avatar answered Nov 17 '22 19:11

Anoop