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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T04:53:18+00:00 2026-06-03T04:53:18+00:00

Model: class ProjectType(models.Model): project_type_id = models.AutoField(primary_key=True) name = models.CharField(max_length=45, help_text=’Type of project’, verbose_name=’Project Type’)

  • 0

Model:

class ProjectType(models.Model):
    project_type_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=45, help_text='Type of project', verbose_name='Project Type')
    slug = models.SlugField(max_length=45, blank=True)
    description = models.CharField(max_length=400, help_text='Description of the main  purpose of the project', verbose_name='Project Type Description')
    default = models.BooleanField(default=False)
    owner = models.ForeignKey(User)
class Meta:
    ...
    unique_together = (('slug', 'owner'),('name', 'owner'))

I need a form to create/update ProjectType’s. Please note the owner field – it is supposed to be current logged-in user. The question is how to ensure that constraints in the unique_together are validated correctly.

I do not want to show owner field on the form – it’s the current user, so it should be set automatically by the system. But no matter how I try to do this, either validation does not work, or there are other errors.

Among approaches I tried (individually or in combination):

  • Creating a hidden field in the related ModelField
  • Defining init in ProjectTypeForm (in various ways), for example:

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(ProjectTypeForm, self).__init__(*args, **kwargs)
        self.fields['owner'].initial = self.user
    
  • Setting values in the view like:

    ...
    if request.method == 'POST':
        project_type = ProjectType(owner=request.user)
        form = ProjectTypeForm(request.POST, instance=project_type, user = request.user.pk) # also tries w/o pk
    ...
    
  • Overriding clean() method of the form in various ways, along these lines:

    def clean(self):
        cleaned_data = super(ProjectTypeForm, self).clean()
        slug=cleaned_data.get('slug')
        owner = cleaned_data.get('owner')
    
        if slug:
            user = User.objects.get(pk=owner)
            ...
    

Many of these approaches are based on various answers found on stackoverflow.com. However, no matter what I try, I cannot find a way to accomplish what I need: (1) auto-setting of the owner field and (2) validation for uniqueness: owner/type_name and owner/type_slug. Typical errors I have is that (a) owner is not recognized as a User (it’s treated as a PK), (b) incorrect validation (like lack of it or it misses the fact that it’s the same record being edited, etc.), (c) owner is a required field.

For the record – if the owner is a regular field in the form, everything works as expected, but I cannot allow users to set the owner value.

Is there any, hopefully elegant, solution to this?

Thanks!

  • 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-03T04:53:20+00:00Added an answer on June 3, 2026 at 4:53 am

    Exclude the owner field from your form, and save the user in your form’s init method – then you can use it to validate the form, eg

    class ProjectTypeForm(...):
        ...
        def __init__(self, user, *args, **kwargs):
            super(ProjectTypeForm, self).__init__(*args, **kwargs)
            self.user = user
    
        def clean(self):
            user_projects = ProjectType.objects.filter(owner=self.user)
            if user_projects.filter(slug=self.cleaned_data['slug']):
                raise forms.ValidationError('...')
            elif user_projects.filter(name=self.cleaned_data['name']):
                raise forms.ValidationError('...')
            else:
                return self.cleaned_data
    

    Then in your view, do something like this when creating a new ProjectType:

    if request.method == 'POST':
        form = ProjectTypeForm(request.user, request.POST)
        if form.is_valid():
            ptype = form.save(commit=False)
            ptype.owner = request.user
            ptype.save()
    

    You shouldn’t need that to save existing ProjectType objects though.

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

Sidebar

Related Questions

Here is my model: class Company(models.Model): id = models.AutoField(primary_key=True); name = models.CharField(max_length=100); address =
Suppose I have a model: class SomeModel(models.Model): id = models.AutoField(primary_key=True) a = models.CharField(max_length=10) b
Model: class Subject(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) description = models.TextField(blank=True,null=True) Forms: class
If I have this model: class Person(models.Model): name=models.CharField(max_length=28) mother=models.ForeignKey(self,null=True,blank=True) I am trying to make
model: class Province(models.Model): user = models.ManyToManyField(User, blank=True) name = models.CharField(max_length=30, unique=True) class City(models.Model): name
#model class Promotion(models.Model): name = models.CharField(max_length=200) start_date = models.DateTimeField() end_date = models.DateTimeField() #view def
model: class Store(models.Model): name = models.CharField(max_length = 20) class Admin: pass def __unicode__(self): return
model: class Product(models.Model): name = models.CharField(max_length = 128) (...) def __unicode__(self): return self.name class
The model: class Product(models.Model): name = models.CharField(max_length = 128) def __unicode__(self): return self.name class
I have the following Model: class Group(models.Model): member = models.ManyToManyField(Player, through='GroupMember') name = models.CharField(max_length=20,

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.