Changes values by default after UpdateViewHow do I sort a dictionary by value?“Least Astonishment” and the Mutable Default Argumentdjango - inlineformset_factory with more than one ForeignKeySaving form data rewrites the same rowShow information of subclass in list_display djangoProducts catalogue: filter by parametersRadio buttons in django adminHow to expose some specific fields of model_b based on a field of model_a?related name in parent model in django if inherited in other modelHow to define Mode with generic ForeignKey in Django

Short story written from alien perspective with this line: "It's too bright to look at, so they don't"

Smooth switching between 12v batteries, with toggle switch

Is it a problem that pull requests are approved without any comments

Dynamically loading CSS files based on URL or URI in PHP

Finding row wise sum of transpose of hv-convex binary matrix

Whats the next step after commercial fusion reactors?

How can drunken, homicidal elves successfully conduct a wild hunt?

X-shaped crossword

Opposite of "Squeaky wheel gets the grease"

How to generate random points without duplication?

Through what methods and mechanisms can a multi-material FDM printer operate?

How is TD(0) method helpful? What good does it do?

Does the growth of home value benefit from compound interest?

What's the correct term describing the action of sending a brand-new ship out into its first seafaring trip?

Can you please explain this joke: "I'm going bananas is what I tell my bananas before I leave the house"?

What is the purpose of building foundations?

Calling GPL'ed socket server inside Docker?

What do we gain with higher order logics?

How do I write "Show, Don't Tell" as an Asperger

Did thousands of women die every year due to illegal abortions before Roe v. Wade?

Why don't B747s start takeoffs with full throttle?

Funtion to extract float from different price patterns

Will TSA allow me to carry a Continuous Positive Airway Pressure (CPAP)/sleep apnea device?

Working in the USA for living expenses only; allowed on VWP?



Changes values by default after UpdateView


How do I sort a dictionary by value?“Least Astonishment” and the Mutable Default Argumentdjango - inlineformset_factory with more than one ForeignKeySaving form data rewrites the same rowShow information of subclass in list_display djangoProducts catalogue: filter by parametersRadio buttons in django adminHow to expose some specific fields of model_b based on a field of model_a?related name in parent model in django if inherited in other modelHow to define Mode with generic ForeignKey in Django






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















First of all, my apologize for mistakes in English.

I have three Models: Books (General Model), BookInfo (Information about book), Location (Position in Library) with Foreign Key.



models.py



class Location(models.Model):
room = models.PositiveIntegerField()
bookcase = models.PositiveIntegerField()
shelf = models.PositiveIntegerField()


class BookInfo(models.Model):
title = models.CharField(max_length=120)
author = models.CharField(max_length=150)
published = models.CharField(max_length=4)
position = models.ForeignKey(Location, on_delete = models.CASCADE, related_name = 'position_information')

def __str__(self):
return self.title
class Meta:
ordering = ['-id']
unique_together = ['title', 'author']


class Books(models.Model):

ON_HANDS = 1
IN_LIBRARY = 0
ALARM = -1

STATUS = (
(ON_HANDS, 'The book is on hands'),
(IN_LIBRARY, 'The book is in library'),
(ALARM, 'Need to return the book')
)

book = models.ForeignKey('BookInfo', on_delete = models.CASCADE, related_name = 'book_information')
date_of_issue = models.DateField(blank= True, default=timezone.now)
date_of_return = models.DateField(blank= True, default=date.today() + timedelta(days=14))
status_of_book = models.IntegerField(choices = STATUS, default = 0)

def __str__(self):
return self.book.title

class Meta:
ordering = ['-id']


forms.py



 class BookFormUpdate(forms.ModelForm):
class Meta:
model = Books

fields = ['book','date_of_issue','date_of_return','status_of_book']
widgets =
'date_of_issue': forms.DateInput(format=('%Y-%m-%d'), attrs='class':'form-control', 'placeholder':'Select a date', 'type':'date'),
'date_of_return': forms.DateInput(format=('%Y-%m-%d'), attrs='class':'form-control', 'placeholder':'Select a date', 'type':'date')



