Home python Django CreateView: Automatic field setting

Django CreateView: Automatic field setting

Author

Date

Category

There is a POST and Author model:

class post (models.model):
  Post_Author = Models.ForeignKey (Author, On_Delete = Models.cascade, Verbose_Name = 'Author')
  Post_Text = Models.TextField (NULL = FALSE)
Class Author (Models.Model):
  Author = Models.Onetoonefield (settings.auth_user_model, on_delete = Models.Cascade)

In View It is created through CreateView:

class postcreateview (CreateView):
  template_name = 'news / create_post.html'
  Form_class = postform

The form is described in this form:

Class Postform (Modelform):
  Class Meta:
    Model = Post.
    Fields = ['post_author', 'post_text']

Is it possible to remove the ‘post_author’ field from the form and transfer the author without choosing from the list of all authors, since the filling form of the user himself will be the author.
Specify in the author model as Default = failed, because The model could not pass the Request object.


Answer 1, Authority 100%

Thank you for a good tip! According to the result, it turned out:

# Jennik to create a post
Class PostcreateView (PermissionRequiredMixin, CreateView):
  template_name = 'news / create_post.html'
  Form_class = postform
  permission_required = ('news.add_post')
  RAISE_EXCEPTION = True.
  # Function for custom validating field shape field
  Def Form_Valid (Self, Form):
    # Create a form, but do not send it to the database, while just keep in mind
    Fields = Form.Save (Commit = False)
    # Through the requester we pass the missing uniform that is required
    fields.post_author = author.Objects.get (author = self.request.user)
    # Finally save in database
    fields.save ()
    Return Super (). Form_Valid (Form)

Answer 2

can so try

class postcreateview (CreateView):
  Def Post (Self, Request, * Args, ** kwargs):
    Form = Postform (Request.post)
    If form.is_valid ():
      Instance = Fam.Save (Commit = False)
      Instance.post_author = Self.request.user.
      instance.save ()
      Return httpresponseredirect (......)
    Return Render (Request, 'NEWS / CREATE_POST.HTML', {'Form': Form})

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions