Django modelform submission with relational dataDoes Django scale?django - inlineformset_factory with more than one ForeignKeyCan't add field to ModelForm at __init__Radio buttons in django adminfilter json data from Django modelDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fieldrelated name in parent model in django if inherited in other modelHow to check if Django Signal works?

Are double contractions formal? Eg: "couldn't've" for "could not have"

Which spells are in some way related to shadows or the Shadowfell?

Is there an application which does HTTP PUT?

Has there been evidence of any other gods?

Is it a good idea to copy a trader when investing?

Do Rabbis admit emotional involvement in their rulings?

How to find the transfer orbit from a initial circular orbit to a final elliptical orbit

Was Mohammed the most popular first name for boys born in Berlin in 2018?

What's an appropriate age to involve kids in life changing decisions?

Narcissistic cube asks who are we?

Are there vaccine ingredients which may not be disclosed ("hidden", "trade secret", or similar)?

Why is it wrong to *implement* myself a known, published, widely believed to be secure crypto algorithm?

Ugin's Conjurant vs. un-preventable damage

Was there a contingency plan in place if Little Boy failed to detonate?

Is it a Munchausen Number?

What is the Ancient One's mistake?

Using wilcox.test() and t.test() in R yielding different p-values

And now you see it II (the B side)

What is the status of the three crises in the history of mathematics?

What replaces x86 intrinsics for C when Apple ditches Intel CPUs for their own chips?

Rusty Chain and back cassette – Replace or Repair?

Can I use a 11-23 11-speed shimano cassette with the RD-R8000 11-speed Ultegra Shadow Rear Derailleur (short cage)?

Is it safe to keep the GPU on 100% utilization for a very long time?

Renting a house to a graduate student in my department



Django modelform submission with relational data


Does Django scale?django - inlineformset_factory with more than one ForeignKeyCan't add field to ModelForm at __init__Radio buttons in django adminfilter json data from Django modelDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fieldrelated name in parent model in django if inherited in other modelHow to check if Django Signal works?






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








0















I have a django modelform that creates a new listing in my post app, I would like to associate this with a company id, which is an account type in my account app.



The account_company db table (postgresql) has a user_id field which is the pk of User. the post_listing table will have a company field which I think should be the pk of account_company.



As I am attempting to use modelforms for all forms, I am having an issue with making this association.



# models.py

class Listing(models.Model):
title = models.CharField(max_length=200)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
...


# forms.py

class newListingForm(forms.ModelForm):

class Meta:
model = Listing
fields = ('title'...)

def __init__(self, user, *args, **kwargs):
super(newListingForm, self).__init__(*args, **kwargs)
self.fields['company'].queryset = Company.objects.filter(pk__user_id=user.id)
# above i am trying to filter the AutoField to the `company pk` where `user_id` is equal to `request.user.id`


# views.py

def post(request):

if request.method == 'POST':
form = newListingForm(request.user, request.POST)
if form.is_valid():
listing = form.save(commit=False)
listing.user = request.user
listing.save()
else:
form = newListingForm(request.user)
return render(request, 'post/post.html', 'form': form)


The debug error i get is:



Unsupported lookup 'user_id' for AutoField or join on the field not permitted.



Updated



#accounts model.py

...
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
photo = models.ImageField(upload_to='images/%Y/%m/%d/', null=True)
description = models.TextField(null=True)









share|improve this question



















  • 1





    change Company.objects.filter(pk__user_id=user.id) to Company.objects.filter(user_id=user.id) is still throws same error?

    – shotgunner
    Mar 23 at 9:13












  • Can you also include your Company model for completeness?

    – Mekicha
    Mar 23 at 9:15











  • @shotgunner with that change it gives just company as an error, however the company field is defined in the model..

    – nghs
    Mar 23 at 9:18











  • @Mekicha added the accounts model.py with the Company model, here the OneToOneField says user, however in the db it is stored as user_id

    – nghs
    Mar 23 at 9:20







  • 1





    But show that error. Also show the bits of the form you've snipped. Is companyactually in the fields list?

    – Daniel Roseman
    Mar 23 at 9:48


















0















I have a django modelform that creates a new listing in my post app, I would like to associate this with a company id, which is an account type in my account app.



The account_company db table (postgresql) has a user_id field which is the pk of User. the post_listing table will have a company field which I think should be the pk of account_company.



As I am attempting to use modelforms for all forms, I am having an issue with making this association.



# models.py

class Listing(models.Model):
title = models.CharField(max_length=200)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
...


# forms.py

class newListingForm(forms.ModelForm):

class Meta:
model = Listing
fields = ('title'...)

def __init__(self, user, *args, **kwargs):
super(newListingForm, self).__init__(*args, **kwargs)
self.fields['company'].queryset = Company.objects.filter(pk__user_id=user.id)
# above i am trying to filter the AutoField to the `company pk` where `user_id` is equal to `request.user.id`


# views.py

def post(request):

if request.method == 'POST':
form = newListingForm(request.user, request.POST)
if form.is_valid():
listing = form.save(commit=False)
listing.user = request.user
listing.save()
else:
form = newListingForm(request.user)
return render(request, 'post/post.html', 'form': form)


The debug error i get is:



Unsupported lookup 'user_id' for AutoField or join on the field not permitted.



Updated



#accounts model.py

...
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
photo = models.ImageField(upload_to='images/%Y/%m/%d/', null=True)
description = models.TextField(null=True)









share|improve this question



















  • 1





    change Company.objects.filter(pk__user_id=user.id) to Company.objects.filter(user_id=user.id) is still throws same error?

    – shotgunner
    Mar 23 at 9:13












  • Can you also include your Company model for completeness?

    – Mekicha
    Mar 23 at 9:15











  • @shotgunner with that change it gives just company as an error, however the company field is defined in the model..

    – nghs
    Mar 23 at 9:18











  • @Mekicha added the accounts model.py with the Company model, here the OneToOneField says user, however in the db it is stored as user_id

    – nghs
    Mar 23 at 9:20







  • 1





    But show that error. Also show the bits of the form you've snipped. Is companyactually in the fields list?

    – Daniel Roseman
    Mar 23 at 9:48














0












0








0








I have a django modelform that creates a new listing in my post app, I would like to associate this with a company id, which is an account type in my account app.



The account_company db table (postgresql) has a user_id field which is the pk of User. the post_listing table will have a company field which I think should be the pk of account_company.



As I am attempting to use modelforms for all forms, I am having an issue with making this association.



# models.py

class Listing(models.Model):
title = models.CharField(max_length=200)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
...


# forms.py

class newListingForm(forms.ModelForm):

class Meta:
model = Listing
fields = ('title'...)

def __init__(self, user, *args, **kwargs):
super(newListingForm, self).__init__(*args, **kwargs)
self.fields['company'].queryset = Company.objects.filter(pk__user_id=user.id)
# above i am trying to filter the AutoField to the `company pk` where `user_id` is equal to `request.user.id`


# views.py

def post(request):

if request.method == 'POST':
form = newListingForm(request.user, request.POST)
if form.is_valid():
listing = form.save(commit=False)
listing.user = request.user
listing.save()
else:
form = newListingForm(request.user)
return render(request, 'post/post.html', 'form': form)


The debug error i get is:



Unsupported lookup 'user_id' for AutoField or join on the field not permitted.



Updated



#accounts model.py

...
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
photo = models.ImageField(upload_to='images/%Y/%m/%d/', null=True)
description = models.TextField(null=True)









share|improve this question
















I have a django modelform that creates a new listing in my post app, I would like to associate this with a company id, which is an account type in my account app.



The account_company db table (postgresql) has a user_id field which is the pk of User. the post_listing table will have a company field which I think should be the pk of account_company.



As I am attempting to use modelforms for all forms, I am having an issue with making this association.



# models.py

class Listing(models.Model):
title = models.CharField(max_length=200)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
...


# forms.py