When I use Update Form for Books and change status of book to 1 or -1, I want automatically change the position of Book to (0,0,0). I overwrite my UpdateView but got some problem.



views.py



class MainUpdate(UpdateView): 
model = Books
template_name = 'core/detail.html'
form = BookFormUpdate

def form_valid(self, form):
form.save()
categories = get_object_or_404(self.model, pk=self.kwargs.get('pk'))
stat = form.cleaned_data['status_of_book']
if stat == 1 or stat == -1:
book_id = categories.book.id
BookInfo.objects.filter(id=book_id).update(position=Location.objects.get(id=32))
return redirect('/books-info/')


For updating the postion I used Location.objects.get(id=32) (id=32 corresponds to position (0,0,0)).
Is there another solution or better way without overwriting the UpdateView to change the position automatically?



I was trying to use such code:



# Not work
BookInfo.objects.filter(id=book_id).update(position__room=0,position__bookcase=0,position__shelf=0)

# Not work
BookInfo.objects.select_related().filter(id=book_id).update(position__room=0,position__bookcase=0,position__shelf=0)

# Not work
test = BookInfo.objects.get(id=book_id)
test.position__room=0
test.position__bookcase=0
test.position__shelf=0
test.save(update_fields=['position__room','position__bookcase','position__shelf'])


Thanks for advise and help










