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 8469283
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T16:11:02+00:00 2026-06-10T16:11:02+00:00

I have 2 models which are related to each other using One to One

  • 0

I have 2 models which are related to each other using One to One Relation. How can i display the validation error if object of one model is already related to another.

Suppose i have 2 models

   Class Place(models.Model):
        field1 = CharField()
        field2 = CharField()

   Class Restaurant(models.Model):
       related_field = OneToOneField(Place)
       field3 = CharField()

In my case For one place one Restaurant. If user submits new Restaurant for the same place, then a validation should raise

If Restaurant object already attached to Place object, so for second Restaurant for same Place object i want to display validation

In admin we usually see this message “Restaurent with this Place already exists.” But how can i achieve the same this using modelform with generic views

 class RestaurantCreateView(CreateView):
       form_class = RestaurantForm
       template_name = 'restaurant_create.html'

       def get_success_url(self):
           return reverse_lazy('restuarants', args=[self.object.id])

       def get_place(self, **kwargs):
           id = self.kwargs['pk']
           place = Place.objects.get(id=id)
           return place 

       def get_context_data(self, **kwargs):
           context = super(RestaurantCreateView, self).get_context_data(**kwargs)
           place = self.get_place()
           context['place'] = place
           return context

       def form_valid(self, form):
          self.object = form.save(commit=False)
          place = self.get_place()
          self.object.place = place
          self.object.save()
          return HttpResponseRedirect(self.get_success_url())

How can perform One To One relation validation in class based generic views?

  • 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-10T16:11:03+00:00Added an answer on June 10, 2026 at 4:11 pm

    Then you need to pass the Place object into your Restaurant form. The form validation has no access to these things defined in the view unless you explicitly pass it that data.

    class MyForm(forms.ModelForm):
        class Meta:
             model = Restaurant
    
        def __init__(self, *args, **kwargs):
            self.place = kwargs.pop('place', None)
            super(MyForm, self).__init__(*args, **kwargs
    
        def clean_related_field(self):
            place = self.place
            try:
                place.restaurant
            except Restaurant.DoesNotExist:
                return place
            raise forms.ValidationError("Restaurant already exists for that book")
    
    
    class MyView(...):
        form_class = MyForm
    
        def get_form_kwargs(self):
            kwargs = super(MyView, self).get_form_kwargs()
            kwargs['place'] = Place.objects.get(id=self.kwargs['pk'])
            return kwargs
    
    {% if form.related_field.errors %}.........{% endif %}
    

    Another approach is to fake validation in form_valid() and set the errors dict, and return the response. This method may be preferable since it’s much more contained. Also especially if you are not using the form field anyways, you might as well add an error flag to the context.

    class MyView():
        def form_valid(self, form):
            if Restaurant.objects.filter(related_field=self.get_place()):
                ctx = self.get_context_data(form=form)
                ctx['massive_error'] = True
                return self.render_to_response(ctx)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two models which are related to each other: /** @Entity @Table(name=permissions) */
I have 2 models, say Model A and Model B, each one having certain
I have a few data models (tables) which are associated with each other. If
Let's say that I have 4 models which are related in the following ways:
I have a class which models all categories and they can be ordered hierarchically.
I have 2 models: User and Book and a join model ownership which connect
When two models are related to each other, Doctrine automatically generates foreign key constraints
I have models User and Message. Every user can send messages to other users.
I have users. Users can poke other users, as well as poke themselves. Each
I have 2 models which are connected via a HABTM association, in the same

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.