Say I have the next model:
STATUS_CHOICES = (
(0, 'open'),
(1, 'close'),
)
class Topic(models.Model):
user = models.ForeignKey(User)
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
status = models.SmallIntegerField(default=0, choices=STATUS_CHOICES)
status_date = models.DateTimeField(null=True, blank=True)
I try to send status in URL (‘open’ or ‘close’) and get it from function in view.
@login_required
def topic_status(request, topic_id, status):
try:
topic = Topic.objects.get(id=topic_id, user=request.user)
except ObjectDoesNotExist:
return HttpResponseRedirect('/error/')
topic.status = status
topic.status_date = datetime.now()
topic.save()
return HttpResponseRedirect(reverse('mainpage'))
But when I set topic.status value, which I receive from URL, I have such error (topic.status = status):
Exception Value: invalid literal for int() with base 10: 'close'
That’s because your status field is a
SmallIntegerField– it’s expecting an integer, not a string.Your valid choices are
0or1(although not enforced beyond the type in your example).Your front end should be displaying the human readable value and submitting the machine value.
You could alternatively map the strings to your integers with a dictionary:
Is there any reason you’re passing this data in the URL instead of say a POST request?