Я пытаюсь обновить проект Django с Django (1.10) до Django (2.1), при этом я просто застрял в одной ошибке, где я использовал request.user.pk
для передачи пользователю создания объекта
Вот что у меня есть:
От models.py
:
class TaggedArticle(models.Model):
user = models.ForeignKey(User, related_name='tagging', on_delete=models.CASCADE)
email = models.EmailField(max_length=255)
category_fit = models.CharField(choices=choices, max_length=255)
article = models.ForeignKey(Article, related_name='articles', on_delete=models.CASCADE)
link = models.URLField(max_length=255,)
relevant_feedback = models.TextField(blank=True)
category = models.CharField(max_length=255,)
created_at = models.DateTimeField(default=timezone.now, editable=False)
От forms.py
:
class TagForm(forms.ModelForm):
class Meta:
model = TaggedArticle
fields = ('user', 'category_fit', 'article', 'link', 'relevant_feedback', 'category',)
widgets = {
'category_fit': forms.RadioSelect()
}
И с views.py
:
class TagView(LoginRequiredMixin, generic.CreateView):
form_class = forms.TagForm
def post(self, request, *args, **kwargs):
try:
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
print(post_data.values)
form = forms.TagForm(post_data)
if form.is_valid():
tag = form.save(commit=False)
tag.user = request.user
tag.email = request.user.email
tag.save()
request.session['user'] = tag.user
request.session['email'] = tag.email
else:
print(form.errors)
return HttpResponse(form.errors, status=400)
print('going to redirect after successful tagging.')
return HttpResponseRedirect(reverse('users:dashboard'))
except Exception as exp:
logging.error(exp)
print('error is: {}'.format(exp))
return HttpResponse(exp, status=400)
Обновление: Вот HTML-форма из шаблона:
<form class="omb_loginForm" action="{% url 'users:tagged' %}" method="POST">
{% csrf_token %}
<table class="table">
<thead><h4> Tag this Article:</h4></thead>
<tbody>
<tr>
<th>Reviewer:</th>
<td></td>
<td>{{ user.username }}</td>
</tr>
<tr>
<th>No of Article Reviewed:</th>
<td></td>
<td>{{ user.tagging.all |length }}</td>
</tr>
<tr>
<th>Category:</th>
<td></td>
<td>{{ art.category }}
<input type="hidden" value="{{ art.id }}" name="article"/>
<input type="hidden" value="{{ art.link }}" name="link"/>
<input type="hidden" value="{{ art.category }}" name="category"/>
</td>
</tr>
<tr>
<th>Does the text of this article fit in this category?</th>
<td><label class="radio-inline"><input type="radio" name="category_fit"
value="yes">Yes</label></td>
<td><label class="radio-inline"><input type="radio" name="category_fit"
value="no">No</label></td>
<td><label class="radio-inline"><input type="radio" name="category_fit"
value="not sure">Not Sure</label>
</td>
</tr>
<tr>
<th><label for="comment">Copy and then paste in a relevant sentence for categorization:</label></th>
<td colspan="3">
<textarea class="form-control" rows="7" id="comment"
name="relevant_feedback"></textarea>
</td>
</tr>
</tbody>
</table>
<button class="btn btn-lg btn-primary btn-block" type="submit">Tag</button>
</form>
Таким образом, при запросе POST
возвращается следующая ошибка:
TypeError: Object of type 'User' is not JSON serializable
Когда я печатаю form.errors
, то печатается:
<ul class="errorlist"><li>user<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>
Так что тут не так?
Заранее спасибо!