I have this django model for questions.
class Question(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.SET_NULL)
question_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False)
question = models.CharField(max_length=150, null=False)
question_description = FroalaField()
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
question_image = models.ImageField(upload_to=get_upload_path, blank=True, null=True)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
dynamic_link = models.CharField(max_length=225, null=False, default="")
question_type = models.CharField( max_length=50, null=False, choices=QUESTIONSTYPE_LIST)
question_status = models.CharField(max_length=150, null=False, default="unapproved")
is_active = models.BooleanField(default=False)
objects = QuestionManager()
class Meta:
ordering = ['-updated_at']
def __str__(self):
return self.question_id
def get_absolute_url(self):
kwargs = {
'questiontype': slugify(self.question_type),
'questionid': self.question_id,
'slug': slugify(self.question)
}
return reverse("questions:detail", kwargs=kwargs)
Everything seems to be working okay, except that the user user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.SET_NULL) always saves but the default which is 1. So no matter which user is logged in and in session, it always defaults to 1.
I am using classed-based-views and the user is a CustomUser.
I have the customUser set in settings.py auth_model_user as:
AUTH_USER_MODEL = 'users.CustomUser'
Here is the form for Question:
class QuestionCreationUpdateForm(forms.ModelForm):
question = forms.CharField(widget=forms.TextInput(attrs={
'class': 'frm-input',
'placeholder': _('Enter question title'),
'autocomplete': 'off'
}))
question_type = forms.ChoiceField(choices=QUESTIONSTYPE_LIST, widget=forms.Select(attrs={'class': 'frm-input'}))
question_description = forms.CharField(widget=FroalaEditor)
def __init__(self, *args, **kwargs):
super(QuestionCreationUpdateForm, self).__init__(*args, **kwargs)
class Meta:
model = Question
fields = ('question', 'question_description', 'question_type')
And the question CreateView:
# Add Question View
@method_decorator(login_required, name='dispatch')
class AskQuestionView(CreateView):
template_name = 'ask_question.html'
form_class = QuestionCreationUpdateForm
model = Question
def form_valid(self, form):
try:
return super(AskQuestionView, self).form_valid(form)
except IntegrityError:
context = {
'msg': _('We don\'t allow continues posting! Take a break. Try again later!')
}
return render(self.request, "500.html", context)
def get_success_url(self):
return self.object.get_absolute_url()
If I do a request.user in the views.py file, I always get the right user.
So why is my model behaving this odd?
Question
? – Klaus D.