share|improve this question




























    0















    First of all, my apologize for mistakes in English.

    I have three Models: Books (General Model), BookInfo (Information about book), Location (Position in Library) with Foreign Key.



    models.py



    class Location(models.Model):
    room = models.PositiveIntegerField()
    bookcase = models.PositiveIntegerField()
    shelf = models.PositiveIntegerField()


    class BookInfo(models.Model):
    title = models.CharField(max_length=120)
    author = models.CharField(max_length=150)
    published = models.CharField(max_length=4)
    position = models.ForeignKey(Location, on_delete = models.CASCADE, related_name = 'position_information')

    def __str__(self):
    return self.title
    class Meta:
    ordering = ['-id']
    unique_together = ['title', 'author']


    class Books(models.Model):

    ON_HANDS = 1
    IN_LIBRARY = 0
    ALARM = -1

    STATUS = (
    (ON_HANDS, 'The book is on hands'),
    (IN_LIBRARY, 'The book is in library'),
    (ALARM, 'Need to return the book')
    )

    book = models.ForeignKey('BookInfo', on_delete = models.CASCADE, related_name = 'book_information')
    date_of_issue = models.DateField(blank= True, default=timezone.now)
    date_of_return = models.DateField(blank= True, default=date.today() + timedelta(days=14))
    status_of_book = models.IntegerField(choices = STATUS, default = 0)

    def __str__(self):
    return self.book.title

    class Meta:
    ordering = ['-id']


    forms.py



     class BookFormUpdate(forms.ModelForm):
    class Meta:
    model = Books

    fields = ['book','date_of_issue','date_of_return','status_of_book']
    widgets =
    'date_of_issue': forms.DateInput(format=('%Y-%m-%d'), attrs='class':'form-control', 'placeholder':'Select a date', 'type':'date'),
    'date_of_return': forms.DateInput(format=('%Y-%m-%d'), attrs='class':'form-control', 'placeholder':'Select a date', 'type':'date')



    When I use Update Form for Books and change status of book to 1 or -1, I want automatically change the position of Book to (0,0,0). I overwrite my UpdateView but got some problem.



    views.py



    class MainUpdate(UpdateView): 
    model = Books
    template_name = 'core/detail.html'
    form = BookFormUpdate

    def form_valid(self, form):
    form.save()
    categories = get_object_or_404(self.model, pk=self.kwargs.get('pk'))
    stat = form.cleaned_data['status_of_book']
    if stat == 1 or stat == -1:
    book_id = categories.book.id
    BookInfo.objects.filter(id=book_id).update(position=Location.objects.get(id=32))
    return redirect('/books-info/')


    For updating the postion I used Location.objects.get(id=32) (id=32 corresponds to position (0,0,0)).
    Is there another solution or better way without overwriting the UpdateView to change the position automatically?



    I was trying to use such code:



    # Not work
    BookInfo.objects.filter(id=book_id).update(position__room=0,position__bookcase=0,position__shelf=0)

    # Not work
    BookInfo.objects.select_related().filter(id=book_id).update(position__room=0,position__bookcase=0,position__shelf=0)

    # Not work
    test = BookInfo.objects.get(id=book_id)
    test.position__room=0
    test.position__bookcase=0
    test.position__shelf=0
    test.save(update_fields=['position__room','position__bookcase','position__shelf'])


    Thanks for advise and help










    share|improve this question
























      0












      0








      0








      First of all, my apologize for mistakes in English.

      I have three Models: Books (General Model), BookInfo (Information about book), Location (Position in Library) with Foreign Key.



      models.py



      class Location(models.Model):
      room = models.PositiveIntegerField()
      bookcase = models.PositiveIntegerField()
      shelf = models.PositiveIntegerField()


      class BookInfo(models.Model):
      title = models.CharField(max_length=120)
      author = models.CharField(max_length=150)
      published = models.CharField(max_length=4)
      position = models.ForeignKey(Location, on_delete = models.CASCADE, related_name = 'position_information')

      def __str__(self):
      return self.title
      class Meta:
      ordering = ['-id']
      unique_together = ['title', 'author']


      class Books(models.Model):

      ON_HANDS = 1
      IN_LIBRARY = 0
      ALARM = -1

      STATUS = (
      (ON_HANDS, 'The book is on hands'),
      (IN_LIBRARY, 'The book is in library'),
      (ALARM, 'Need to return the book')
      )

      book = models.ForeignKey('BookInfo', on_delete = models.CASCADE, related_name = 'book_information')
      date_of_issue = models.DateField(blank= True, default=timezone.now)
      date_of_return = models.DateField(blank= True, default=date.today() + timedelta(days=14))
      status_of_book = models.IntegerField(choices = STATUS, default = 0)

      def __str__(self):
      return self.book.title

      class Meta:
      ordering = ['-id']


      forms.py



       class BookFormUpdate(forms.ModelForm):
      class Meta:
      model = Books

      fields = ['book','date_of_issue','date_of_return','status_of_book']
      widgets =
      'date_of_issue': forms.DateInput(format=('%Y-%m-%d'), attrs='class':'form-control', 'placeholder':'Select a date', 'type':'date'),
      'date_of_return': forms.DateInput(format=('%Y-%m-%d'), attrs='class':'form-control', 'placeholder':'Select a date', 'type':'date')



      When I use Update Form for Books and change status of book to 1 or -1, I want automatically change the position of Book to (0,0,0). I overwrite my UpdateView but got some problem.



      views.py



      class MainUpdate(UpdateView): 
      model = Books
      template_name = 'core/detail.html'
      form = BookFormUpdate

      def form_valid(self, form):
      form.save()
      categories = get_object_or_404(self.model, pk=self.kwargs.get('pk'))
      stat = form.cleaned_data['status_of_book']
      if stat == 1 or stat == -1:
      book_id = categories.book.id
      BookInfo.objects.filter(id=book_id).update(position=Location.objects.get(id=32))
      return redirect('/books-info/')


      For updating the postion I used Location.objects.get(id=32) (id=32 corresponds to position (0,0,0)).
      Is there another solution or better way without overwriting the UpdateView to change the position automatically?



      I was trying to use such code:



      # Not work
      BookInfo.objects.filter(id=book_id).update(position__room=0,position__bookcase=0,position__shelf=0)

      # Not work
      BookInfo.objects.select_related().filter(id=book_id).update(position__room=0,position__bookcase=0,position__shelf=0)

      # Not work
      test = BookInfo.objects.get(id=book_id)
      test.position__room=0
      test.position__bookcase=0
      test.position__shelf=0
      test.save(update_fields=['position__room','position__bookcase','position__shelf'])


      Thanks for advise and help










      share|improve this question














      First of all, my apologize for mistakes in English.

      I have three Models: Books (General Model), BookInfo (Information about book), Location (Position in Library) with Foreign Key.



      models.py



      class Location(models.Model):
      room = models.PositiveIntegerField()
      bookcase = models.PositiveIntegerField()
      shelf = models.PositiveIntegerField()


      class BookInfo(models.Model):
      title = models.CharField(max_length=120)
      author = models.CharField(max_length=150)
      published = models.CharField(max_length=4)
      position = models.ForeignKey(Location, on_delete = models.CASCADE, related_name = 'position_information')

      def __str__(self):
      return self.title
      class Meta:
      ordering = ['-id']
      unique_together = ['title', 'author']


      class Books(models.Model):

      ON_HANDS = 1
      IN_LIBRARY = 0
      ALARM = -1

      STATUS = (
      (ON_HANDS, 'The book is on hands'),
      (IN_LIBRARY, 'The book is in library'),
      (ALARM, 'Need to return the book')
      )

      book = models.ForeignKey('BookInfo', on_delete = models.CASCADE, related_name = 'book_information')
      date_of_issue = models.DateField(blank= True, default=timezone.now)
      date_of_return = models.DateField(blank= True, default=date.today() + timedelta(days=14))
      status_of_book = models.IntegerField(choices = STATUS, default = 0)

      def __str__(self):
      return self.book.title

      class Meta:
      ordering = ['-id']


      forms.py



       class BookFormUpdate(forms.ModelForm):
      class Meta:
      model = Books

      fields = ['book','date_of_issue','date_of_return','status_of_book']
      widgets =
      'date_of_issue': forms.DateInput(format=('%Y-%m-%d'), attrs='class':'form-control', 'placeholder':'Select a date', 'type':'date'),
      'date_of_return': forms.DateInput(format=('%Y-%m-%d'), attrs='class':'form-control', 'placeholder':'Select a date', 'type':'date')



      When I use Update Form for Books and change status of book to 1 or -1, I want automatically change the position of Book to (0,0,0). I overwrite my UpdateView but got some problem.



      views.py



      class MainUpdate(UpdateView): 
      model = Books
      template_name = 'core/detail.html'
      form = BookFormUpdate

      def form_valid(self, form):
      form.save()
      categories = get_object_or_404(self.model, pk=self.kwargs.get('pk'))
      stat = form.cleaned_data['status_of_book']
      if stat == 1 or stat == -1:
      book_id = categories.book.id
      BookInfo.objects.filter(id=book_id).update(position=Location.objects.get(id=32))
      return redirect('/books-info/')


      For updating the postion I used Location.objects.get(id=32) (id=32 corresponds to position (0,0,0)).
      Is there another solution or better way without overwriting the UpdateView to change the position automatically?



      I was trying to use such code:



      # Not work
      BookInfo.objects.filter(id=book_id).update(position__room=0,position__bookcase=0,position__shelf=0)

      # Not work
      BookInfo.objects.select_related().filter(id=book_id).update(position__room=0,position__bookcase=0,position__shelf=0)

      # Not work
      test = BookInfo.objects.get(id=book_id)
      test.position__room=0
      test.position__bookcase=0
      test.position__shelf=0
      test.save(update_fields=['position__room','position__bookcase','position__shelf'])


      Thanks for advise and help







      python django django-views






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 14:22









      amyardamyard

      13




      13






















          0






          active

          oldest

          votes












          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%2f55324769%2fchanges-values-by-default-after-updateview%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          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%2f55324769%2fchanges-values-by-default-after-updateview%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현