What does "_wrapped_view() takes at least 1 argument" error mean? - python

I am rendering the Django form data to a template but every time when i visit to the url it shows me this error:
_wrapped_view() takes at least 1 argument (0 given)
Method in views.py:
#login_required
def subnet_network_detail(request):
if request.method == 'POST':
form = NetworkCreateForm(request.POST)
if form.is_valid():
subnet = form.data['Subnet_Address']
ip = form.data['IP_Address']
user_hosts = get_hosts(user=request.user)
hosts_list = host_subnet(user_hosts,subnet,ip)
import pdb;pdb.set_trace()
extra_context = {
'hosts_list': hosts_list
}
return direct_to_template(request, 'networks/subnet_network.html',extra_context)
and urls.py:
url(r'^network/netmask/select/$',
'subnet_network_detail', name='subnet_network_detail')
I read from the other questions about this error but didn't get any idea. How to solve it?

direct_to_template is designed to be used in your urls.py:
url(r'^network/netmask/select/$', 'direct_to_template', {'template':'networks/subnet_network.html'}, name='subnet_network_detail')
You should be using render or render_to_response from within a view.
If you are using django 1.3 or later you can use:
from django.shortcuts import render
...
return render('networks/subnet_network.html', extra_context)
Or if you are using an earlier version:
from django.shortcuts import render_to_response
from django.template import RequestContext
...
return render_to_response('networks/subnet_network.html', extra_context, RequestContext(request))

Related

userpost() got an unexpected keyword argument 'instance'

I am practicing a little CRUD project in django.
here is the views.py of crudproject
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect, render
from .models import userpost
from .forms import customerform
#creating postdate
def create(request):
form= customerform()
if request.method=='POST':
Form=customerform(request.POST)
if Form.is_valid():
Form.save()
Form={}
context ={'form':form}
return render(request,'create.html',context)
#reading the post
def read(request):
user_data=userpost.objects.all()
context ={ 'user_data':user_data}
return render(request,'read.html',context)
#Updating the post
def update(request,pk):
get_user_data=get_object_or_404(userpost,pk=pk)
form= userpost(instance=get_user_data)
if request.method=='POST':
form=userpost(request.POST,isinstance=get_user_data)
if form.is_valid():
form.save()
messages.success(request,'User data has been Updated')
return redirect('read')
context={'form':form}
return render(request,'update.html',context)
#deleting the post
def delete(request,pk):
get_user=get_object_or_404(userpost,pk=pk)
get_user.delete()
messages.error(request,'User deleted')
return redirect('/')
urls.py of crud project
from django.urls import path
from .import views
urlpatterns = [
path('new/',views.create,name='create'),
path('update<int:pk>/',views.update,name='update'),
path('delete/<int:pk>/',views.delete,name='delete'),
path('',views.read,name='read')
]
but the server says
TypeError at /update8/
userpost() got an unexpected keyword argument 'instance'
Request Method: GET
Request URL: http://localhost:8000/update8/
Django Version: 3.2.8
Exception Type: TypeError
Exception Value:
userpost() got an unexpected keyword argument 'instance'
Exception Location: C:\Users\ITS\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py, line 503, in __init__
please help me to figure this out.it would be so much helpful if you give me a little explaination. Thanks in advance
In your update view, you use userpost as a model, not a form. You thus should (and perhaps first define) a form that works on a userpost, so:
def update(request,pk):
get_user_data = get_object_or_404(userpost,pk=pk)
if request.method=='POST':
# &downarrow; work with a form
form = UserPostForm(request.POST, request.FILES, instance=get_user_data)
if form.is_valid():
form.save()
messages.success(request,'User data has been Updated')
return redirect('read')
else:
# &downarrow; work with a form
form= UserPostForm(instance=get_user_data)
context={'form':form}
return render(request,'update.html',context)
In the urls.py, you also forgot a slash (/) between update and the primary key:
urlpatterns = [
# …
# slash &downarrow;
path('update/<int:pk>/',views.update,name='update'),
# …
]

Django 1.11.17 TypeError: 'context must be a dict rather than Context', except IT IS A DICT

