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

  • Home
  • SEARCH
  • 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 4347198
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T12:16:26+00:00 2026-05-21T12:16:26+00:00

What I would like to do is to display a single form that lets

  • 0

What I would like to do is to display a single form that lets the user:

  • Enter a document title (from Document model)
  • Select one of their user_defined_code choices from a drop down list (populated by the UserDefinedCode model)
  • Type in a unique_code (stored in the Code model)

I’m not sure how to go about displaying the fields for the foreign key relationships in a form. I know in a view you can use document.code_set (for example) to access the related objects for the current document object, but I’m not sure how to apply this to a ModelForm.

My model:

class UserDefinedCode(models.Model):
    name = models.CharField(max_length=8)
    owner = models.ForeignKey(User)

class Code(models.Model):
    user_defined_code = models.ForeignKey(UserDefinedCode)
    unique_code = models.CharField(max_length=15)

class Document(models.Model):
    title = models.CharField(blank=True, null=True, max_length=200)
    code = models.ForeignKey(Code)
    active = models.BooleanField(default=True)

My ModelForm

class DocumentForm(ModelForm):
    class Meta:
        model = Document
  • 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-05-21T12:16:27+00:00Added an answer on May 21, 2026 at 12:16 pm

    In regards to displaying a foreign key field in a form you can use the forms.ModelChoiceField and pass it a queryset.

    so, forms.py:

    class DocumentForm(forms.ModelForm):
        class Meta:
            model = Document
    
        def __init__(self, *args, **kwargs):
            user = kwargs.pop('user','')
            super(DocumentForm, self).__init__(*args, **kwargs)
            self.fields['user_defined_code']=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user))
    

    views.py:

    def someview(request):
        if request.method=='post':
            form=DocumentForm(request.POST, user=request.user)
            if form.is_valid():
                selected_user_defined_code = form.cleaned_data.get('user_defined_code')
                #do stuff here
        else:
            form=DocumentForm(user=request.user)
    
        context = { 'form':form, }
    
        return render_to_response('sometemplate.html', context, 
            context_instance=RequestContext(request))
    

    from your question:

    I know in a view you can use
    document.code_set (for example) to
    access the related objects for the
    current document object, but I’m not
    sure how to apply this to a ModelForm.

    Actually, your Document objects wouldn’t have a .code_set since the FK relationship is defined in your documents model. It is defining a many to one relationship to Code, which means there can be many Document objects per Code object, not the other way around. Your Code objects would have a .document_set. What you can do from the document object is access which Code it is related to using document.code.

    edit: I think this will do what you are looking for. (untested)

    forms.py:

    class DocumentForm(forms.ModelForm):
        class Meta:
            model = Document
            exclude = ('code',)
    
        def __init__(self, *args, **kwargs):
            user = kwargs.pop('user','')
            super(DocumentForm, self).__init__(*args, **kwargs)
            self.fields['user_defined_code']=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user))
            self.fields['unique_code']=forms.CharField(max_length=15)
    

    views.py:

    def someview(request):
        if request.method=='post':
            form=DocumentForm(request.POST, user=request.user)
            if form.is_valid():
                uniquecode = form.cleaned_data.get('unique_code')
                user_defined_code = form.cleaned_data.get('user_defined_code')
                doc_code = Code(user_defined_code=user_defined_code, code=uniquecode)
                doc_code.save()
                doc = form.save(commit=False)
                doc.code = doc_code
                doc.save()
                return HttpResponse('success')
        else:
            form=DocumentForm(user=request.user)
    
        context = { 'form':form, }
    
        return render_to_response('sometemplate.html', context, 
            context_instance=RequestContext(request))
    

    actually you probably want to use get_or_create when creating your Code object instead of this.

    doc_code = Code(user_defined_code=user_defined_code, code=uniquecode)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like display something more meaningful that animated gif while users upload file
I would like to display details of an xml error log to a user
I would like to display certain meta data fields in the edit form based
I would like to display an animated gif on a .NET Compact Form .
I would like to validate both single field and multiple field data from a
I would like to display some memory statistics (working set, GCs etc.) on a
I would like to display multiple colors (and potentially shapes and sizes) of data
I would like to display some smiley's inbetween text in my chatbox but when
I would like to display the up time of the machine my code is
I would like to display the differences between versions of the same content. Initially

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.