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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T03:47:39+00:00 2026-06-13T03:47:39+00:00

I got a form as following: class CourseAddForm(forms.ModelForm): Add a new course name =

  • 0

I got a form as following:

class CourseAddForm(forms.ModelForm):
  """Add a new course"""
  name = forms.CharField(label=_("Course Name"), max_length=100)
  description = forms.Textarea()
  course_no = forms.CharField(label=_("course Number"), max_length=15)


  #Attach a form helper to this class
  helper = FormHelper()
  helper.form_id = "addcourse"
  helper.form_class = "course"

  #Add in a submit and reset button
  submit = Submit("Add", "Add New Record")
  helper.add_input(submit)
  reset = Reset("Reset", "Reset")
  helper.add_input(reset)

def clean(self):
  """ 
  Override the default clean method to check whether this course has been already inputted.
  """    
  cleaned_data = self.cleaned_data
  name = cleaned_data.get('name')
  hic = cleaned_data.get('course_no')

  try:
    course=Course.objects.get(name=name)
  except Course.DoesNotExist:
    course=None

  if course:
    msg = u"Course name: %s has already exist." % name
    self._errors['name'] = self.error_class([msg])
    del cleaned_data['name']
    return cleaned_data
  else:
    return self.cleaned_data

  class Meta:
    model = Course

As you can see I overwrote the clean method to check whether this course has already existed in the database when the user is trying to add it. This works fine for me.

However, when I want to add the same check for the form for editing, the problem happened. Because it is editing, so the record with same course name has already exist in the DB. Thus, the same check would throw error the course name has already exist. But I need to check the duplication in order to avoid the user updating the course name to another already existed course name.

I am thinking of checking the value of the course name to see if it is changed. If it has been changed, than I can do the same check as above. If it has not been changed, I don’t need to do the check. But I don’t know how can I obtain the origin data for editing.

Does anyone know how to do this in Django?

My view looks as following:

@login_required
@csrf_protect
@never_cache
@custom_permission_required('records.change_course', 'course')
def edit_course(request,course_id):
  # See if the family exists:
try:
  course = Course.objects.get(id=course_id)
except Course.DoesNotExist:
  course = None

if course:
  if request.method == 'GET':
    form = CourseEditForm(instance=course)
    return render_to_response('records/add.html',
                            {'form': form},
                            context_instance=RequestContext(request)
                            )
  elif request.method == 'POST':
    form = CourseEditForm(request.POST, instance=course)
    if form.is_valid():
      form.save()
      return HttpResponseRedirect('/records/')
    # form is not valid: 
    else:
      error_message = "Please correct all values marked in red."
      return render_to_response('records/edit.html', 
                              {'form': form, 'error_message': error_message},
                              context_instance=RequestContext(request)
                              )      
else:
  error = "Course %s does not exist. Press the 'BACK' button on your browser." % (course)
  return HttpResponseRedirect(reverse('DigitalRecords.views.error', args=(error,)))

Thank you.

  • 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-13T03:47:41+00:00Added an answer on June 13, 2026 at 3:47 am

    I think you should just set unique=True on the Course.name field and let the framework handle that validation for you.

    Update:

    Since unique=True is not the right answer for your case, you can check this way:

    def clean(self):
        """ 
        Override the default clean method to check whether this course has
        been already inputted.
        """    
        cleaned_data = self.cleaned_data
        name = cleaned_data.get('name')
    
        matching_courses = Course.objects.filter(name=name)
        if self.instance:
            matching_courses = matching_courses.exclude(pk=self.instance.pk)
        if matching_courses.exists():
            msg = u"Course name: %s has already exist." % name
            raise ValidationError(msg)
        else:
            return self.cleaned_data
    
    class Meta:
        model = Course
    

    As a side note, I’ve also changed your custom error handling to use a more standard ValidationError.

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

Sidebar

Related Questions

My form field looks something like the following: class FooForm(ModelForm): somefield = models.CharField( widget=forms.TextInput(attrs={'readonly':'readonly'})
I've got the following code for a search form, but how would I add
I have models similar to the following: class Band(models.Model): name = models.CharField(unique=True) class Event(models.Model):
I've got the following routes: // Submission/* routes.MapRoute( Submission, Submission/{form}, new { controller =
I have the following code: class UserForm(ModelForm): email = forms.EmailField(widget = forms.TextInput(attrs ={ 'id':'email'}),
I got the following Model: public class ViewBloqueioNotaFiscal { public ViewComboStatus ComboStatus = new
I've got the following JSF form: <h:form> <ui:repeat value=#{list.categories} var=cat> <h:selectOneRadio id=sel1Rad value=#{list.choose} layout=pageDirection>
I have got a the following problem: I have got multi-step form where in
I've got a complex form with rather a lot of css on the following
I've got the following bit of code to check if a form with multiple

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.