I am new to django.. I cannot understand what is this error. Can someone help me solve this issue?
Traceback (most recent call last):
File "C:\Error logger\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Error logger\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Error logger\errorLogger\log\views.py", line 130, in add_solution
s.save()
File "C:\Error logger\errorLogger\log\models.py", line 41, in save
super().save(*args, **kwargs)
File "C:\Error logger\venv\lib\site-packages\django\db\models\base.py", line 682, in save
self._prepare_related_fields_for_save(operation_name='save')
File "C:\Error logger\venv\lib\site-packages\django\db\models\base.py", line 932, in _prepare_related_fields_for_save
raise ValueError(
Exception Type: ValueError at /add-solution/4/my-name-is-anirudh
Exception Value: save() prohibited to prevent data loss due to unsaved related object 'log'.
Also can someone explain what does the below do? I found that this is needed for slug urls.. But I don't understand what is super().save()
def save(self, *args, **kwargs):
self.slug = self.slug or slugify(self.solution)
super().save(*args, **kwargs)
Also what is the error that I am getting?
models.py
class Solutions(models.Model):
log = models.ForeignKey(
Log, on_delete=models.CASCADE, blank=True, null=True)
solution = models.TextField(null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(max_length=50, null=False, blank=True)
image = models.ImageField(
upload_to='images', blank=True)
def save(self, *args, **kwargs):
self.slug = self.slug or slugify(self.solution)
super().save(*args, **kwargs)
class Meta:
verbose_name = ("Solution")
verbose_name_plural = ("Solutions")
def __str__(self):
return f" {self.solution} "
views.py
def add_solution(request, id, solution):
log = Log()
if request.method == 'POST':
form = SolutionForm(request.POST, request.FILES)
if form.is_valid():
sol = form.cleaned_data['solution']
image = request.FILES.get('image')
s = Solutions()
s.solution = sol
s.image = image
s.log = log
s.save()
message = messages.add_message(request, 25,
'Solution added successfully')
return HttpResponseRedirect(f'/solution/{id}/{solution}')
else:
form = SolutionForm()
message = ''
try:
solution = Solutions.objects.filter(id=id).first()
print(solution)
except Solutions.DoesNotExist:
solution = ''
context = {
'form': form,
'message': message,
'solution': solution
}
return render(request, 'add_solution.html', context=context)
Thanks
You need to save the log first, so add
s.log.save()
Before
s.save()
Related
Can someone help me out please.
I want to redirect to a post detail page after deleting a comment of a given pk.
I got an AttributeError when ever I hit the comment delete button.
Error: function object has no attribute 'format'
If I change my success_url of the comment delete view to redirect to post list page with no argument, it works well but that's not what I want. I need the user to be redirected to post detail page after deleting a comment.
Here's my Post model
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published')
objects = models.Manager()
published = PublishedManager()
tags = TaggableManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[self.pk, self.slug])
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)'''
Comment model
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
comment = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return f'Comment by {self.author} on {self.post}'
def get_absolute_url(self):
return self.post.get_absolute_url() + f'#comment-{self.pk}'
CommentDeleteView
class CommentDeleteView(DeleteView):
model = Comment
template_name = 'comment_delete.html'
def success_url(self):
post = Post.objects.get(pk=self.object.post.pk)
return post.get_absolute_url()
And the full error
Internal Server Error: /blog/13/comment_delete/
Traceback (most recent call last):
File "C:\Users\SUNNY\blog_folder\ven\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\SUNNY\blog_folder\ven\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\SUNNY\blog_folder\ven\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\SUNNY\blog_folder\ven\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\SUNNY\blog_folder\ven\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\SUNNY\blog_folder\ven\lib\site-packages\django\views\generic\edit.py", line 218, in post
return self.delete(request, *args, **kwargs)
File "C:\Users\SUNNY\blog_folder\ven\lib\site-packages\django\views\generic\edit.py", line 212, in delete
success_url = self.get_success_url()
File "C:\Users\SUNNY\blog_folder\ven\lib\site-packages\django\views\generic\edit.py", line 222, in get_success_url
return self.success_url.format(**self.object.__dict__)
AttributeError: 'function' object has no attribute 'format'
[19/Jun/2020 11:50:28] "POST /blog/13/comment_delete/ HTTP/1.1" 500 88418
To configure the DeleteView success URL, you have to override the method get_success_url(). See that the method where you are implementing the success URL doesn't match that name, instead, its super class is trying to access the success_url property in the default get_success_url(), giving you that error.
I am making registration form in django. I have followed Set up subdomains for tenants in a Django web app? example but I get the following error.
Traceback (most recent call last):
File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
Its been hours and I cannot see where it comes from. I am hoping that a pair of fresh (and more experienced) eyes could see my mistake.
Here are the files I am working with:
models.py
class Client(TenantMixin):
name = models.CharField(max_length=100, default='')
email = models.EmailField(default='')
company = models.CharField(max_length=100, default='')
password = models.CharField(max_length=100, default='')
paid_until = models.DateField()
on_trial = models.BooleanField()
created_on = models.DateField(auto_now_add=True)
#
class Domain(DomainMixin):
pass
forms.py
class NewClientForm(forms.ModelForm):
name = forms.CharField(max_length=100)
email = forms.EmailField(max_length=100)
company = forms.CharField(max_length=100)
password = forms.CharField(widget = forms.PasswordInput)
def clean(self):
email = self.cleaned_data.get('email')
company = self.clean_date.get('company')
email_qs = Client.objects.filter(email=email)
if email_qs.exists():
raise forms.ValidationError(
"this email is already being used"
)
company_qs = Client.objects.filter(company=company)
if company_qs.exists():
raise forms.ValidationError(
'this company name is already identified in our system'
)
return email, company
view.py
class SignupView(View):
def get(self, request):
form = NewClientForm()
return render(request, "register.html", {'form': form})
def post(self, request,*args, **kwargs):
form = NewClientForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
tenant = Client(domain_url='company' + ".inventory4.com", schema_name='company', name= 'name')
tenant.save()
with schema_context(tenant.schema_name):
instance.save()
redirect = 'http://' + 'company' + '.inventory4.com:8000/login'
return HttpResponseRedirect(redirect)
return render(request, "register.html", {'form' : form})
Any help would be greatly appreciated!
I wish to set initial value in profile form.
Profile model has a OneToOne relation with User model.
I get the following error when I set initial field in init method,
'ForwardOneToOneDescriptor' object has no attribute 'email'
Traceback
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/core/handlers/base.py"
in _get_response
126. response = self.process_exception_by_middleware(e, request)
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/core/handlers/base.py"
in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/base.py"
in view
68. return self.dispatch(request, *args, **kwargs)
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/base.py"
in dispatch
88. return handler(request, *args, **kwargs)
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/edit.py"
in get
190. return super().get(request, *args, **kwargs)
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/edit.py"
in get
133. return self.render_to_response(self.get_context_data())
File "/home/drogon/Crowdsocial_project/users/views.py" in
get_context_data
90. context = super(ProfileSettingsView, self).get_context_data(**kwargs)
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/edit.py"
in get_context_data
66. kwargs['form'] = self.get_form()
File
"/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/edit.py"
in get_form
33. return form_class(**self.get_form_kwargs())
File "/home/drogon/Crowdsocial_project/users/forms.py" in init
144. self.initial['profile_email'] = Profile.user.email
Exception Type: AttributeError at /users/12/profile/settings Exception
Value: 'ForwardOneToOneDescriptor' object has no attribute 'email'
Profile Model
class Profile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
full_name = models.CharField(max_length=30, null=True, blank=True)
Profile Form
class ProfileSettingsForm(forms.ModelForm):
full_name = forms.CharField(required=False,
widget=forms.TextInput(attrs={'readonly': 'readonly'}))
profile_email = forms.CharField(required=False,
widget=forms.TextInput(attrs={'readonly': 'readonly'}))
def __init__(self, *args, **kwargs):
super(ProfileSettingsForm, self).__init__(*args, **kwargs)
self.initial['profile_email'] = Profile.user.email
self.initial['full_name'] = Profile.user.name
class Meta:
model = Profile
fields = ['image','full_name','biography','profile_email','linked_in','facebook',
'twitter','phone','education']
I've read a bunch of similar sounding questions of SO, but somehow none of them have helped me solve my particular case. I added a ManyToManyField to represent "Likes" to my Photo model:
class Photo(TimestampModerated):
owner = models.ForeignKey('auth.User', related_name='photos', on_delete=models.CASCADE)
uuid = models.UUIDField(default=uuid4, editable=False)
slug = models.SlugField(max_length=80, editable=False)
title = models.CharField(max_length=80, blank=False, null=False)
description = models.TextField(verbose_name='description of entity', blank=True, null=True)
photo = models.ImageField(upload_to=user_directory_path, height_field="height", width_field="width", blank=True)
height = models.IntegerField(blank=True)
width = models.IntegerField(blank=True)
tags = TaggableManager(blank=True)
hash = models.CharField(max_length=64, unique=True, null=True)
size = models.BigIntegerField('size of file in bytes', blank=True, null=True)
likes = models.ManyToManyField('auth.User', blank=True, null=True)
class Meta:
verbose_name_plural = "photos"
def __str__(self):
return self.title
def delete(self, using=None, keep_parents=False):
default_storage.delete("{}".format(self.photo))
super().delete()
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Photo, self).save(*args, **kwargs)
Here is the view (at least the part that should matter for creating):
class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (IsOwnerOrReadOnly, permissions.AllowAny,)
parser_classes = (MultiPartParser, FormParser)
def perform_create(self, serializer):
serializer.save(owner=self.request.user, likes=[])
And here is the serializer:
class PhotoSerializer(serializers.ModelSerializer, TaggitSerializer):
owner = serializers.CharField(source='owner.username', read_only=True)
tags = TagListSerializerField()
photo = Base64ImageField(
max_length=None, use_url=True,
)
class Meta:
model = Photo
fields = ('photo', 'height', 'width', 'owner', 'slug', 'uuid', 'title', 'id', 'created', 'updated',
'moderation_code', 'tags', 'hash', 'description', 'size', 'likes')
def create(self, validated_data):
photo = Photo.objects.create(owner=validated_data.pop('owner'),
**validated_data)
p = Photo.objects.get(uuid=photo.uuid)
[p.tags.add(tag) for tag in validated_data['tags']]
return photo
To be clear, the only thing that has been added is the likes field in the model. Also, I should note that I am able to actually POST new likes to photos that already existed in the DB before the migration. I'm just having issues creating new instances. Any ideas?
Here is the full error traceback:
Internal Server Error: /api/photos/
Traceback (most recent call last):
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 86, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/views.py", line 489, in dispatch
response = self.handle_exception(exc)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/views.py", line 449, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/views.py", line 486, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/mixins.py", line 21, in create
self.perform_create(serializer)
File "/Users/xxxxxx/_/photos/views.py", line 24, in perform_create
serializer.save(owner=self.request.user, likes=[])
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 215, in save
self.instance = self.create(validated_data)
File "/Users/xxxxxx/_/photos/serializers.py", line 88, in create
**validated_data)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/query.py", line 392, in create
obj = self.model(**kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/base.py", line 566, in __init__
_setattr(self, prop, kwargs[prop])
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 536, in __set__
manager = self.__get__(instance)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
return self.related_manager_cls(instance)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
(instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Photo: photo-260561.jpeg>" needs to have a value for field "id" before this many-to-many relationship can be used.
Well, I solved this with one seemingly very simple line of code:
def create(self, validated_data):
validated_data.pop('likes') ## adding this line solved the issue
photo = Photo.objects.create(owner=validated_data.pop('owner'),
**validated_data)
p = Photo.objects.get(uuid=photo.uuid)
[p.tags.add(tag) for tag in validated_data['tags']]
return photo
If anyone can explain why this works, I'd be interested to know. I should point out that for this use case a photo would never be initiated with likes.
In django rest framework If i use DictField() in serializer its given me AttributeError at /api/v1/analytics/reports-configuration/1/
‘str’ object has no attribute ‘items’ error.please take a look.
serializers.py
import json
from rest_framework import serializers
from models import ReportConfiguration
class ReportConfigurationSerializer(serializers.ModelSerializer):
report_type = serializers.ChoiceField(choices=['query', 'activity', 'summary'])
read_only = serializers.BooleanField(required=True)
query_data = serializers.DictField(required=True)
class Meta:
model = ReportConfiguration
fields = ('id', 'title', 'query_data', 'created_by', 'last_activity_by', 'deleted',
'deleted_by', 'added_at', 'last_activity_at', 'report_type', 'read_only')
def validate(self, data):
if data['report_type'] is not 'summary' and data['read_only'] is True:
raise serializers.ValidationError("If read only true then report type should be summary")
if data['report_type'] is 'summary' and data['read_only'] is not True:
raise serializers.ValidationError("If read only not true then report type should not be summary")
return data
def create(self, validated_data):
validated_data['created_by'] = self.context['request'].user
validated_data['last_activity_by'] = self.context['request'].user
return ReportConfiguration.objects.create(**validated_data)
views.py
class ReportConfigurationViewSet(viewsets.ModelViewSet):
serializer_class = ReportConfigurationSerializer
queryset = ReportConfiguration.objects.all()
permission_classes = (permissions.IsAuthenticated,)
filter_backends = (DjangoFilterBackend,)
filter_class = ReportFilter
def list(self, request):
response = super(ReportConfigurationViewSet, self).list(request)
for data in response.data['results']:
data['query_data'] = json.loads(data['query_data'])
return response
def retrieve(self, request, pk=None):
response = super(ReportConfigurationViewSet, self).retrieve(request, pk=pk)
response.data['query_data'] = json.loads(response.data['query_data'])
return response
models.py
class ReportConfiguration(models.Model):
class ReportTypeChoice(Choice):
QueryReport = 'query'
ActivityReport = 'activity'
SummaryList = 'summary'
title = models.CharField(max_length=300, unique=True, blank=False, null=False)
query_data = JSONField(default={})
created_by = models.ForeignKey(User, null=True, blank=True, related_name='report_created_by')
last_activity_by = models.ForeignKey(User, null=True, blank=True,related_name='last_active_in_report')
deleted = models.BooleanField(default=False)
deleted_by = models.ForeignKey(User, null=True, blank=True, related_name='report_deleted_by')
added_at = models.DateTimeField(auto_now_add=True)
last_activity_at = models.DateTimeField(default=timezone.now)
report_type = models.CharField(max_length=15, choices=ReportTypeChoice)
read_only = models.BooleanField(default=False)
Error:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
ERROR Internal Server Error: /api/v1/analytics/reports-configuration/1/
Traceback (most recent call last):
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/viewsets.py", line 83, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/ranvijay.s/wk/project/django/dhanalytics/views.py", line 47, in retrieve
response = super(ReportConfigurationViewSet, self).retrieve(request, pk=pk)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/mixins.py", line 58, in retrieve
return Response(serializer.data)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 527, in data
ret = super(Serializer, self).data
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 496, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/fields.py", line 1601, in to_representation
for key, val in value.items()
AttributeError: 'str' object has no attribute 'items'