Django ошибка got an unexpected keyword argument

I’m trying to create an archive so I pass to the view the arguments year and month.

However, I get an error with the code below and I can’t figure out what it means and how to solve it:

Exception Type: TypeError
Exception Value:    archive() got an unexpected keyword argument 'year_id'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response, line 115

What can be wrong?

views.py

    # loop over years and months
def mkmonth_lst():
    if not Post.objects.count():
        return []
    # set up vars
    year, month = time.localtime()[:2]
    first = Post.objects.order_by("created")[0]
    fyear = first.created.year
    fmonth = first.created.month
    months = []

    # loop over years and months
    for y in range(year, fyear-1, -1):
        start, end = 12, 0
        if y == year: start = month
        if y == fyear: end = fmonth-1

        for m in range(start, end, -1):
            months.append((y, m, month_name[m]))

    return months

def archive(request, year, month):
    posts = Post.objects.filter(created__year=year, created__month=month)
    context = {'PostList': posts, 'Months': mkmonth_lst()}

    return(render, 'archives.html', context)

urls.py

url(r'^archives/(?P<year_id>d+)/(?P<month_id>d+)$', views.archive, name='archives'),

Update:

models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    url = models.URLField(null=True, blank=True)
    video = models.FileField(upload_to = 'video', verbose_name = 'Video', null=True, blank=True)
    picture = models.ImageField(upload_to = 'post', verbose_name = 'Picture')
    tags = TaggableManager()

    def __unicode__(self):
        return self.title

Template

<h3>Archivo</h3>
  <p>
    {% for month in months %}
        {% ifchanged month.0 %} {{ month.0 }} <br /> {% endifchanged %}
            <a href="/blog/archives/{{month.0}}/{{month.1}}">{{ month.2 }}</a> <br />
    {% endfor %}
  </p>

Update 2: error

usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response
            response = middleware_method(request, response) ...
/usr/local/lib/python2.7/dist-packages/django/middleware/common.py in process_response
    if response.status_code == 404: ...


Request Method: GET
Request URL:    http://127.0.0.1:8000/blog/archives/2014/1
Django Version: 1.5
Exception Type: AttributeError
Exception Value:    
'tuple' object has no attribute 'status_code'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/middleware/common.py   in process_response, line 106
Python Executable:  /usr/bin/python
Python Version: 2.7.3
Python Path:    
['/home/fernando/develop/blogmanage',
'/usr/local/lib/python2.7/dist-packages/django_mptt-0.6.0-py2.7.egg',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-control-panel',
'/usr/lib/python2.7/dist-packages/ubuntuone-couch',
'/usr/lib/python2.7/dist-packages/ubuntuone-installer',
'/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
Server time:    Wed, 29 Jan 2014 21:09:56 +0100

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/mixins.py", line 45, in list
    serializer = self.get_serializer(queryset, many=True)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/generics.py", line 110, in get_serializer
    return serializer_class(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 501, in __init__
    raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Ingrediente() got an unexpected keyword argument 'many'

Issue

I just uploaded my app into a production server (Centos7) with migrations via Gitlab and everything works fine, the problem here is that once I want to access through the browser I get this error on my logs:

File "/usr/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 49, in render
    context_instance = RequestContext(request, current_app=current_app)
TypeError: __init__() got an unexpected keyword argument 'current_app'

The weird thing is that everything works properly in my local machine and I can run it without any issue, the only difference in the server side is that I run the server with production-settings (with a configuration for a production server)

Hint: if I run funtions through url, everything runs properly seems the problem is that every time it goes into the «return render» I get that message too.

Thanks for your attention,

Solution

I found out that the issue was because I had an oldest Django folder in my server (1.6 version). I delete all the Django versions, reboot the server and install the one my app uses (1.10.2) and problem was fixed

Answered By — Deluq

Answer Checked By — Robin (WPSolving Admin)

Я пытаюсь перенаправить на страницу, которую я намерен реализовать как домашнюю страницу объекта после создания.

Ниже приведена соответствующая часть моих views.py

            new_station_object.save()
            return HttpResponseRedirect(reverse("home_station", 
                                                kwargs={'pk':   new_station_object.id}
            ))

class StationHome(View):
    def get(self, request):
        return HttpResponse("Created :)")

и соответствующей части моего urls.py;

    url(r'^station/(?P<pk>d+)$', StationHome.as_view(),    name='home_station'),

Но я получаю указанную ошибку;

TypeError at /station/2
get() got an unexpected keyword argument 'pk'

Кто-то, пожалуйста, помогите мне.

I am using Django to create a user and an object when the user is created. 

But there is an error

__init__() got an unexpected keyword argument ‘user’

when calling the register() function in view.py. The function is:

def register(request):  
    '''signup view'''     
    if request.method=="POST":  
        form=RegisterForm(request.POST)  
        if form.is_valid():  
            username=form.cleaned_data["username"]  
            email=form.cleaned_data["email"]  
            password=form.cleaned_data["password"]  
            user=User.objects.create_user(username, email, password)  
            user.save()
            return HttpResponseRedirect('/keenhome/accounts/login/')
        else: 
            form = RegisterForm()      
            return render_to_response("polls/register.html", {'form':form}, context_instance=RequestContext(request))  

    #This is used for reinputting if failed to register    
    else: 
        form = RegisterForm()      
        return render_to_response("polls/register.html", {'form':form}, context_instance=RequestContext(request))

and the object class is:

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, temp=65):
        self.temp=temp

    TURN_ON_OFF = (
        ('ON', 'On'),
        ('OFF', 'Off'),
    )

    TEMP = (
        ('HIGH', 'High'),
        ('MEDIUM', 'Medium'),
        ('LOW', 'Low'),
    )

    on_off = models.CharField(max_length=2, choices=TURN_ON_OFF)
    temp = models.CharField(max_length=2, choices=TEMP)

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        LivingRoom.objects.create(user=instance)

post_save.connect(create_control_livingroom, sender=User)

The Django error page notifies the error information: 

user=User.objects.create_user(username, email, password) and LivingRoom.objects.create(user=instance).

How to solve it?

Понравилась статья? Поделить с друзьями:
  • Dismhost exe ошибка приложения
  • Django обработка ошибок формы
  • Dism ошибка 87 неизвестный параметр cleanup image
  • Django логирование ошибок
  • Dism ошибка 87 неизвестный параметр capture image