my issue is exactly as the problem states...I am unable to get form validation errors to work. I will post what I am currently trying below. Please let me know how I can amend my code in order to get this working. Currently, I can even successfully submit the form with any name. So clearly what I have set in forms.py is not even working...
forms.py
class PackingListForm(forms.ModelForm):
class Meta:
model = PackingList
fields = ['Exporter', 'Consignee', 'Reference_Number', ... ]
def clean_test_value(self):
data = self.cleaned_data.get('Exporter')
if not Exporter == 'Jeff':
raise forms.ValidationError('ahhhh Error!')
return data
template (packlist.html)
<td rowspan="3"colspan="2">Exporter: {{ form.Exporter }}
{% for error in form.Exporter.errors %}
<P class='help is-danger'>{{ error }}</p>
{% endfor %}
</td>
views.py
def PackingListView(request):
if request.method == "POST":
form = PackingListForm(request.POST)
if form.is_valid():
.....do stuff here......
else:
return render(request, 'packlist.html', {'form': form})
else:
form = PackingListForm()
return render(request, 'packlist.html', {'form': form})
traceback
Request Method: POST
Request URL: http://127.0.0.1:8000/create/packing_list
Django Version: 1.11
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Poseidon',
'crispy_forms',
'bootstrap_modal_forms']
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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/Users/andrews/Desktop/WBU2/Poseidon/views.py" in PackingListView
188. if form.is_valid():
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in is_valid
183. return self.is_bound and not self.errors
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in errors
175. self.full_clean()
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in full_clean
384. self._clean_fields()
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in _clean_fields
405. value = getattr(self, 'clean_%s' % name)()
File "/Users/andrews/Desktop/WBU2/Poseidon/forms.py" in clean_Exporter
52. if not Exporter == 'Greg':
Exception Type: NameError at /create/packing_list
Exception Value: global name 'Exporter' is not defined
Since the name of the field is Exporter, the cleaning function should be clean_Exporter:
class PackingListForm(forms.ModelForm):
class Meta:
model = PackingList
fields = ['Exporter', 'Consignee', 'Reference_Number']
def clean_Exporter(self):
data = self.cleaned_data.get('Exporter')
if data != 'Jeff':
raise forms.ValidationError('ahhhh Error!')
return data
Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be: exporter instead of Exporter.
Related
Hi All I faced this issue while getting API response. I am using django==2.1.7. Below I am adding my code snippet
models.py
The model contains topic names(en,bn), taglist(string), and Bucket_id or topic_id
class Topics(models.Model):
id = models.AutoField(primary_key=True)
name_en = models.CharField(max_length=70, blank=False, default='')
name_bn = models.CharField(max_length=70, blank=False, default='')
tags = models.TextField(blank=False, default='')
bucket_id = models.IntegerField()
def set_tags(self, x):
self.tags = json.dumps(x)
def get_tags(self):
return json.loads(self.tags)
class Meta:
managed = True
db_table = 'follow_topics'
serialize.py
TopicSeializer used for JSON serialize the model
from rest_framework import serializers
from .models import Topics
class TopicSerializer(serializers.ModelSerializer):
class Meta:
model = Topics
fields = ['name_en','name_bn','tags', 'bucket_id']
views.py
get_topic function gives me the list of the topic from the model
#api_view(('GET',))
def get_topics(requests):
topic_id = requests.GET.get('topic_id', None)
post_data = Topics.objects.filter(bucket_id=topic_id)
serialize_data = TopicSerializer(post_data, many=True)
return Response({"status": "success", "data": serialize_data})
I got serializable error. This error looks frustrating for me. Please help me share some useful resource or way that I can fix this error
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/feed/v1/get_topics?topic_id=2
Django Version: 2.1.7
Python Version: 3.6.8
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'rest_framework',
'feedv1']
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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
'django.middleware.common.CommonMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
156. response = self.process_exception_by_middleware(e, request)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
154. response = response.render()
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/template/response.py" in render
106. self.content = self.rendered_content
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
733. context = self.get_context(data, accepted_media_type, renderer_context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_context
688. 'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_content
424. content = renderer.render(data, accepted_media_type, renderer_context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
107. allow_nan=not self.strict, separators=separators
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/json.py" in dumps
28. return json.dumps(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py" in dumps
238. **kw).encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in encode
201. chunks = list(chunks)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
430. yield from _iterencode_dict(o, _current_indent_level)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode_dict
404. yield from chunks
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
437. o = _default(o)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/encoders.py" in default
68. return super(JSONEncoder, self).default(obj)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in default
180. o.__class__.__name__)
Exception Type: TypeError at /feed/v1/get_topics
Exception Value: Object of type 'TopicSerializer' is not JSON serializable
You need to access the .data property of the serializer
return Response({"status": "success", "data": serialize_data.data})
I'm trying to send a verification email after a user registers an account using django-templated-mail.
This is the error I get after the user is created:
AttributeError 'dict' object has no attribute 'get_host'
So Django is trying to call get_host() and is unable to? So it's an error because it can't retrieve my host name?
Can someone point out what am I missing here?
class UserListView(generics.ListCreateAPIView):
serializer_class = UserSerializer
def perform_create(self, serializer):
user = serializer.save()
context = {'user': user}
to = user.email
email.ActivationEmail(context).send(to)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'password', 'email')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password')
user = super(UserSerializer, self).create(validated_data)
user.set_password(password)
user.save()
return user
class ActivationEmail(BaseEmailMessage):
template_name = 'email/activation.html'
def get_context_data(self):
context = super(ActivationEmail, self).get_context_data()
user = context.get('user')
context['uid'] = utils.encode_uid(user.pk)
context['token'] = default_token_generator.make_token(user)
context['url'] = 'verify/{uid}/{token}'.format(**context)
return context
Traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/users/
Django Version: 2.0
Python Version: 3.6.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'templated_mail',
'accounts',]
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'simple_history.middleware.HistoryRequestMiddleware']
Traceback:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
483. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
443. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
480. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/generics.py" in post
244. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/code/accounts/views.py" in perform_create
54. email.ActivationEmail(context).send(to)
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in send
69. self.render()
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in render
61. context = make_context(self.get_context_data(), request=self.request)
File "/code/accounts/email.py" in get_context_data
12. context = super(ActivationEmail, self).get_context_data()
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in get_context_data
33. site = get_current_site(self.request)
File "/usr/local/lib/python3.6/site-packages/django/contrib/sites/shortcuts.py" in get_current_site
16. return RequestSite(request)
File "/usr/local/lib/python3.6/site-packages/django/contrib/sites/requests.py" in __init__
10. self.domain = self.name = request.get_host()
Exception Type: AttributeError at /users/
Exception Value: 'dict' object has no attribute 'get_host'
Thank you much appreciate any help you may be able to render.
ActivationEmail takes the request as the first positional argument to its initializer. You're passing the context as the first positional argument, which causes ActivationEmail to fall over.
Make sure you pass the request instance as well as the context to ActivationEmail when you create it.
email.ActivationEmail(self.request, context).send(to)
You instantiated ActivationEmail incorrectly. The request parameter should be an HttpRequest object instead of a dict.
I had a problem with my Django program. I'm a beginner in Django, I was looking for an answer with different posts with the same error than mine but no success ...
Here's my traceback :
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/pod
Django Version: 1.11.2
Python Version: 2.7.13
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'labinit',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\django_learneo3\Learneo\labinit\views.py" in groupe_pod
121. if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
183. return self.is_bound and not self.errors
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
175. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
384. self._clean_fields()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
396. value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Python27\lib\site-packages\django\forms\widgets.py" in
value_from_datadict
639. getter = data.get
Exception Type: AttributeError at /pod
Exception Value: 'unicode' object has no attribute 'get'
This issue appears since I have changed my init fonction, for the form that I use in my view :
Forms:
class Groupe_Form(forms.ModelForm) :
def __init__(self, nom_groupe, *args, **kwargs):
super(Groupe_Form,self).__init__(*args, **kwargs)
self.fields['pod'].widget = forms.Select()
pod1 = Groupe.objects.filter(nom_groupe = nom_groupe).values_list('pod', flat = True)
pods = list(pod1)
self.fields['pod'].queryset = Pod.objects.filter(id__in=pods)
class Meta:
model = Groupe
fields = ['pod']
Views :
def groupe_pod(request):
global new_groupe
grp = new_groupe
form = forms.Groupe_Form(request.POST, grp)
if request.method == 'POST':
if form.is_valid():
print "form was valid"
data_groupe_pod = request.POST.get('grp_pod')
print "data_groupe :", data_groupe_pod
global new_cours
print new_cours
if new_cours == "ICND1":
return redirect('http://127.0.0.1:8000/icnd_1')
elif new_cours == "ICND2":
return redirect('http://127.0.0.1:8000/icnd_2')
else :
form = forms.Groupe_Form(new_groupe)
return render(request, 'pod.html', locals())
I've tried many things, I really don't know where is the problem in my Django code.
Your form's __init__ method is:
def __init__(self, nom_groupe, *args, **kwargs):
Therefore you should instantiate it with:
form = forms.Groupe_Form(grp, request.POST)
You currently have the arguments the other way round.
Your __init__ signature has as its first parameter nom_groupe. In form = forms.Groupe_Form(request.POST, grp) you pass request.POST as the first parameter. You have to switch the parameters:
form = forms.Groupe_Form(grp, request.POST)
I'm a beginner to the Django Rest Frame work. I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me
models.py
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class Account(models.Model):
my_user=models.OneToOneField(User,on_delete=models.CASCADE)
statut=models.CharField(max_length=80)
date=models.DateField(auto_now=True,auto_now_add=False)
def __unicode__(self):
return self.my_user.first_name
Now i want to update Account serilizer .
Serializers .py
class AccountUpdateSerializer(serializers.ModelSerializer):
username=serializers.CharField(source ='my_user.username')
class Meta:
model= Account
fields=['id','username','statut','date']
def update(self, instance, validated_data):
print(instance)
instance.statut = validated_data.get('statut', instance.statut)
instance.my_user.username=validated_data['username']
return instance
Trace Back:
Environment:
Request Method: PUT
Request URL: http://127.0.0.1:9000/api/account/edit/1/
Django Version: 1.9
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'project',
'sponsors',
'contacts',
'medias',
'conferencier',
'competition',
'poste',
'account']
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 "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
474. response = self.handle_exception(exc)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
434. self.raise_uncaught_exception(exc)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
471. response = handler(request, *args, **kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/generics.py" in put
256. return self.update(request, *args, **kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/mixins.py" in update
70. self.perform_update(serializer)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/mixins.py" in perform_update
74. serializer.save()
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/serializers.py" in save
187. self.instance = self.update(self.instance, validated_data)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/serializers.py" in update
907. setattr(instance, attr, value)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in __set__
207. self.field.remote_field.model._meta.object_name,
Exception Type: ValueError at /api/account/edit/1/
Exception Value: Cannot assign "{u'username': u'kais'}": "Account.my_user" must be a "User" instance.
Your update method is not called, because it is a method of the meta class of the serializer (AccountUpdateSerializer.Meta), not the serializer class AccountUpdateSerializer itself.
Here is how it should look:
class AccountUpdateSerializer(serializers.ModelSerializer):
username=serializers.CharField(source ='my_user.username')
class Meta:
model= Account
fields=['id','username','statut','date']
def update(self, instance, validated_data):
print(instance)
instance.statut = validated_data.get('statut', instance.statut)
instance.my_user.username = validated_data['username']
return instance
(Or did you just post your code incorrectly?)
In the project im working on the admin site is working fine and i want to test the frontend. But im Getting:
TypeError at /auth/login
dict expected at most 1 arguments, got 2
Here the full traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/auth/login?next=/
Django Version: 1.10
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django_nose',
'widget_tweaks',
'rest_framework',
'rest_framework_gis',
'backbone_app',
'accounts',
'map')
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "D:\SHK\ElektroClean\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "D:\SHK\ElektroClean\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response
249. response = self._get_response(request)
File "D:\SHK\ElektroClean\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "D:\SHK\ElektroClean\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\SHK\ElektroClean\accounts\views.py" in login_view
47. return render(request, 'login.html', context)
File "D:\SHK\ElektroClean\lib\site-packages\django\shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "D:\SHK\ElektroClean\lib\site-packages\django\template\loader.py" in render_to_string
68. return template.render(context, request)
File "D:\SHK\ElektroClean\lib\site-packages\django\template\backends\django.py" in render
64. context = make_context(context, request, autoescape=self.backend.engine.autoescape)
File "D:\SHK\ElektroClean\lib\site-packages\django\template\context.py" in make_context
267. context.push(original_context)
File "D:\SHK\ElektroClean\lib\site-packages\django\template\context.py" in push
59. return ContextDict(self, *dicts, **kwargs)
File "D:\SHK\ElektroClean\lib\site-packages\django\template\context.py" in __init__
18. super(ContextDict, self).__init__(*args, **kwargs)
Exception Type: TypeError at /auth/login
Exception Value: dict expected at most 1 arguments, got 2
This is the urls.py :
urlpatterns = [
url(r'^map/', include('map.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^auth/', include('accounts.urls')),
url(r'^', include('backbone_app.urls')),
and the other
app_name = 'accounts'
urlpatterns = [
url(r'^auth/', views.auth_view, name='auth_view'),
url(r'login', views.login_view, name='login'),
url(r'logout', views.logout_view, name='logout'),
url(r'invalid', views.invalid_view, name='invalid'),
]
This is the views.py :
def login_view(request):
context = RequestContext(request)
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
context['user'] = user
if user.is_active:
login(request, user)
return HttpResponseRedirect('/') #Redirect to a success page
else:
return HttpResponseRedirect('auth/invalid')
else:
return HttpResponse('Passwort oder Username falsch')
return render(request, 'login.html', context)
where's my Problem ? Please help.
Thanks
The render function is expecting a dictionary not a RequestContext object. Change your return line in your login_view to something like this:
return render(request, 'login.html', {'context': context})