How to auto initialize fields in a Django model?












-1















I have the following model in Django and basically I need to to auto initialize 3 out of 5 fields once the user has inserted some data, i.e.,



Models.py



class Assignment(models.Model):
assignment = models.CharField(max_length=60)
comments = models.CharField(max_length=60)
starting_date = models.DateField()
points = models.IntegerField()
STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done'))
status = models.CharField(max_length=1, choices=STATUS)


Forms.py



from django import forms
from .models import Task

class TaskForm(forms.ModelForm):
class Meta:
model = Task
starting_date = datetime.now()
fields = ['task_description', 'task_comments', 'starting_date', 'priority', 'points']


Input form



<!-- Input form to request to values-->
<div class="panel-heading">Add a new assignment </div>
<form id ="insert_new_assign" class="form-horizontal" method="POST">
{% csrf_token %}
<div class="panel-body">
<div class="input-group">
<input class="form-control" name="insert_new_assign_field" type="text" placeholder="Insert your new assignment here" />
<input class="form-control" name="insert_new_comment_field" type="text" placeholder="Any comment you want to add?" />
<button class="btn btn-primary" type="submit">Add</button>
</div>
</div>
</form>
</div>


See the JS fiddle for quick reference



Basically when the user enters a new assignment and comment, I want Django to save these two fields and auto initialize the other fields with the current time, 0 points and A status. Whenever I try to to save a new record, I get the error The view engine.views.home didn't return an HttpResponse object which is normal because Django expects from the user to complete all the fields and not only two.



Previous research



Based on some research, I found out that only one field can be completed in a Django model - the id - but at the same time they mention the Custom Managers which are classes that can address the problem I have, however, the examples they provide do not fit for my current situation.



My main question is:



How can I indicate in Django to save the two fields and auto initialize the other fields with the current date and time, 0 points and A status?



Any help in this questions will be greatly appreciated, feel free to improve this question as well.










share|improve this question




















  • 1





    For starting_time you can add auto_now_add to True in your model, For integer field add default to 0 and for status add the default id of status and also add blank and null in those case. In forms.py mark them with required = False.

    – Bidhan Majhi
    Nov 22 '18 at 7:49













  • So, the models.py should have starting_date = models.DateField(auto_now_add=True) something like this?

    – Alejandro BR
    Nov 22 '18 at 7:51











  • Yes. And also skip it from the form's field.

    – Bidhan Majhi
    Nov 22 '18 at 7:54











  • I have made some of your suggestions but I found out another problem: django.core.exceptions.FieldError: 'starting_date' cannot be specified for Task model form as it is a non-editable field . Is there any chance you can illustrate your code as an answer?

    – Alejandro BR
    Nov 22 '18 at 8:00











  • The problem you describe has nothing at all to do with your models or initialisation, but is entirely contained within the view, which you didn't post.

    – Daniel Roseman
    Nov 22 '18 at 9:24
















-1















I have the following model in Django and basically I need to to auto initialize 3 out of 5 fields once the user has inserted some data, i.e.,



Models.py



class Assignment(models.Model):
assignment = models.CharField(max_length=60)
comments = models.CharField(max_length=60)
starting_date = models.DateField()
points = models.IntegerField()
STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done'))
status = models.CharField(max_length=1, choices=STATUS)


Forms.py



from django import forms
from .models import Task

class TaskForm(forms.ModelForm):
class Meta:
model = Task
starting_date = datetime.now()
fields = ['task_description', 'task_comments', 'starting_date', 'priority', 'points']


Input form



<!-- Input form to request to values-->
<div class="panel-heading">Add a new assignment </div>
<form id ="insert_new_assign" class="form-horizontal" method="POST">
{% csrf_token %}
<div class="panel-body">
<div class="input-group">
<input class="form-control" name="insert_new_assign_field" type="text" placeholder="Insert your new assignment here" />
<input class="form-control" name="insert_new_comment_field" type="text" placeholder="Any comment you want to add?" />
<button class="btn btn-primary" type="submit">Add</button>
</div>
</div>
</form>
</div>


See the JS fiddle for quick reference



