Reputation: 47
I'm new in the Django.I have 2 models, one of them Post,
class Post(models.Model):
unit = models.ForeignKey('Unit',on_delete=models.CASCADE, primary_key=False, blank = True)
and next is Unit model,
class Unit(models.Model):
name = models.CharField(max_length=120, unique = True)
def __str__(self):
return self.name
I use ForeignKey, and i have such problem. In my site I use Unit model like drop down list
<div class="form-group">
<label for="id_unit">Unit</label>
<select class="selectpicker form-control" data-live-search="true" name="unit">
{%for unit in units%}
<option>{{ unit.name }}</option>
{%endfor%}
</select>
</div>
and when I try to create a new Post by site I have a value error "Cannot assign "'Moscow'": "Post.unit" must be a "Unit" instance."
This is my function in the view.py, that create.
def post_new(request):
posts = Post.objects.all()
units = Unit.objects.all()
if request.method == 'POST':
title = request.POST['title']
text = request.POST['text']
unit = request.POST['unit']
user = User.objects.first()
status = StatusOfPost.objects.first()
post = Post.objects.create(
author = user,
title = title,
text = text,
unit = unit,
status = status
)
return redirect('postsList')
return render(request, 'post_new.html', {'posts': posts, 'units': units})
What I must do, i don't understand. How apply Unit.name value to Post.unit. Sorry for the stupid question, but I'm learning.
Upvotes: 2
Views: 286
Reputation: 1984
In your view, request.POST['unit']
is not a Unit
object but a name, you need to query the Unit
object.
So replace:
unit = request.POST['unit']
by:
unit = Unit.objects.get(name=request.POST['unit'])
Upvotes: 2