0
votes

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?

2
How do you create an instance of Question?Klaus D.
I have form, I will edit the code to add the formLearnToday
Can you share your view's code?ruddra
@ruddra I have that added.LearnToday

2 Answers

2
votes

As I can see, you need to assign the User object to form instance. Like this:

@method_decorator(login_required, name='dispatch')
class AskQuestionView(CreateView):
    ...

    def form_valid(self, form):
        try:
            obj = form.save(commit=False)
            obj.user = self.request.user
            return super(AskQuestionView, self).form_valid(obj)
        except IntegrityError:
            context = {
                'msg': _('We don\'t allow continues posting! Take a break. Try again later!')
            }
            return  render(self.request, "500.html", context)  
            # ^^ consider using a 400 error response, as 500 is for server error response. 400 is for bad request
    ...
1
votes

You are not assigning any user to Question.user. You need to assign the current user to that field.

@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:
            form.instance.user = self.request.user
            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)

Further read Models and request.user