Basically when the user enters a new assignment and comment, I want Django to save these two fields and auto initialize the other fields with the current time, 0 points and A status. Whenever I try to to save a new record, I get the error The view engine.views.home didn't return an HttpResponse object which is normal because Django expects from the user to complete all the fields and not only two.



Previous research



Based on some research, I found out that only one field can be completed in a Django model - the id - but at the same time they mention the Custom Managers which are classes that can address the problem I have, however, the examples they provide do not fit for my current situation.



My main question is:



How can I indicate in Django to save the two fields and auto initialize the other fields with the current date and time, 0 points and A status?



Any help in this questions will be greatly appreciated, feel free to improve this question as well.










share|improve this question




















  • 1





    For starting_time you can add auto_now_add to True in your model, For integer field add default to 0 and for status add the default id of status and also add blank and null in those case. In forms.py mark them with required = False.

    – Bidhan Majhi
    Nov 22 '18 at 7:49













  • So, the models.py should have starting_date = models.DateField(auto_now_add=True) something like this?

    – Alejandro BR
    Nov 22 '18 at 7:51











  • Yes. And also skip it from the form's field.

    – Bidhan Majhi
    Nov 22 '18 at 7:54











  • I have made some of your suggestions but I found out another problem: django.core.exceptions.FieldError: 'starting_date' cannot be specified for Task model form as it is a non-editable field . Is there any chance you can illustrate your code as an answer?

    – Alejandro BR
    Nov 22 '18 at 8:00











  • The problem you describe has nothing at all to do with your models or initialisation, but is entirely contained within the view, which you didn't post.

    – Daniel Roseman
    Nov 22 '18 at 9:24














-1












-1








-1








I have the following model in Django and basically I need to to auto initialize 3 out of 5 fields once the user has inserted some data, i.e.,



Models.py



class Assignment(models.Model):
assignment = models.CharField(max_length=60)
comments = models.CharField(max_length=60)
starting_date = models.DateField()
points = models.IntegerField()
STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done'))
status = models.CharField(max_length=1, choices=STATUS)


Forms.py



from django import forms
from .models import Task

class TaskForm(forms.ModelForm):
class Meta:
model = Task
starting_date = datetime.now()
fields = ['task_description', 'task_comments', 'starting_date', 'priority', 'points']


Input form



<!-- Input form to request to values-->
<div class="panel-heading">Add a new assignment </div>
<form id ="insert_new_assign" class="form-horizontal" method="POST">
{% csrf_token %}
<div class="panel-body">
<div class="input-group">
<input class="form-control" name="insert_new_assign_field" type="text" placeholder="Insert your new assignment here" />
<input class="form-control" name="insert_new_comment_field" type="text" placeholder="Any comment you want to add?" />
<button class="btn btn-primary" type="submit">Add</button>
</div>
</div>
</form>
</div>


See the JS fiddle for quick reference



Basically when the user enters a new assignment and comment, I want Django to save these two fields and auto initialize the other fields with the current time, 0 points and A status. Whenever I try to to save a new record, I get the error The view engine.views.home didn't return an HttpResponse object which is normal because Django expects from the user to complete all the fields and not only two.



Previous research



Based on some research, I found out that only one field can be completed in a Django model - the id - but at the same time they mention the Custom Managers which are classes that can address the problem I have, however, the examples they provide do not fit for my current situation.



My main question is:



How can I indicate in Django to save the two fields and auto initialize the other fields with the current date and time, 0 points and A status?



Any help in this questions will be greatly appreciated, feel free to improve this question as well.










share|improve this question
















I have the following model in Django and basically I need to to auto initialize 3 out of 5 fields once the user has inserted some data, i.e.,



Models.py



class Assignment(models.Model):
assignment = models.CharField(max_length=60)
comments = models.CharField(max_length=60)
starting_date = models.DateField()
points = models.IntegerField()
STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done'))
status = models.CharField(max_length=1, choices=STATUS)


Forms.py



from django import forms
from .models import Task

class TaskForm(forms.ModelForm):
class Meta:
model = Task
starting_date = datetime.now()
fields = ['task_description', 'task_comments', 'starting_date', 'priority', 'points']


Input form



