Django, unicode object has no attribute pk - django

I have a problem with validation of form containing ModelMultipleChoiceField.
In face on submit, I have this error :
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/Proapp/main_app/views.py", line 275, in felicitationInscription
if completerProfilForm.is_valid() :
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 161, in is_valid
return self.is_bound and not self.errors
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 153, in errors
self.full_clean()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 362, in full_clean
self._clean_fields()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 380, in _clean_fields
value = field.clean(value)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1254, in clean
qs = self._check_values(value)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1287, in _check_values
pks = set(force_text(getattr(o, key)) for o in qs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1287, in <genexpr>
pks = set(force_text(getattr(o, key)) for o in qs)
AttributeError: 'unicode' object has no attribute 'pk'
So my form is like this :
class inscritForm(forms.ModelForm) :
firstname = forms.CharField(max_length=50,widget=forms.TextInput(attrs={'class':'form-control'}))
class Meta :
model = Inscrit
fields = ['firstname','skills']
def __init__(self, *args, **kwargs):
super(inscritForm, self).__init__(*args, **kwargs)
thedomains = Domain.objects.values_list('name',flat=True)
self.fields["skills"] = forms.ModelMultipleChoiceField(queryset=thedomains, widget=forms.CheckboxSelectMultiple()
for key, field in self.fields.iteritems():
self.fields[key].required = False
And the models :
class Inscrit(models.Model):
user = models.OneToOneField(User)
competences = models.ManyToManyField(Speciality,related_name='specialities')
class Domain(models.Model):
name = models.CharField(max_length=20,primary_key=True)
def __str__(self) :
return self.name
def __unicode__(self) :
return self.name
#python_2_unicode_compatible
class Speciality(models.Model):
domain = models.ForeignKey(Domain,null=False)
specificity = models.TextField(max_length=100,null=True)
def __str__(self):
return u'%s %s'%(self.domain.name, self.specificity)
And finally my validation in the view :
...
if request.method == "POST" :
form = inscritForm(request.POST)
if form.is_valid() : # Errors here
...
I tested if instances of Domain have attribute 'pk' in the shell and YES they have...

Since are using a model multiple choice field, you should use a regular queryset instead of values().
thedomains = Domain.objects.all()
self.fields["skills"] = forms.ModelMultipleChoiceField(queryset=thedomains, widget=forms.CheckboxSelectMultiple())

Related

Django multiupload error: 'list' object has no attribute 'name'

I'm trying to use multiupload in django form for upload several images at once.
I'm using django ModelForm but when i'm calling form.is_valid() in function-base view or using generic.FormView, i'm getting 'list' object has no attribute 'name' error. in generic.FormView neither of form_valid and form_invalid methods aren't called. although when I use request.POST.get(some_data) it works without any errors but I want to use generic.FormView for some validations. I think the validation of the form makes the error happen.
so what should I do?
here is my code.
models.py
class Post(models.Model):
post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="posts")
text = models.TextField(max_length=1000)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
...
class Image(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="images")
image = models.ImageField(upload_to="images/posts/")
forms.py
class PostForm(forms.ModelForm):
images = MultiImageField(min_num=1, max_num=3)
class Meta:
model = models.Post
fields = ("text", "images")
views.py
class CreatePostView(LoginRequiredMixin, generic.FormView):
template_name = "posts/post_create.html"
form_class = forms.PostForm
def get_success_url(self):
return redirect("profile", slug=self.request.kwargs.slug)
def form_valid(self, form):
...
# some codes
...
return super(CreatePostView, self).form_valid(form)
error:
Traceback (most recent call last):
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 119, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\edit.py", line 152, in post
if form.is_valid():
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 205, in is_valid
return self.is_bound and not self.errors
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 200, in errors
self.full_clean()
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 433, in full_clean
self._clean_fields()
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 443, in _clean_fields
value = field.clean(value, bf.initial)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\fields.py", line 670, in clean
return super().clean(data)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\fields.py", line 200, in clean
self.run_validators(value)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\fields.py", line 185, in run_validators
v(value)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\validators.py", line 611, in validate_image_file_extension
return FileExtensionValidator(allowed_extensions=get_available_image_extensions())(
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\validators.py", line 576, in __call__
extension = Path(value.name).suffix[1:].lower()
Exception Type: AttributeError at /profile/ehsanadmin/post/create/
Exception Value: 'list' object has no attribute 'name'

Adding context to a Class Based View (detail view) geting an error get_context_data() got an unexpected keyword argument 'object'

I am trying to learn how to add a 2nd Context to a Class-Based view which has always been an issue for me and I can't get it right from the first time.
In my current project, I am trying to add a comment section to item detail view.
I am currently getting an error of get_context_data() got an unexpected keyword argument 'object'
which is from the item detail view as I indicated and I don't know who to fix it
Here is the item model:
class Item(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
here is the comment model:
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments")
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{} by {}'.format(self.subject, str(self.user.username))
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment']
here is the view:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(request, id):
context = super(ItemDetailView, request).get_context_data() <---------------- error from this line
context["comments"] = Comment.objects.filter(item_id=id, status='True')
return context
here is the add coment view
def addcomment(request,id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.item_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
Here is the traceback
Traceback (most recent call last):
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\detail.py", line 107, in get
context = self.get_context_data(object=self.object)
File "C:\Users\Ahmed\Desktop\Project 4.3\core\views.py", line 113, in get_context_data
context["comments"] = Comment.objects.filter(item_id=id, status='True')
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1315, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\fields\__init__.py", line 966, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'
The signature of get_context_data(...) method is wrong in your view. It should be as follows,
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["comments"] = Comment.objects.filter(item=self.object, status='True')
return context

Model form foreign key field to duration field not working

I have the following form where the user selects a value which corresponds to a duration field of the name value in a model called Duration.
When the form is submitted I'm getting this error
return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
Attribute Error - 'str' object has no attribute days.
Clearly Django expects the argument to be a timedelta object when this method is called and it is getting a string instead. Where am I at fault ?
The form :
class AuctionCreateForm(forms.ModelForm):
class Meta:
model = Auction
fields = ['title', 'reserve']
exclude = ('duration',)
labels = {'reserve': _('Reserve')}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["duration_value"] = forms.ModelChoiceField(
queryset=Duration.objects.all(),
empty_label=None,
to_field_name="value",
)
The view :
class AuctionCreate(CreateView):
""" View function for creating an auction """
form_class = AuctionCreateForm
template_name = "auction/auction_form.html"
def form_valid(self, form):
form.instance.start = timezone.now()
duration_value = form.cleaned_data.get('duration_value')
form.instance.duration = Duration.objects.get(value=duration_value)
form.instance.creator = self.request.user
return super().form_valid(form)
And here are the two models if it helps.
class Auction(models.Model):
""" Model for an auction """
uuid = models.UUIDField(
db_index=True,
default=uuid.uuid4,
editable=False,
)
title = models.CharField(max_length=10)
valid_from = models.DateTimeField(auto_now_add=True)
duration = models.ForeignKey(
Duration,
on_delete=models.SET_NULL,
null=True
)
reserve = models.PositiveIntegerField(default=0)
creator = models.ForeignKey(
get_user_model(),
on_delete=models.SET_NULL,
null=True,
)
winning_bid = models.ForeignKey(
'Bid',
related_name='highest_bid',
on_delete=models.SET_NULL,
null=True,
blank=True,
)
class Duration(models.Model):
""" Choice durations for auction """
value = models.DurationField()
def __str__(self):
return humanfriendly.format_timespan(self.value)
I know there is nothing wrong with the duration objects I have. I created them through the admin interface successfully where it provides a text field and entered a value in seconds. Furthermore, in another part of the application, where i list the auction, i can retrieve the values and do arithmetic on them.
Full Traceback -
[22/Apr/2019 13:08:54] "GET /auction/create/ HTTP/1.1" 200 3234
Internal Server Error: /auction/create/
Traceback (most recent call last):
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/views/generic/edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/views/generic/edit.py", line 141, in post
if form.is_valid():
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/forms/forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/forms/forms.py", line 180, in errors
self.full_clean()
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/forms/forms.py", line 381, in full_clean
self._clean_fields()
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/forms/forms.py", line 399, in _clean_fields
value = field.clean(value)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/forms/fields.py", line 148, in clean
value = self.to_python(value)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/forms/models.py", line 1248, in to_python
value = self.queryset.get(**{key: value})
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/query.py", line 402, in get
num = len(clone)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/query.py", line 256, in __len__
self._fetch_all()
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/query.py", line 55, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1084, in execute_sql
sql, params = self.as_sql()
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 486, in as_sql
where, w_params = self.compile(self.where) if self.where is not None else ("", [])
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 402, in compile
sql, params = node.as_sql(self, self.connection)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/sql/where.py", line 81, in as_sql
sql, params = compiler.compile(child)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 402, in compile
sql, params = node.as_sql(self, self.connection)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/lookups.py", line 163, in as_sql
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/lookups.py", line 260, in process_rhs
return super().process_rhs(compiler, connection)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/lookups.py", line 95, in process_rhs
return self.get_db_prep_lookup(value, connection)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/lookups.py", line 187, in get_db_prep_lookup
[get_db_prep_value(value, connection, prepared=True)]
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1619, in get_db_prep_value
return duration_microseconds(value)
File "/home/ross/.local/share/virtualenvs/v4-MIvAvlKB/lib/python3.6/site-packages/django/utils/duration.py", line 44, in duration_microseconds
return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
This is what the html for the select widget looks like -
<select name="duration_value" id="id_duration_value">
<option value="0:05:00">5 minutes</option>
<option value="0:10:00">10 minutes</option>
<option value="0:20:00">20 minutes</option>
<option value="0:40:00">40 minutes</option>
<option value="1:00:00">1 hour</option>
<option value="2:00:00">2 hours</option>
<option value="4:00:00">4 hours</option>
<option value="8:00:00">8 hours</option>
<option value="16:00:00">16 hours</option>
<option value="1 day, 0:00:00">1 day</option>
</select>
So, the problem is DurationField works on a timedelta object. So you need to convert your string to timedelta object and then perform the lookup
# views.py
from django.utils.dateparse import parse_duration
class AuctionCreate(CreateView):
""" View function for creating an auction """
form_class = AuctionCreateForm
template_name = "auction/auction_form.html"
def form_valid(self, form):
form.instance.start = timezone.now()
duration_value = form.cleaned_data.get('duration_value')
duration_obj = parse_duration(duration_value) # convert string to timedelta object
form.instance.duration = Duration.objects.get(value=duration_obj)
form.instance.creator = self.request.user
return super().form_valid(form)
In case it helps anyone...
Got it working like this for functions -
#login_required
def AuctionCreate(request):
if request.method == 'POST':
request.POST = request.POST.copy()
duration_value = request.POST["duration_value"]
duration_value = parse_duration(duration_value)
request.POST["duration_value"] = duration_value
print(request.POST)
form = AuctionCreateForm(request.POST)
if form.is_valid():
Auction.objects.create(
title=form.cleaned_data["title"],
valid_from=timezone.now(),
duration=Duration.objects.get(value=duration_value),
reserve=form.cleaned_data["reserve"],
creator=request.user,
winning_bid=None
)
return HttpResponse("Created auction")
else:
return HttpResponse("Something went wrong")
else:
form = AuctionCreateForm()
return render (
request,
'auction/auction_form.html',
{
'form': form
}
)
And like this for class based view -
""" View function for creating an auction """
form_class = AuctionCreateForm
template_name = "auction/auction_form.html"
def post(self, request, *args, **kwargs):
request.POST = request.POST.copy()
duration_value = request.POST["duration_value"]
duration_value = parse_duration(duration_value)
request.POST["duration_value"] = duration_value
return super().post(request, *args, **kwargs)
def form_valid(self, form):
form.instance.start = timezone.now()
duration_value = form.cleaned_data.get('duration_value')
form.instance.duration = duration_value
form.instance.creator = self.request.user
return super().form_valid(form)

djanga rest framwork: 'str' object has no attribute 'pk'

I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have composite pk on my table TestSuite. When I do a get() on the test_suites it throws an error - 'str' object has no attribute 'pk' . I haven't defined pk in my model, as with django I cannot define composite primary keys. Hence, django uses 'id' an autogenerated pk for the model. I cannot add id in my database (as I cannot modify the db).
The post() works as expected, however get() is throwing error through postman() as well as browsable API.
I am new to DRF. Any help is appreciated.
DB create statement:
CREATE TABLE `test_suite` (
`team_name` varchar(30) NOT NULL,
`suite_name` varchar(100) NOT NULL,
`description` varchar(200) DEFAULT NULL,
`schedule` varchar(100) DEFAULT NULL,
`email_list_ok` varchar(200) DEFAULT NULL,
`email_list_fail` varchar(200) DEFAULT NULL,
`template_name` varchar(100) NOT NULL,
PRIMARY KEY (`team_name`,`suite_name`),
KEY `fk_test_suite__email_templates` (`template_name`),
CONSTRAINT `fk_test_suite__email_templates` FOREIGN KEY (`template_name`) REFERENCES `email_templates` (`template_name`),
CONSTRAINT `fk_test_suite__team` FOREIGN KEY (`team_name`) REFERENCES `team` (`team_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I need to do a get() and post() to this table. Below are my models , serializers and viewsets.
models.py
class Team(models.Model):
team_name = models.CharField(primary_key=True, max_length=30)
description = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'team'
class TestSuite(models.Model):
team_name = models.ForeignKey(Team, on_delete=models.DO_NOTHING, db_column='team_name')
suite_name = models.CharField(max_length=100)
description = models.CharField(max_length=200, blank=True, null=True)
schedule = models.CharField(max_length=100, blank=True, null=True)
email_list_ok = models.CharField(max_length=200, blank=True, null=True)
email_list_fail = models.CharField(max_length=200, blank=True, null=True)
template_name = models.ForeignKey(EmailTemplates, on_delete=models.DO_NOTHING, db_column='template_name')
class Meta:
managed = False
db_table = 'test_suite'
unique_together = (('team_name', 'suite_name'),)
views.py
class TestSuiteViewSet(viewsets.ModelViewSet):
queryset = models.TestSuite.objects.values('team_name','suite_name', 'description','schedule','email_list_ok','email_list_fail','template_name')
serializer_class = serializers.TestSuiteSerializer
class TeamViewSet(viewsets.ModelViewSet):
queryset = models.Team.objects.all()
serializer_class = serializers.TeamSerializer
serializers.py
class TestSuiteSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestSuite
fields = ['team_name','suite_name', 'description','schedule','email_list_ok','email_list_fail','template_name']
Error Traceback:
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in data
768. ret = super(ListSerializer, self).data
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in to_representation
686. self.child.to_representation(item) for item in iterable
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in <listcomp>
686. self.child.to_representation(item) for item in iterable
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in to_representation
530. ret[field.field_name] = field.to_representation(attribute)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/relations.py" in to_representation
272. return value.pk
Exception Type: AttributeError at /dqf_api/test_suites/
Exception Value: 'str' object has no attribute 'pk'
urls.py
router = routers.DefaultRouter()
router.register(r'teams', views.TeamViewSet)
router.register(r'test_suites', views.TestSuiteViewSet)
urlpatterns = [ url(r'^dqf_api/', include(router.urls))]
EDIT:
I was able to resolve get()by adding below code to my serializers.py However, now my post() is not working - ValueError at /dqf_api/test_suites/
Cannot assign "'ede'": "TestSuiteModel.team_name" must be a "Team" instance.
def to_representation(self, obj):
return {
'team_name': obj.get('team_name'),
'suite_name': obj.get('suite_name'),
'description': obj.get('description'),
'schedule': obj.get('schedule'),
'email_list_ok': obj.get('email_list_ok'),
'email_list_fail': obj.get('email_list_fail'),
'template_name': obj.get('template_name'),
}
def to_internal_value(self, data):
return {
'team_name': data.get('team_name'),
'suite_name': data.get('suite_name'),
'description': data.get('description'),
'schedule': data.get('schedule'),
'email_list_ok': data.get('email_list_ok'),
'email_list_fail': data.get('email_list_fail'),
'template_name': data.get('template_name'),
}
Error Traceback:
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in save
214. self.instance = self.create(validated_data)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in create
943. instance = ModelClass._default_manager.create(**validated_data)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in create
415. obj = self.model(**kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py" in __init__
477. _setattr(self, field.name, rel_obj)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related_descriptors.py" in __set__
197. self.field.remote_field.model._meta.object_name,
Exception Type: ValueError at /dqf_api/test_suites/
Exception Value: Cannot assign "'ede'": "TestSuiteModel.team_name" must be a "Team" instance.
There was issue with serialization and deserialization with foreign key relations. I fixed it by adding below code to the serializers.py
class TestSuiteSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestSuiteModel
fields = ['team_name','suite_name', 'description','schedule','email_list_ok','email_list_fail','template_name']
def to_representation(self, obj):
if isinstance(obj, dict): # get methods
return obj
else:
self.fields['team_name'] = TeamSerializer()
self.fields['template_name'] = EmailTemplatesSerializer()
return super(TestSuiteSerializer, self).to_representation(obj)

Django 1.11 Invalid Literal for ManytoMany field when saving form

I have a model that has a many to many field. When I try to save it, it errors out with a invalid literal for int() with base 10: 'A' error. From other posts I've read it looks like it's something to do with the CharField in my forms.py. In my clean_states, I can print the value for self.cleaned_data['states'] and get back the two letter code of the state. I thought that was what was going to be saved to the database. I'm not sure why it thinks I'm trying to save an int.
models.py
class States(models.Model):
state = models.CharField(max_length=2, choices=US_STATES , null=True, blank=True)
def __str__(self):
return self.state
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
state = models.ManyToManyField(States)
views.py
class UserProfileUpdateView(LoginRequiredMixin, UpdateView):
model = Person
form_class = UserProfileChangeForm
template_name = 'accounts/profile-update-view.html'
def get_context_data(self, *args, **kwargs):
context = super(UserProfileUpdateView, self).get_context_data(*args, **kwargs)
context['states'] = States.objects.all()
return context
def get_object(self):
qs = Person.objects.filter(pk=self.request.user.person.user_id).first()
return qs
forms.py
class UserProfileChangeForm(forms.ModelForm):
state= forms.CharField(widget=USStateSelect(), initial='TX')
class Meta:
model = SkilledLaborer
fields = ['user','state']
def clean_user(self):
user = self.cleaned_data['user']
return user
def clean_state(self):
state= self.cleaned_data['state']
return state
def save(self, *args, **kwargs):
print('im saving')
print(self.cleaned_data['states'])
obj = super(UserProfileChangeForm, self).save(*args, **kwargs)
print('here2')
add_states = self.cleaned_data['states']
print(add_states)
print('here3')
if add_states:
for state in add_states.split(","):
state = States.objects.get(state=state)
obj.states.add(state)
return obj
stacktrace
Traceback:
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\contrib\auth\mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\views\generic\edit.py" in post
240. return super(BaseUpdateView, self).post(request, *args, **kwargs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\views\generic\edit.py" in post
183. return self.form_valid(form)
File "C:\Users\Starlord\Dev\ecommerce\src\accounts\views.py" in form_valid
174. form.save()
File "C:\Users\Starlord\Dev\ecommerce\src\accounts\forms.py" in save
105. obj = super(UserProfileChangeForm, self).save(*args, **kwargs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\forms\models.py" in save
469. self._save_m2m()
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\forms\models.py" in _save_m2m
451. f.save_form_data(self.instance, cleaned_data[f.name])
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related.py" in save_form_data
1686. getattr(instance, self.attname).set(data)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_descriptors.py" in set
1007. self.add(*new_objs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_descriptors.py" in add
934. self._add_items(self.source_field_name, self.target_field_name, *objs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_descriptors.py" in _add_items
1083. '%s__in' % target_field_name: new_ids,
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\query.py" in filter
784. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
802. clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\sql\query.py" in add_q
1250. clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\sql\query.py" in _add_q
1276. allow_joins=allow_joins, split_subq=split_subq,
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\sql\query.py" in build_filter
1206. condition = lookup_class(lhs, value)
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\lookups.py" in __init__
24. self.rhs = self.get_prep_lookup()
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_lookups.py" in get_prep_lookup
56. self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_lookups.py" in <listcomp>
56. self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
966. return int(value)
Exception Type: ValueError at /account/profile/
Exception Value: invalid literal for int() with base 10: 'A'