class newListingForm(forms.ModelForm):

class Meta:
model = Listing
fields = ('title'...)

def __init__(self, user, *args, **kwargs):
super(newListingForm, self).__init__(*args, **kwargs)
self.fields['company'].queryset = Company.objects.filter(pk__user_id=user.id)
# above i am trying to filter the AutoField to the `company pk` where `user_id` is equal to `request.user.id`


# views.py

def post(request):

if request.method == 'POST':
form = newListingForm(request.user, request.POST)
if form.is_valid():
listing = form.save(commit=False)
listing.user = request.user
listing.save()
else:
form = newListingForm(request.user)
return render(request, 'post/post.html', 'form': form)


The debug error i get is:



Unsupported lookup 'user_id' for AutoField or join on the field not permitted.



Updated



#accounts model.py

...
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
photo = models.ImageField(upload_to='images/%Y/%m/%d/', null=True)
description = models.TextField(null=True)






python django






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 9:20







nghs

















asked Mar 23 at 9:08









nghsnghs

6011




6011







  • 1





    change Company.objects.filter(pk__user_id=user.id) to Company.objects.filter(user_id=user.id) is still throws same error?

    – shotgunner
    Mar 23 at 9:13












  • Can you also include your Company model for completeness?

    – Mekicha
    Mar 23 at 9:15











  • @shotgunner with that change it gives just company as an error, however the company field is defined in the model..

    – nghs
    Mar 23 at 9:18











  • @Mekicha added the accounts model.py with the Company model, here the OneToOneField says user, however in the db it is stored as user_id

    – nghs
    Mar 23 at 9:20







  • 1





    But show that error. Also show the bits of the form you've snipped. Is companyactually in the fields list?

    – Daniel Roseman
    Mar 23 at 9:48













  • 1





    change Company.objects.filter(pk__user_id=user.id) to Company.objects.filter(user_id=user.id) is still throws same error?

    – shotgunner
    Mar 23 at 9:13












  • Can you also include your Company model for completeness?

    – Mekicha
    Mar 23 at 9:15











  • @shotgunner with that change it gives just company as an error, however the company field is defined in the model..

    – nghs
    Mar 23 at 9:18











  • @Mekicha added the accounts model.py with the Company model, here the OneToOneField says user, however in the db it is stored as user_id

    – nghs
    Mar 23 at 9:20







  • 1





    But show that error. Also show the bits of the form you've snipped. Is companyactually in the fields list?

    – Daniel Roseman
    Mar 23 at 9:48








1




1





change Company.objects.filter(pk__user_id=user.id) to Company.objects.filter(user_id=user.id) is still throws same error?

– shotgunner
Mar 23 at 9:13






change Company.objects.filter(pk__user_id=user.id) to Company.objects.filter(user_id=user.id) is still throws same error?

– shotgunner
Mar 23 at 9:13














Can you also include your Company model for completeness?

– Mekicha
Mar 23 at 9:15





Can you also include your Company model for completeness?

– Mekicha
Mar 23 at 9:15













@shotgunner with that change it gives just company as an error, however the company field is defined in the model..

– nghs
Mar 23 at 9:18





@shotgunner with that change it gives just company as an error, however the company field is defined in the model..

– nghs
Mar 23 at 9:18













@Mekicha added the accounts model.py with the Company model, here the OneToOneField says user, however in the db it is stored as user_id

– nghs
Mar 23 at 9:20






@Mekicha added the accounts model.py with the Company model, here the OneToOneField says user, however in the db it is stored as user_id

– nghs
Mar 23 at 9:20





1




1





But show that error. Also show the bits of the form you've snipped. Is companyactually in the fields list?

– Daniel Roseman
Mar 23 at 9:48






But show that error. Also show the bits of the form you've snipped. Is companyactually in the fields list?

– Daniel Roseman
Mar 23 at 9:48













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%2f55312208%2fdjango-modelform-submission-with-relational-data%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%2f55312208%2fdjango-modelform-submission-with-relational-data%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

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript