Answer the question
In order to leave comments, you need to log in
Issues with ForeignKey(): IntegrityError at /question/ask/ what is the cause?
Hello, tell me what the problem is, I can’t create a question through the site, the question is created in the admin panel. As far as I understand, the problem is in the database, but I don’t know how to fix it, who can tell me.
here is models.py:
class Question(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
pub_date = models.DateTimeField(timezone.now)
author = models.ForeignKey(User)
views = models.IntegerField(default=0)
slug = models.SlugField(max_length=240, blank=True)
tag = TaggableManager()
def __unicode__(self):
return self.title
def ask(request):
if request.method == 'POST':
form = AskForm(request.POST)
if form.is_valid():
question = form.save(commit=False)
question.user = request.user
question.save()
return redirect('/question/one_question') + str(question.id)
return HttpResponseBadRequest()
class AskForm(forms.ModelForm):
tag = forms.CharField(max_length=100, required=False, label='Tags:',
help_text="Write here some tags, example: python, django ")
class Meta:
model = Question
fields = ['title', 'content']
labels = {
'title': 'Title', 'content': 'Text of your question'
}
Answer the question
In order to leave comments, you need to log in
question.user = request.user - what is this user field that is not in the model description?
I did it by example, I just substituted my data, I thought it was a reference to User. changed views to this one:
def ask(request):
if request.method == 'POST':
form = AskForm(request.POST)
if form.is_valid():
question = form.save(commit=False)
question.author = request.user
question.save()
return redirect('/question/one_question') + str(question.id)
return HttpResponseBadRequest()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question