So I have my code below, whenever I run it in admin and try to view that object returns and error:
Exception Type: MultipleObjectsReturned
Exception Value:
get() returned more than one c2 -- it returned 2!
How do I resolve this error?
models.py:
from django.db import models
import datetime
import pytz
from django.utils import timezone
class c1(models.Model):
name = models.CharField(max_length=30, default="Other")
def __str__(self):
return self.name
class c2(models.Model):
c1 = models.ForeignKey(c1, on_delete=models.CASCADE)
name = models.CharField(max_length=30, default="Other")
def __str__(self):
return self.name
class c3(models.Model):
c2 = models.ForeignKey(c2, on_delete=models.CASCADE)
name = models.CharField(max_length=30, default="Other")
def __str__(self):
return self.name
class Task_manager(models.Manager):
def create_Task(self, title):
Task1 = self.create(title=title)
return Task1
class Task(models.Model):
STATUS = (
('ONGOING', 'ONGOING'),
('COMPLETED','COMPLETED'),
)
search=models.CharField(max_length=300, choices=search_title, default="OTHER")
c1=models.ForeignKey(c1, on_delete=models.SET_NULL, null=True)
c2=models.ForeignKey(c2, on_delete=models.SET_NULL, null=True)
c3=models.ForeignKey(c3, on_delete=models.SET_NULL, null=True)
title=models.CharField(max_length=30,default="Other")
created=models.DateTimeField(default=timezone.now())
objects=Task_manager()
class Meta:
ordering = [ '-created']
def __str__(self):
return self.title
Here is my ModelAmdin class in admin.py
admin.py snippet:
class TaskAdmin(admin.ModelAdmin):
film_status.allow_tags = True'''
form=TaskForm
list_filter=('c1')
readonly_fields = ['score','score_fixed','deadline_fixed','created']
def change_view(self,request,object_id,extra_content=None):
return super(TaskAdmin,self).change_view(request,object_id)
admin.site.register(Task,TaskAdmin)
admin.site.register(c1)
admin.site.register(c2)
admin.site.register(c3)
You can also have a look at TaskForm class.
forms.py:
class TaskForm(forms.ModelForm):
class Meta:
model=Task
fields='__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['c1'].queryset = c1.objects.all()
self.fields['c2'].queryset = c2.objects.get()
self.fields['c3'].queryset = c3.objects.none()
Here is the full error for the code:
Traceback (most recent call last):
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "C:\My_Django_stuff\tada\todo\tasks\admin.py", line 64, in change_view
return super(TaskAdmin,self).change_view(request,object_id)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\options.py", line 1641, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\contrib\admin\options.py", line 1582, in _changeform_view
form = ModelForm(instance=obj)
File "C:\My_Django_stuff\tada\todo\tasks\forms.py", line 14, in __init__
self.fields['c2'].queryset = c2.objects.get()
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 419, in get
raise self.model.MultipleObjectsReturned(
Exception Type: MultipleObjectsReturned at /admin/tasks/task/9/change/
Exception Value: get() returned more than one c2 -- it returned 2!
QuerySet.get() will raise an exception if the queryset does not contain exactly one object. Either an DoesNotExist or an MultipleObjectsReturned. This is by design.
You can handle this by using a try, except, of by calling another QuerySet method (.first() to get first object, for instance).
Related
I am running Django==3.2.12 and trying to generate a rendered tewmplate string. The following is the nuts and bolts of it....
I am recieving the error "'Context' object has no attribute 'render_context'" and can not make any sence of it.
It used to work fine, I am using django-mjml for this.
Code...
import uuid
from django.db import models
from django.template import Template, Context
from django.urls import reverse
class EmailTemplate(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
uuid = models.UUIDField(default = uuid.uuid4)
mjml_template = models.TextField(blank=True)
html_template = models.TextField(blank=True)
class Meta:
ordering = ['name', ]
verbose_name = 'Template'
verbose_name_plural = 'Templates'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('pages:emailing', kwargs={'slug': self.slug, 'uuid': self.uuid})
def save(self, *args, **kwargs):
mjml_open = '{% load mjml %}{% mjml %}'
mjml_close = '{% endmjml %}'
verbatum_open = '{% verbatim %}{{'
verbatum_close = '}}{% endverbatim %}'
verbatum = self.mjml_template.replace('{{', verbatum_open)
verbatum = verbatum.replace('}}', verbatum_close)
verbatum = mjml_open + verbatum + mjml_close
template = Template(verbatum)
context = Context({})
passed = False
try:
self.html_template = template.render(context)
passed = True
except Exception as err:
self.html_template = str(err)
if passed:
image_categories = ImageCategory.objects.filter(templates=self)
for image_category in image_categories:
for image in image_category.get_images():
tag = '[~ ' + image.slug + ' ~]'
swap = self.html_template
swap = swap.replace(tag, image.image.url)
self.html_template = swap
resource_categories = ResourceCategory.objects.filter(templates=self)
for resource_category in resource_categories:
for resource in resource_category.get_resources():
tag = '[~ ' + resource.slug + ' ~]'
swap = self.html_template
swap = swap.replace(tag, resource.resource)
self.html_template = swap
super(EmailTemplate, self).save(*args, **kwargs)
Traceback....
Internal Server Error: /admin/emailing/emailtemplate/1/change/
Traceback (most recent call last):
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1660, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1540, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1586, in _changeform_view
self.save_model(request, new_object, form, not add)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1099, in save_model
obj.save()
File "/Applications/MAMP/htdocs/mjml/emailing/models.py", line 42, in save
self.html_template = template.render(context)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/template/base.py", line 166, in render
with context.render_context.push_state(self):
AttributeError: 'Context' object has no attribute 'render_context'
Am starter in Django and tried CreateView class and got the following error: Am unable to find the issue. ListView and DetailView works fine.
Trace Log :
System check identified no issues (0 silenced).
July 20, 2022 - 22:38:33
Django version 3.2.12, using settings 'configs.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /task/create/
Traceback (most recent call last):
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 32, in get_form
form_class = self.get_form_class()
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 101, in get_form_class
return model_forms.modelform_factory(model, fields=self.fields)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 563, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 261, in __new__
fields = fields_for_model(
File "C:\Users\mayank.shah\.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 150, in fields_for_model
opts = model._meta
AttributeError: type object 'Task' has no attribute '_meta
model :
class Task(models.Model):
user =models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=True,related_name='usertasks')
title = models.CharField(max_length=200,blank=False, null=False)
description = models.TextField(null=True, blank=True)
complete = models.BooleanField(default=False)
create = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('task-app:task', kwargs={'pk': self.pk})
def __unicode__(self):
return self.title
class Meta:
ordering = ['-create']
view :
class TaskCreate(CreateView):
model = Task
# fields = "__all__"
fields = ('title', 'description')
# fields = ['title']#,'description','completed']
success_url= reverse_lazy('task-app:tasks')
Dear All the issue is Task is Key-word and so causing issue. I renamed the model as alltask and it fixed the issue. Though this is not faced by all, but can be useful if no solution found.
This is my serializer and Viewset, i want to create an instance of Like if someone likes a product (Post request 'products/product:id/like'). But i get an error that 'request' is required.
class LikeSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
product = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = Like
fields = ('user', 'product',)
class LikeProductApi(generics.CreateAPIView):
queryset = Like.objects.all()
serializer_class = LikeSerializer
def create(self, request, *args, **kwargs):
product_id = self.kwargs['pk']
product = ProductInStore.objects.get(id=int(product_id))
if Like.objects.filter(user=self.request.user, product=product).exists():
raise ValidationError(_("This user already likes this product"))
else:
return super().create(user=self.request.user, product_id=product_id, **kwargs)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "/Users/jakubstrawa/programming/PythonKuba/api/ecommerce/views.py", line 124, in create
return super().create(user=self.request.user, product_id=product_id, **kwargs)
TypeError: create() missing 1 required positional argument: 'request'
Do you have any idea why?
You are making a super() call with the wrong parameters, it should be:
def create(self, request, *args, **kwargs):
product_id = self.kwargs['pk']
if Like.objects.filter(user=self.request.user, product_id=product_id).exists():
raise ValidationError(_("This user already likes this product"))
else:
return super().create(request, *args, **kwargs)
The issue is how you're calling create()
Try the below:
In the PythonKuba/api/ecommerce/views.py file
return super().create(request=self.request, product_id=product_id, **kwargs)
At the moment you are sending in the user, not the request
I have 2 serializers that add and subtract (they are the same, with the difference being add +=1 and subtract -=1) points to an answer. I want to limit them so that a user can only use add point to an answer once. Do you have any idea how to get to it in Django Rest Framework?
class Answer(models.Model):
number_of_points = models.IntegerField(default=0)
class SubtractPointsSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('number_of_points',)
def update(self, instance, validated_data):
instance.number_of_points -= 1
instance.save()
return instance
Internal Server Error: /api/v1/answers/2/addpoints
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 226, in put
return self.update(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 68, in update
self.perform_update(serializer)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 78, in perform_update
serializer.save()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 200, in save
self.instance = self.update(self.instance, validated_data)
File "/Users/jakubstrawa/programming/gitlabdeor/api/questions/serializers.py", line 74, in update
if not instance.addition_done and self.request.user not in instance.voters.all():
AttributeError: 'AddPointsSerializer' object has no attribute 'request'
You can always add a Boolean field that stores if addition/subtraction was done. You can store every User that had voted already so noone will vote twice (also will not vote for both +1/-1).
class Answer(models.Model):
number_of_points = models.IntegerField(default=0)
addition_done = models.BooleanField(default=False)
subtraction_done = models.BooleanField(default=False)
voters = models.ManyToManyField('User', default=None, blank=True)
===========================================================
class SubtractPointsSerializer(serializers.ModelSerializer):
...
def update(self, instance, validated_data):
if not instance.subtraction_done:
instance.number_of_points -= 1
instance.subtraction_done = True
instance.save()
return instance
You can also divide ManyToMany field into two separated (one for addition, another for subtraction).
I have been troubleshooting this problem for 3 days now. I think I'm missing something fundamental about testing Create Views or using client.post().
The test is failing because the date key is not present in the cleaned_data dictionary of the form, however, the code works correctly when executed from the browser.
Can you please tell me why is the date key present in the cleaned_data dictionary when running in the browser but absent when executed by client.post() in the test?
Below are snippets of relevant code.
Models.py
class Livestock(CommonInfo):
"""Model definition for Livestock. CommonInfo is an abstract model that contains
created_by, modified_by, date_created, date_modified and comment fields"""
product = models.ForeignKey(
Product, on_delete=models.CASCADE, related_name='livestock')
date = models.DateField(
auto_now=False, auto_now_add=False)
production = models.PositiveIntegerField(
'Livestock produced (Kg or litre or #)')
number_of_animal = models.PositiveIntegerField(
'Number of Animals (Quantity)', blank=True, null=True)
cost_of_production = models.PositiveIntegerField(
'Cost of Production (GYD)', blank=True, null=True)
views.py
class LivestockCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
model = Livestock
form_class = LivestockForm
success_url = reverse_lazy('real:livestock-list')
template_name = "real/livestock/livestock_form.html"
permission_required = ('real.add_livestock')
def get_initial(self):
initial = super(LivestockCreateView, self).get_initial()
initial['date'] = timezone.now()
return initial
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
Forms.py
class LivestockForm(forms.ModelForm):
"""Form definition for Livestock."""
class Meta:
"""Meta definition for Livestockform."""
model = Livestock
fields = ['product', 'date', 'production',
'number_of_animal', 'cost_of_production', 'comment',
'modified_by', 'created_by']
widgets = {
'date': forms.DateInput(attrs={'type': 'date'}),
'modified_by': forms.HiddenInput(),
'created_by': forms.HiddenInput(),
}
def clean(self):
self.cleaned_data = super(LivestockForm, self).clean()
self._validate_unique = True
self.cleaned_data['date'] = self.cleaned_data['date'].replace(day=1)
return self.cleaned_data
test.py
class LivestockTests(TestCase):
#classmethod
def setUpTestData(cls):
cls.User = get_user_model()
cls.user = cls.User.objects.create_user(
username='test_user',
password='testpass123',
first_name='test',
last_name='user'
)
cls.product = Product.objects.create(
name='Milk'
)
def test_livestock_create_view_user_is_login_and_have_permission(self):
self.user.user_permissions.add(
Permission.objects.get(codename='add_livestock'))
login = self.client.login(username='test_user', password='testpass123')
response = self.client.post((reverse('real:livestock-create'),
{'product': self.product.id,
'date': timezone.now(),
'production': 5200
})
view = resolve('/sector/real/livestock/create')
self.assertTrue(login)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'real/livestock/livestock_form.html')
self.assertContains(response, 'Livestock')
self.assertNotContains(response, 'Sugar')
self.assertEqual(
view.func.__name__,
views.LivestockCreateView.as_view().__name__
)
traceback
D:\MOF\Projects\guyanaeconomicsectoranalysis>docker-compose exec web python manage.py test real
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.E............
======================================================================
ERROR: test_livestock_create_view_user_is_login_and_have_permission
(real.tests.tests_livestock.LivestockTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Projects/real/tests/tests_livestock.py", line 875, in
test_livestock_create_view_user_is_login_and_have_permission
'production': 5200
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 543, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 357, in post
secure=secure, **extra)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 503, in request
raise exc_value
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/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 85, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/edit.py", line 141, in post
if form.is_valid():
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 180, in errors
self.full_clean()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 382, in full_clean
self._clean_form()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 409, in _clean_form
cleaned_data = self.clean()
File "/Projects/real/forms.py", line 140, in clean
self.cleaned_data['date'] = self.cleaned_data['date'].replace(day=1)
KeyError: 'date'
----------------------------------------------------------------------
Ran 14 tests in 0.791s
FAILED (errors=1)
Destroying test database for alias 'default'...
Proof Code working in browser