userpost() got an unexpected keyword argument 'instance' - python

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'),
# …
]

Related

how can i login with local url in Django administration and add user? [duplicate]

This question already has answers here:
Django 2.1.3 Error: __init__() takes 1 positional argument but 2 were given
(3 answers)
Closed 1 year ago.
i tried for make a django userprofile but i can't Enter to login page
there is my error when i enter to my local url
TypeError at /account/login/
__init__() takes 1 positional argument but 2 were given
Request Method: GET
Request URL: http://127.0.0.1:8000/account/login/
Django Version: 3.2.9
Exception Type: TypeError
Exception Value:
__init__() takes 1 positional argument but 2 were given
Exception Location: /home/pantea/.local/lib/python3.6/site-packages/django/core/handlers/base.py, line 181, in _get_response
Python Executable: /usr/bin/python3
Python Version: 3.6.9
Python Path:
['/home/pantea/tutorial',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/pantea/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages']
here is my url file
from django.conf.urls import url
from django.contrib.auth.views import LoginView,LogoutView
from accounts import views
# from accounts import views
urlpatterns = [
url(r'^$',views.home),
url(r'^login/$', LoginView, {'template_name': 'accounts/login.html'}),
url(r'^logout/$', LogoutView, {'template_name': 'accounts/logout.html'}),
url(r'^register/$',views.register, name ='register'),
url(r'^profile/$',views.view_profile, name ='view_profile'),
url(r'^profile/edit/$',views.edit_profile , name ='edit profile'),
]
and also my views file
from django.contrib.auth.views import PasswordChangeDoneView
from django.shortcuts import render,redirect
from accounts.forms import NewUserForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm, UserChangeForm
def home(request):
numbers = [1,2,3,4,5]
name = 'max'
args = {'myName': name,'numbers':numbers}
return render(request, 'accounts/home.html',args)
def register(request):
if request.method == 'POST':
form = NewUserForm(request.POST)
if form.is_valid():
form.save()
return redirect('/account')
else:
form = NewUserForm()
args = {'form':form}
return render(request,'accounts/reg_form.html',args)
def view_profile(request):
args ={'user':request.user}
return render(request,'accounts/profile.html',args)
def edit_profile(request):
if request.method == 'POST':
form = PasswordChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = PasswordChangeDoneView(instance=request.user)
args={'form':form}
return render(request,'accounts/edit_profile.html')
def edit_profile(request):
if request.method == 'POST':
form = PasswordChangeDoneView(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = PasswordChangeDoneView(instance=request.user)
args={'form':form}
return render(request,'accounts/change_password.html',args)
they are both in same folder that named account it's work when i looking for http://127.0.0.1:8000/account/
idon't really know what should i do for this :)
The LoginView, LogoutView, etc. are class-based views, so you should use .as_view(…) [Django-doc]:
urlpatterns = [
url(r'^$',views.home),
url(r'^login/$', LoginView.as_view(template_name='accounts/login.html')),
url(r'^logout/$', LogoutView.as_view(template_name='accounts/logout.html')),
url(r'^register/$',views.register, name ='register'),
url(r'^profile/$',views.view_profile, name ='view_profile'),
url(r'^profile/edit/$',views.edit_profile , name ='edit profile'),
]
Note: As of django-3.1, url(…) [Django-doc] is
deprecated in favor of re_path(…) [Django-doc].
Furthermore a new syntax for paths has been introduced with path converters: you
use path(…) [Django-doc] for that.

I want to add registeration to my web by django. I did all things right:

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Tutorial
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.models import User
def register (request):
form = UserCreationForm(request.POST)
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages():
print(form.error_messages[msg])
return render(request,
'main/register.html',
context={'form':form})
but still I get this error " 'dict' object is not callable
Request Method: POST Request
URL: http://127.0.0.1:8000/register/ Django Version: 3.0.7
Exception Type: TypeError
Exception Value: 'dict' object is not callable "
for msg in form.error_messages():
print(form.error_messages[msg])
First, no where in the Django documentation is using form.error_messages for the error messages, and if form.error_messages is a dict, then there is a python problem -> dict is not callable, get the list of keys by calling .keys() on your dict.
According to Newest Django's doc to get errors from your forms is using form.errors.
for field, msg in form.errors.items():
print(f'Field {key}: {msg}')

Why am I getting this error "local variable 'text' referenced before assignment"

I am trying to create a share function using python and Django and when I run "share" it gives me back an error. Here's my code:
views.py
from django.shortcuts import render
from basicapp.forms import UserForm, UserProfileInfoForm, PostForm
from django.contrib.auth.models import User
from basicapp.models import UserProfileInfo
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import login,logout,authenticate
#login_required
def user_post(request):
form = PostForm(request.POST)
if form.is_valid():
text = form.cleaned_data['post']
form = PostForm()
return HttpResponseRedirect(reverse('index'))
else:
HttpResponse("Not Valid try dat boi agian")
render(request, 'basicapp/userpost.html',
{'form':form,
'text':text})
forms.py
class PostForm(forms.Form):
post = forms.CharField(max_length=256)
This is the error:
You're not returning the HttpResponse in your else block execution continues to next line of code which wants a text variable to be defined, but since the is_valid block never ran, there is no text in scope.
You will also never get to the final line once you have a return in both the if and else branches of the form.is_valid() test.
def user_post(request):
form = PostForm(request.POST)
if form.is_valid():
text = form.cleaned_data['post']
form = PostForm()
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Not Valid try dat boi agian") # return here
return render(request, 'basicapp/userpost.html', # should return here too but this line will never run
{'form':form,
'text':text})

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']);

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

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))

Categories

Resources