I have recently switched from Django 1.9 to 1.11.17 and one thing is bothering me a lot. There is this error that says
TypeError at /somepath
context must be a dict rather than Context
The line that is throwing it is:
return render(request=request, template_name="mytemplate.html", context={"form": form, "update": updateType})
There are many answers on SO where people use RequestContext or Context instead of dict for context and switching to dict solves their problem. But not for me. Here I am pretty sure that my context is in fact a dict. What is interesting if I change it to:
return render(request=request, template_name="mytemplate.html", context={})
The error goes away, but obviously causes another error later on. Do you guys have any idead on what am I doing wrong here?
EDIT:
My imports:
from django.shortcuts import render, render_to_response
from django.template.context import RequestContext, Context
I have tried bot render and render_to_response with similar effect. Also using Context or RequestContext gave similar error.
EDIT2: More code for reference
from django.http import (
HttpResponseRedirect,
HttpResponseBadRequest,
)
from django.shortcuts import render, render_to_response
from django.template import RequestContext, Context
from django.utils.html import escape
# some more imports, but from local files, not django
def update_my_template(request):
user = request.user
# preform some checks for user
...
if request.method == "GET":
updateType = request.GET.get("id")
if updateType:
form = None
if updateType == "something":
form = SomeForm(user)
if updateType == "something else":
form = DifferentForm()
if form is None:
return HttpResponseRedirect("/somepage")
# This was the code that worked in 1.9
rctx = RequestContext(
request, {"form": form, "update": updateType}
)
return render_to_response("mytemplate.html", rctx)
# some different cases, but the error is thrown already
...
Neither of these work:
dictctx = {"form": form, "update": updateType}
return render(request=request, template_name="mytemplate.html", dictctx)
.
ctx = Context({"form": form, "update": updateType})
return render(request=request, template_name="mytemplate.html", ctx)
.
ctx = Context({"form": form, "update": updateType})
return render(request=request, template_name="mytemplate.html", ctx.flatten())
.
rctx = RequestContext(request, {"form": form, "update": updateType})
return render_to_response("mytemplate.html", rctx.flatten())
The render logic is different, depending on what you pass to render:
def render(self, context):
"Display stage -- can be called many times"
with context.render_context.push_state(self):
if context.template is None:
with context.bind_template(self):
context.template_name = self.name
return self._render(context)
else:
return self._render(context)
and it looks as though you may be able to change your parameter template_name to just be name but your object doesn't have a context.render_context value which is why it would be better to create and use an instance of a Context
https://docs.djangoproject.com/en/1.11/_modules/django/template/base/#Template.render
The docs show passing an actual instance of a Context so I recommend that you do that in your code instead of just passing a dict:
>>> from django.template import Context, Template
>>> template = Template("My name is {{ my_name }}.")
>>> context = Context({"my_name": "Adrian"})
>>> template.render(context)
"My name is Adrian."
>>> context = Context({"my_name": "Dolores"})
>>> template.render(context)
so the easiest way to fix your code would be something like this:
from django.template import Context
...
return render(request=request, template_name="mytemplate.html", context=Context({"form": form, "update": updateType}))
Ok, after some more digging (in "unresolved" questions) I found this gem. And yep, that was solution to my problem. Basically I had the line {{form|bootstrap}} in my mytemplate.html which was causing this.
Even better, updating the django-bootstrap-form to version 3.4 allowed me to keep the {{form|bootstrap}} and get rid of the error.
Always pass the variables/values in parameters. But You give both at a same time. Try this as,...
return render(request=request, template_name="mytemplate.html",
{"form": form, "update": updateType})
Or
context={"form": form, "update": updateType} return
render(request=request, template_name="mytemplate.html",context)

In Django is it possible to specify separate `http` verbs with same urlpattern?

I am creating a registration form in Django 2.1. In the typical examples people are using same views method both for showing forms and accepting POST request from forms like following:
In urls.py:
urlpatterns = [
path('auth/register', auth.register, name='register')
]
and in the view named auth.py:
from django.shortcuts import render
from blog_admin.forms import SignUpForm
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
# do registration stuff...
else:
form = SignUpForm()
return render(request, 'blog_admin/auth/register.html', {'form': form})
but I want to use separate method for showing the form and handling registration process and also want to use identical urlpatterns one with GET and one with POST functionality, like following:
in urls.py
urlpatterns = [
# can we limit it range, so that it only works for GET request
path('auth/register', auth.show_registration_form, name='register_show'),
# can we limit it range, so that it only works for POST request
path('auth/register', auth.register, name='register')
]
and in the view named auth.py:
from django.shortcuts import render
from blog_admin.forms import SignUpForm
from django.contrib.auth.forms import UserCreationForm
def show_registration_form(request):
form = SignUpForm()
return render(request, 'blog_admin/auth/register.html', {'form': form})
def register(request):
# do registration stuff...
If need some more example from other frameworks, in php Laravel it would have been done by following:
Route::get('auth/register', ['as' => 'register_show', 'uses' => 'Auth\AuthController#show_registration_form']);
Route::post('auth/register', ['as' => 'register', 'uses' => 'Auth\AuthController#register']);