<!-- Input form to request to values-->
<div class="panel-heading">Add a new assignment </div>
<form id ="insert_new_assign" class="form-horizontal" method="POST">
{% csrf_token %}
<div class="panel-body">
<div class="input-group">
<input class="form-control" name="insert_new_assign_field" type="text" placeholder="Insert your new assignment here" />
<input class="form-control" name="insert_new_comment_field" type="text" placeholder="Any comment you want to add?" />
<button class="btn btn-primary" type="submit">Add</button>
</div>
</div>
</form>
</div>


See the JS fiddle for quick reference



Basically when the user enters a new assignment and comment, I want Django to save these two fields and auto initialize the other fields with the current time, 0 points and A status. Whenever I try to to save a new record, I get the error The view engine.views.home didn't return an HttpResponse object which is normal because Django expects from the user to complete all the fields and not only two.



Previous research



Based on some research, I found out that only one field can be completed in a Django model - the id - but at the same time they mention the Custom Managers which are classes that can address the problem I have, however, the examples they provide do not fit for my current situation.



My main question is:



How can I indicate in Django to save the two fields and auto initialize the other fields with the current date and time, 0 points and A status?



Any help in this questions will be greatly appreciated, feel free to improve this question as well.







django python-3.x django-models django-forms






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 9:32









cezar

5,61232454




5,61232454










asked Nov 22 '18 at 7:42









Alejandro BRAlejandro BR

5852927




5852927








  • 1





    For starting_time you can add auto_now_add to True in your model, For integer field add default to 0 and for status add the default id of status and also add blank and null in those case. In forms.py mark them with required = False.

    – Bidhan Majhi
    Nov 22 '18 at 7:49













  • So, the models.py should have starting_date = models.DateField(auto_now_add=True) something like this?

    – Alejandro BR
    Nov 22 '18 at 7:51











  • Yes. And also skip it from the form's field.

    – Bidhan Majhi
    Nov 22 '18 at 7:54











  • I have made some of your suggestions but I found out another problem: django.core.exceptions.FieldError: 'starting_date' cannot be specified for Task model form as it is a non-editable field . Is there any chance you can illustrate your code as an answer?

    – Alejandro BR
    Nov 22 '18 at 8:00











  • The problem you describe has nothing at all to do with your models or initialisation, but is entirely contained within the view, which you didn't post.

    – Daniel Roseman
    Nov 22 '18 at 9:24














  • 1





    For starting_time you can add auto_now_add to True in your model, For integer field add default to 0 and for status add the default id of status and also add blank and null in those case. In forms.py mark them with required = False.

    – Bidhan Majhi
    Nov 22 '18 at 7:49













  • So, the models.py should have starting_date = models.DateField(auto_now_add=True) something like this?

    – Alejandro BR
    Nov 22 '18 at 7:51











  • Yes. And also skip it from the form's field.

    – Bidhan Majhi
    Nov 22 '18 at 7:54











  • I have made some of your suggestions but I found out another problem: django.core.exceptions.FieldError: 'starting_date' cannot be specified for Task model form as it is a non-editable field . Is there any chance you can illustrate your code as an answer?

    – Alejandro BR
    Nov 22 '18 at 8:00











  • The problem you describe has nothing at all to do with your models or initialisation, but is entirely contained within the view, which you didn't post.

    – Daniel Roseman
    Nov 22 '18 at 9:24








1




1





For starting_time you can add auto_now_add to True in your model, For integer field add default to 0 and for status add the default id of status and also add blank and null in those case. In forms.py mark them with required = False.

– Bidhan Majhi
Nov 22 '18 at 7:49







For starting_time you can add auto_now_add to True in your model, For integer field add default to 0 and for status add the default id of status and also add blank and null in those case. In forms.py mark them with required = False.

– Bidhan Majhi
Nov 22 '18 at 7:49















So, the models.py should have starting_date = models.DateField(auto_now_add=True) something like this?

– Alejandro BR
Nov 22 '18 at 7:51





So, the models.py should have starting_date = models.DateField(auto_now_add=True) something like this?

– Alejandro BR
Nov 22 '18 at 7:51













Yes. And also skip it from the form's field.

