Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8156037
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T16:50:04+00:00 2026-06-06T16:50:04+00:00

For example. class One(models.Model): text=models.CharField(max_length=100) class Two(models.Model): test = models.Integer() many = models.ManyToManyField(One, blank=True)

  • 0

For example.

class One(models.Model):

     text=models.CharField(max_length=100)

class Two(models.Model):

     test = models.Integer()
     many = models.ManyToManyField(One, blank=True)

When I try save my object in admin panel, I take error such as:

“‘Two’ instance needs to have a primary key value before a many-to-many relationship can be used.”

I use django 1.3. I tried add AutoField to Two class, but it’s not work too.

This is my code.

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from project.foo.forms import FooForm
from project.foo.models import Foo
from project.fooTwo.views import fooTwoView

def foo(request, template_name="foo_form.html"):
    if request.method == 'POST':
        form = FooForm(data=request.POST)
        if form.is_valid():
            foo = Foo()
            foo.name = request.POST.get("name")
            foo.count_people = request.POST.get("count_people")
            foo.date_time = request.POST.get("date_time")
            foo.save()
            return fooTwoView(request)
    else:
        form = FooForm()

    return render_to_response(template_name, RequestContext(request, {
        "form": form,
    }))

P.S. I find my fail. It is in model. I used many-to-many in save method. I add checking before using, but it’s not help.

class Foo(models.Model):
    name = models.CharField(max_length=100, null=False, blank=False)
    count_people = models.PositiveSmallIntegerField()
    menu = models.ManyToManyField(Product, blank=True, null=True)
    count_people = models.Integer()
    full_cost = models.IntegerField(blank=True)

    def save(self, *args, **kwargs):
        if(hasattr(self,'menu')):
            self.full_cost = self.calculate_full_cost()
        super(Foo, self).save(*args, **kwargs)

    def calculate_full_cost(self):
        cost_from_products = sum([product.price for product in self.menu.all()])
        percent = cost_from_products * 0.1
        return cost_from_products + percent

I try hack in save method such as

if(hasattr(self,Two)):
        self.full_cost = self.calculate_full_cost()

This is help me, but i dont think that is the django way. What is interesting, that is without this checking admin panel show error, but create object. Now, if i select item from Two and save, my object does not have full_cost, but when i view my object, admin panel remember my choice and show me my Two item, what i select… I dont know why.

How do i save this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T16:50:05+00:00Added an answer on June 6, 2026 at 4:50 pm

    There are quite a few problems with your code. The most obvious one are

    1/ in your view, using a form for user inputs validation/sanitization/conversion then ignoring the santized/converted data and getting unsanitized inputs directly from the request. Use form.cleaned_data instead of request.POST to get your data, or even better use a ModelForm which will take care of creating a fully populated Foo instance for you.

    2/ there’s NO implicit “this” (or “self” or whatever) pointer in Python methods, you have to explicitely use “self” to get at the instance attributes. Here’s what your model’s “save” method really do:

       def save(self, *args, **kwargs):
           # test the truth value of the builtin "id" function
           if(id):  
               # create a local variable "full_cost" 
               full_cost = self.calculate_full_cost()
           # call on super with a wrong base class
           super(Banquet, self).save(*args, **kwargs)
           # and exit, discarding the value of "full_cost"
    

    Now with regard to your question: Foo.save is obviously not the right place to compute someting based on m2m related objects. Either write a distinct method that run the computation AND update Foo AND save it and call it after the m2m are saved (hint : a ModelForm will take care of saveing the m2m related objects for you), or just use the m2m_changed signal.

    This being said, I strongly suggest you spend a few hours learning Python and Django – it will save you a lot of time.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

class Person(models.Model): name = models.CharField(max_length=100) class Entry(models.Model): text = models.CharField(max_length=100) person = models.ManyToManyField(Person, blank=True,
I have this models: class Comment(models.Model): text = models.TextField(max_length = 300) author = models.ForeignKey(User)
I have a few model classes with basic one-to-many relationships. For example, a book
From code how can we know which interfaces one class implements? Example: interface IDrink
Could you provide an example of how one would represent a player class with
Can I have more than one XmlElement on property of a class? For example:
I am currently learning objective-c from a book. In one example, before the class
This example is from the Django documentation . Given the (Django) database model: class
Is it possible to create one model that stands for two different objects? for
I want to enable something like a one-to-many relation between a text object and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.