How to redirect from a view to another view In Django

This is a view written for my posts app in Django. The problem is that after filling the update form and submitting it happens successfully. But it creates confusion for the user because the same HTML page is there and how can I redirect into the updated object?
def post_update(request,id=None):
instance=get_object_or_404(Post,id=id)
if instance.created_user != request.user.username :
messages.success(request, "Post owned by another user, You are having read permission only")
return render(request,"my_blog/denied.html",{})
else :
form=PostForm(request.POST or None,request.FILES or None,instance=instance)
if form.is_valid():
instance=form.save(commit=False)
instance.save()
context={ "form":form,
"instance":instance }
return render(request,"my_blog/post_create.html",context)
As already suggested by #mdegis you can use the Django redirect function to redirect to another view or url.
from django.shortcuts import redirect
def view_to_redirect_to(request):
#This could be the view that handles the display of created objects"
....
perform action here
return render(request, template, context)
def my_view(request):
....
perform form action here
return redirect(view_to_redirect_to)
Read more about redirect here and here
You can pass positional or keyword argument(s) to the redirect shortcut using the reverse() method and the named url of the view you're redirecting to.
In urls.py
from news import views
url(r'^archive/$', views.archive, name='url_to_redirect_to')
In views.py
from django.urls import reverse
def my_view(request):
....
return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value}))
More about reverse Here
You can use redirect from http shortcuts.
from django.shortcuts import redirect
def my_view(request):
...
object = MyModel.objects.get(...)
return redirect(object) #or return redirect('/some/url/')
Here is the link to official docs.
To redirect from a view to another view, you need to give the conbination of the app name "myapp", colon ":" and the view name "dest_view" which is set in the path in "myapp/urls.py" as shown below. And, you don't need to modify the path in "myapp/urls.py" if you pass data with session with request.session['key'] as shown below:
# "myapp/views.py"
from django.shortcuts import render, redirect
def redirect_view(request):
# Here
request.session['person'] = {'name': 'John', 'age': 27}
# Here
return redirect("myapp:dest_view")
def destination_view(request):
return render(request, 'myapp/index.html', {})
You need to give the view name "dest_view" to path() in "myapp/urls.py" as shown below:
# "myapp/urls.py"
from django.urls import path
from . import views
app_name = "myapp"
urlpatterns = [ # This is view name
path('dest/', views.destination_view, name="dest_view")
]
Then, this is Django Template:
# "myapp/index.html"
{{ request.session.person.name }} {# John #}
{{ request.session.person.age }} {# 27 #}
from django.urls import reverse
def my_view(request):
....
return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value(object.id for specific id)}))

Django: View "didn't return an HttpResponse object"

I am recieving the following error for not returning an httpresponse object when submitting a form, and I cannot really understand why:
Exception Type: ValueError at /contact/addcontact
Exception Value: The view openshift.contactapplication.views.contact didn't return an HttpResponse object.
Here is my view:
# Create your views here.
from django.shortcuts import render_to_response, render
from django.http import HttpResponseRedirect, HttpResponse
#forms imports
from contactapplication.forms import applicantsForm
#model imports
from contactapplication.models import applicantsModel
def contact(request):
if request.method == 'POST':
form = applicantsForm(request.POST)
if form.is_valid():
clean_form =form.cleaned_data
collect = applicantsModel(first_name=clean_form['first_name'], last_name=clean_form['last_name'],
linkedin_profile=clean_form['linkedin_profile'], elevator_pitch=clean_form['elevator_pitch'],
email=clean_form['email'], phone=clean_form['phone'])
collect.save()
return HttpResponseRedirect('contactUs/contactUs.html') #the same page, change to thankyou page later
else:
return render(request, 'contactUs/contactUs.html',)
What could be the issue? I am clearly returning an HttpResponseRedirect
You are returning a HttpResponseRedirect if method is POST and the form is valid. If method isn't POST, you return the result of render(), which is a HttpResponse. So far so good.
But if method is POST and the form isn't valid, then you don't return anything explicitly (so None is returned).
This is assuming I got the indentation right -- it's a bit wrong in your question, e.g. the code under the def isn't indented.

Categories

Resources