– Bidhan Majhi
Nov 22 '18 at 7:54





Yes. And also skip it from the form's field.

– Bidhan Majhi
Nov 22 '18 at 7:54













I have made some of your suggestions but I found out another problem: django.core.exceptions.FieldError: 'starting_date' cannot be specified for Task model form as it is a non-editable field . Is there any chance you can illustrate your code as an answer?

– Alejandro BR
Nov 22 '18 at 8:00





I have made some of your suggestions but I found out another problem: django.core.exceptions.FieldError: 'starting_date' cannot be specified for Task model form as it is a non-editable field . Is there any chance you can illustrate your code as an answer?

– Alejandro BR
Nov 22 '18 at 8:00













The problem you describe has nothing at all to do with your models or initialisation, but is entirely contained within the view, which you didn't post.

– Daniel Roseman
Nov 22 '18 at 9:24





The problem you describe has nothing at all to do with your models or initialisation, but is entirely contained within the view, which you didn't post.

– Daniel Roseman
Nov 22 '18 at 9:24












1 Answer
1






active

oldest

votes


















0














After some suggestions made from Bidhan, I was able to get the following code to bypass the problem.



from django.utils import timezone

class Assignment(models.Model):
STATUS = (
('A', 'Active'),
('C', 'Cancelled'),
('D', 'Done')
)

assignment = models.CharField(max_length=60)
comments = models.CharField(max_length=60)
starting_date = models.DateField(default=timezone.now())
points = models.IntegerField(default=0)
status = models.CharField(max_length=1, choices=STATUS, default='A')





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53426045%2fhow-to-auto-initialize-fields-in-a-django-model%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    After some suggestions made from Bidhan, I was able to get the following code to bypass the problem.



    from django.utils import timezone

    class Assignment(models.Model):
    STATUS = (
    ('A', 'Active'),
    ('C', 'Cancelled'),
    ('D', 'Done')
    )

    assignment = models.CharField(max_length=60)
    comments = models.CharField(max_length=60)
    starting_date = models.DateField(default=timezone.now())
    points = models.IntegerField(default=0)
    status = models.CharField(max_length=1, choices=STATUS, default='A')





    share|improve this answer






























      0














      After some suggestions made from Bidhan, I was able to get the following code to bypass the problem.



      from django.utils import timezone

      class Assignment(models.Model):
      STATUS = (
      ('A', 'Active'),
      ('C', 'Cancelled'),
      ('D', 'Done')
      )

      assignment = models.CharField(max_length=60)
      comments = models.CharField(max_length=60)
      starting_date = models.DateField(default=timezone.now())
      points = models.IntegerField(default=0)
      status = models.CharField(max_length=1, choices=STATUS, default='A')





      share|improve this answer




























        0












        0








        0







        After some suggestions made from Bidhan, I was able to get the following code to bypass the problem.



        from django.utils import timezone

        class Assignment(models.Model):
        STATUS = (
        ('A', 'Active'),
        ('C', 'Cancelled'),
        ('D', 'Done')
        )

        assignment = models.CharField(max_length=60)
        comments = models.CharField(max_length=60)
        starting_date = models.DateField(default=timezone.now())
        points = models.IntegerField(default=0)
        status = models.CharField(max_length=1, choices=STATUS, default='A')





        share|improve this answer















        After some suggestions made from Bidhan, I was able to get the following code to bypass the problem.



        from django.utils import timezone

        class Assignment(models.Model):
        STATUS = (
        ('A', 'Active'),
        ('C', 'Cancelled'),
        ('D', 'Done')
        )

        assignment = models.CharField(max_length=60)
        comments = models.CharField(max_length=60)
        starting_date = models.DateField(default=timezone.now())
        points = models.IntegerField(default=0)
        status = models.CharField(max_length=1, choices=STATUS, default='A')






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 22 '18 at 9:34









        cezar

        5,61232454




        5,61232454










        answered Nov 22 '18 at 8:50









        Alejandro BRAlejandro BR

        5852927




        5852927






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53426045%2fhow-to-auto-initialize-fields-in-a-django-model%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Tonle Sap (See)

            I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

            Guatemaltekische Davis-Cup-Mannschaft