I have a many to many field ConnectedTo in my model and I want to create the object using a form. However when I list it as a field I just get a listbox with options to highlight and no way of selecting one or more.
Ideally I'd love a multiple selection checkbox with a list of items in a scroll box. But I'd start with just having a selectable item.
Here's my code so far:
models.py:
class Part(models.Model):
PartID = models.AutoField(primary_key=True, unique=True)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE, null=True)
Comment = models.CharField(max_length=255, blank=True)
Subtype = models.ForeignKey('Subtype', on_delete=models.CASCADE, null=True)
Location = models.CharField(max_length=255, blank=True)
ConnectedTo= models.ManyToManyField('self', blank=True, null=True)
BatchNo = models.CharField(max_length=32, blank=False, null=True)
SerialNo = models.CharField(max_length=32,blank=True)
Manufacturer = models.CharField(max_length=32, blank=False, null=True)
Length = models.CharField(max_length=6, blank=True, null=True)
InspectionPeriod = models.IntegerField(blank=True, null=True)
LastInspected = models.DateField(blank=True, null=True)
InspectionDue = models.CharField(max_length=255, blank=True)
#classmethod
def create(cls, siteid, comment, subtype, location, batchno, serialno, manufacturer, length, inspectionperiod, lastinspected, inspectiondue):
part = cls(SiteID = siteid, Comment = comment, Subtype = subtype, Location = location, BatchNo = batchno, SerialNo = serialno, Manufacturer = manufacturer, Length = length, InspectionPeriod = inspectionperiod, LastInspected = lastinspected, InspectionDue = inspectiondue)
return part
def __str__(self):
return str(self.PartID)
forms.py:
class PartForm(forms.ModelForm):
class Meta:
model = Part
fields = ('Comment', 'Subtype', 'Location', 'ConnectedTo', 'BatchNo', 'SerialNo', 'Manufacturer', 'Length', 'InspectionPeriod', 'LastInspected')
views.py:
#login_required(login_url='/accounts/login/')
def addPartForm_Create(request, site, subtype):
siteselected = site
subtypeselected = Subtype.objects.get(SubtypeID = subtype)
if request.method == 'POST':
form = addPartForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.SiteID = Site.objects.get(SiteID = siteselected)
obj.Subtype = subtypeselected
obj.save()
return redirect('/sites/'+str(site))
else:
form = addPartForm()
return render(request, 'myproj/addPart.html', {'form': form, 'SiteNo': Site.objects.get(SiteID = siteselected).SiteID, 'subtype': subtypeselected})
EDIT: had the wrong view, sorry.
EDIT 2: example of what I mean by the highlighted box:
UPDATE:
Jey_Jen's answer has helped me get the style I want. I now have a multiple selection checkbox. But the ConnectedTo attributes do not save. Everything else in the model is saved and a new part is created. But no many to many links.
I would suggest looking into django form widgets. you can override the default widget to be a whatever you want. you can view them here.
heres a small example the django docs give:
class CommentForm(forms.Form):
name = forms.CharField()
url = forms.URLField()
comment = forms.CharField(widget=forms.Textarea)
Related
Im getting a NOT NULL constraint error in my code when trying to save my model form, even though the fields I have left empty are optional (have set blank=True, null=True) in models.py
Im very confused, what am I doing wrong?
The error is popping up when I leave the first optional field blank (description). Filling any of them manually before work.save() pushes the issue to the next field, and passes when all fields are filled.
EDIT: this also happens when trying to create a work instance from the admin dashboard.
models.py
class Work(models.Model):
## core fields
creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,
default=None)
created = models.DateTimeField()
modified = models.DateTimeField()
work_slug = models.SlugField(max_length=50) # slug -> TBD: find way to assign default value to slug = archival number.
archive = models.ForeignKey(Archive, on_delete=models.CASCADE)
# superfolder -> replaces category, series etc with dynamic hierarchical database
folder = models.ForeignKey(Folder, on_delete=models.CASCADE)
# basic metadata fields
name = models.CharField(max_length=50)
year = models.CharField(max_length=50)
medium = models.CharField(max_length=50)
description = models.CharField(max_length=1200, blank=True, null=True)
# optional metadata
authors = models.CharField(max_length=50, blank=True, null=True)
classification = models.CharField(max_length=50, blank=True, null=True)
location = models.CharField(max_length=50, blank=True, null=True)
link = models.URLField(max_length=50, blank=True, null=True)
record_creator = models.CharField(max_length=50, blank=True, null=True) # revisit ->
# custom descriptors
cd1_name = models.CharField(max_length=50, blank=True, null=True)
cd1_value = models.CharField(max_length=50, blank=True, null=True)
cd2_name = models.CharField(max_length=50, blank=True, null=True)
cd2_value = models.CharField(max_length=50, blank=True, null=True)
cd3_name = models.CharField(max_length=50, blank=True, null=True)
cd3_value = models.CharField(max_length=50, blank=True, null=True)
cd4_name = models.CharField(max_length=50, blank=True, null=True)
cd4_value = models.CharField(max_length=50, blank=True, null=True)
cd5_name = models.CharField(max_length=50, blank=True, null=True)
cd5_value = models.CharField(max_length=50, blank=True, null=True)
cd6_name = models.CharField(max_length=50, blank=True, null=True)
cd6_value = models.CharField(max_length=50, blank=True, null=True)
cd7_name = models.CharField(max_length=50, blank=True, null=True)
cd7_value = models.CharField(max_length=50, blank=True, null=True)
# Standardized Metadata
# Methods
def __str__(self):
return 'Work: {}'.format(self.name)
def save(self, *args, **kwargs):
''' On save, update timestamps '''
user = get_current_user()
if not self.id: # if the model is being created for the first time:
self.creator = user # assign the currently logged in user as the creator
self.created = timezone.now() # set the 'created' field to the current date and time
# self.slug = **archival id of work (automatically determined)**
self.modified = timezone.now() # set the modified field to the current date and time. This is reassigned everytime the model is updated.
return super(Work, self).save(*args, **kwargs)
forms.py
class WorkForm(ModelForm):
class Meta:
model = Work
fields = ['name', 'year', 'medium', 'description', 'authors', 'classification', 'location', 'link', 'record_creator', 'cd1_name', 'cd1_value', 'cd2_name', 'cd2_value', 'cd3_name', 'cd3_value', 'cd4_name', 'cd4_value', 'cd5_name', 'cd5_value', 'cd6_name', 'cd6_value', 'cd7_name', 'cd7_value']
views.py
def add_work(request, folder_pk):
'''
Add a work to the filesystem.
folder_pk: the primary key of the parent folder
Checks if the user is logged in and if the user is the creator of the folder. If so, the user is allowed to add a work to the folder. Otherwise, the user is redirected to the login page.
'''
# add work to the database
parent = Folder.objects.get(pk=folder_pk)
mediaFormSet = modelformset_factory(MediaFile, fields=('name', 'alt_text', 'caption', 'media'), extra=1)
if request.method == "POST" and parent.archive.creator == get_current_user():
# if the form has been submitted
# Serve the form -> request.POST
form = WorkForm(request.POST)
# mediaFormSet = mediaFormSet(request.POST)
if form.is_valid(): # if the all the fields on the form pass validation
# Generate archival ID for work
# archival ID is random, unique 6 digit number that identifies the work
archival_id = get_archival_id()
# create a new work with the parameters retrieved from the form. currently logged in user is automatically linked
work = form.save(commit=False)
work.work_slug = archival_id
work.folder=parent
work.archive=parent.archive
work.save()
# Redirect to dashboard page
return redirect('add_media_to_work', work_pk=work.pk)
else:
# If the form is not submitted (page is loaded for example)
# -> Serve the empty form
form = WorkForm()
return render(request, "archival/add_edit_work.html", {"workForm": form})
i was facing the same problem as you, i made a sign up form, and it was giving me the same error because the .save() method was getting executed before i fill in the fields, there was no data to save, because of that: the fields type was None. so i just implemented an if else statement to make sure that the .save() method won't be executed if the type of the field isnNone,
here is a snippet:
if field == None:
pass
else:
form.save()
My site simply works like this: every Manager can have some SubManagers, those SubManagers can have some Agents (so the Agents are indirectly related to the Manager, see models.py to understand better the relations between them). I want to show in the Manager's profile page (see views.py) all the MembershipCard created by his/her related Agents. I'm trying to implement a filter to search, for example, cards created by a specific Agent, i'm able to do this but i would like to show in the dropdown only the Agents related to the Manager, the dropdown list now shows all Agents in the database
models.py
class StandardProfile(models.Model):
name = models.CharField(max_length=200, null=True)
surname = models.CharField(max_length=200, null=True)
phone_number = models.CharField(max_length=200, null=True)
class Meta:
abstract = True
class Manager(StandardProfile):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
class SubManager(StandardProfile):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
manager = models.ForeignKey(Capo, null=True, on_delete = models.SET_NULL)
class Agent(StandardProfile):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
manager = models.ForeignKey(Manager, null=True, on_delete = models.SET_NULL)
subManager = models.ForeignKey(SubManager, null=True, blank=True, on_delete = models.SET_NULL)
class MembershipCard(models.Model):
agent = models.ForeignKey(Agent, null=True,blank=True, on_delete = models.SET_NULL)
client = models.ForeignKey(Client, null=True,blank=True, on_delete = models.SET_NULL)
creation_date = models.DateTimeField(auto_now_add=True, null=True)
activation_date = models.DateTimeField(null=True,blank=True)
expiration_date = models.DateTimeField(null=True,blank=True)
views.py
#login_required(login_url='login')
def profilePage(request, pk): #www.mysite.com/profilePage/<pk>
user = User.objects.get(id=pk) #getting the user from <pk>
cards = MembershipCard.objects.filter(agent__manager=user.manager)
myFilter = MembershipCardFilter(request.GET,queryset=cards,user=user)
cards = myFilter.qs
#page_obj is used for Pagination, and contains the cards, i removed this part of code for better readability, can add it if needed
context = {'page_obj': page_obj,"user": user,"myFilter":myFilter}
return render(request, 'polls/profilePage.html',context)
filters.py
class MembershipCardFilter(django_filters.FilterSet):
class Meta:
model = MembershipCard
fields = ['agent','agent__subManager']
exclude = ['creation_date']
By reading answers to similar questions i think i have to modify the __init__ method in the CardFilter class, i've tried to adapt some answers to my case but it didn't work for some reasons . Any anser/comment is appreciated!
PS: I don't know if the title is clear, feel free to suggest a better one
You can try feeding the agent dropdown during init like (not tested!):
class MembershipCardFilter(django_filters.FilterSet):
agent= django_filters.ModelChoiceFilter(
queryset=Agent.objects.none(),
)
class Meta:
model = MembershipCard
fields = ['agent','agent__subManager']
exclude = ['creation_date']
def __init__(self, *args, **kwargs):
user = kwargs.get("user")
agents = Agent.objects.filter(manager__user=user)
super().__init__(*args, **kwargs)
self.filters["agent"].queryset = agents
I am making a CV page,
I want to link my Skill, Language etc class(table) to Main Person table/class,
But for that, I need to submit skill table first because my person table contains the foreign key for skills.
But as per CV form name & personal info comes first.
Also, I can put the whole form on one page but I want to go to the next page for each sub information, so is it possible to pass the request data from one class-based view to another class-based view.
models.py
from django.db import models
from django.core.validators import MinLengthValidator
from django.conf import settings
import datetime
class Workexperience(models.Model):
work = models.CharField(null=True, blank=True,
max_length=256,
help_text='eg: Juniorengineer: at L&T ')
person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=True, null=False, default=1 )
def __str__(self):
return self.work
class Education(models.Model):
school = models.CharField(max_length=200)
college = models.CharField(null=True, blank=True,max_length=200)
person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=True, null=False, default=1 )
def __str__(self):
return self.school
class Skills(models.Model):
skill = models.CharField(
max_length=256,
help_text='Add skills sperated by commas eg: programming, Matlab')
person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=True, null=False, default=1 )
def __str__(self):
return self.skill
class Languages(models.Model):
language = models.CharField(
max_length=256,
help_text='Add language sperated by commas eg: English, Gujarati')
person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=True, null=False, default=1 )
def __str__(self):
return self.language
class Person(models.Model):
name = models.CharField(
max_length=100,
help_text='Enter a name (e.g. Harry Virani)',
validators=[MinLengthValidator(2, "It must be greater than 1 character")]
)
picture = models.BinaryField(null=True, blank=True, editable=True)
content_type = models.CharField(max_length=256, null=True, blank=True,
help_text='The MIMEType of the file')
profession = models.CharField(
max_length=100,
validators=[MinLengthValidator(2, "It must be greater than 1 character")]
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default='')
address = models.CharField(max_length=256)
email = models.EmailField(max_length = 254)
phone = models.CharField(
max_length=15,
help_text='Enter a phone number like this (e.g. +91000000000)',
validators=[MinLengthValidator(10, "It must be greater than 10 character")] )
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
facebook = models.URLField(null=True, blank=True, max_length=200,
help_text='enter your facebook URL' )
instagram = models.URLField(null=True, blank=True, max_length=200,
help_text='enter your instagram link URL' )
linkedin = models.URLField(null=True, blank=True, max_length=200,
help_text='enter your Linked link URL' )
skill = models.ManyToManyField(Skills, related_name='skills', default=1)
language = models.ManyToManyField(Languages, related_name='languages', default=1)
edu = models.ManyToManyField(Education, default=1,related_name='edu' )
work = models.ManyToManyField(Workexperience,default=1, blank=True, related_name='works')
# Shows up in the admin list
def __str__(self):
return self.name
views.py
I want to save it in another class which is for creating skill & other models.
class PersonCreateView(LoginRequiredMixin, View):
template_name = 'MYP/form.html'
success_url = 'MYP:myp_create_info'
def get(self, request, pk=None):
personform = PersonForm()
ctx = { 'personform': personform}
return render(request, self.template_name, ctx)
def post(self, request, pk=None) :
# if 'personform' in request.POST:
personform = PersonForm(request.POST, request.FILES or None)
if not personform.is_valid():
ctx = {'personform': personform}
return render(request, self.template_name, ctx)
pform = personform.save(commit=False)
#adding onwer
pform.owner = self.request.user
pform.save()
return redirect(self.success_url, pform.id)
class InfoCreateView(LoginRequiredMixin, View):
template_name = 'MYP/form2.html'
success_url = reverse_lazy('MYP:all')
def get(self, request, pk):
person = get_object_or_404(Person,id=pk)
skill= SkillsForm()
skill_list = Skills.objects.filter(person=person)
ctx = { 'skill':skill, 'skill_list':skill_list }
return render(request, self.template_name, ctx)
def post(self, request, pk):
if 'skill' in request.POST:
skill = SkillsForm(request.POST or None)
if not skill.is_valid() :
ctx = { 'skill':skill}
return render(request, self.template_name, ctx)
person = get_object_or_404(Person,id=pk)
print(person)
skill = Skills(skill=request.POST['skill'], person=person)
skill.save()
print(skill.person)
return redirect('MYP:myp_create_info', pk=pk)
forms.py
class PersonForm(forms.ModelForm):
max_upload_limit = 2 * 1024 * 1024
max_upload_limit_text = naturalsize(max_upload_limit)
# Call this 'picture' so it gets copied from the form to the in-memory model
# It will not be the "bytes", it will be the "InMemoryUploadedFile"
# because we need to pull out things like content_type
picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text)
upload_field_name = 'picture'
# Hint: this will need to be changed for use in the ads application :)
class Meta:
model = Person
fields = ['name', 'profession', 'picture', 'address', 'email', 'phone','facebook','linkedin','instagram'] # Picture is manual
# Validate the size of the picture
def clean(self) :
cleaned_data = super().clean()
pic = cleaned_data.get('picture')
if pic is None : return
if len(pic) > self.max_upload_limit:
self.add_error('picture', "File must be < "+self.max_upload_limit_text+" bytes")
# Convert uploaded File object to a picture
def save(self, commit=True) :
instance = super(PersonForm, self).save(commit=False)
# We only need to adjust picture if it is a freshly uploaded file
f = instance.picture # Make a copy
if isinstance(f, InMemoryUploadedFile): # Extract data from the form to the model
bytearr = f.read();
instance.content_type = f.content_type
instance.picture = bytearr # Overwrite with the actual image data
if commit:
instance.save()
return instance
class WorkexperienceForm(forms.ModelForm):
class Meta:
model = Workexperience
fields = ['work']
class EducationForm(forms.ModelForm):
class Meta:
model = Education
fields = ['school','college']
class SkillsForm(forms.ModelForm):
class Meta:
model = Skills
fields = ['skill']
class LanguagesForm(forms.ModelForm):
class Meta:
model = Languages
fields = ['language']
Ignore the rest of the code it is just for image handling....
This is what I want to do but I know it is the wrong format
I want to just add id for everything later.
In my opinion, your models are messed up. Here is how I would have write them :
class WorkExperience(models.Model):
work = models.CharField(
blank=True,
max_length=256,
help_text='eg: Juniorengineer: at L&T'
)
def __str__(self):
return self.work
class Education(models.Model):
school = models.CharField(max_length=200)
college = models.CharField(blank=True, max_length=200)
def __str__(self):
return self.school
class Skill(models.Model):
name = models.CharField(
max_length=256,
help_text='Add a skill name (eg: Programming)'
)
def __str__(self):
return self.name
class Language(models.Model):
name = models.CharField(
max_length=256,
help_text='Add a language name (eg: Gujarati)'
)
def __str__(self):
return self.name
class Person(models.Model):
name = models.CharField(
max_length=100,
help_text='Enter a name (e.g. Harry Virani)',
validators=[MinLengthValidator(2, "It must be greater than 1 character")]
)
# [...Other fields...]
skills = models.ManyToManyField(Skill, related_name='persons', blank=True)
languages = models.ManyToManyField(Language, related_name='persons', blank=True)
educations = models.ManyToManyField(Education, related_name='persons', blank=True)
work_experiences = models.ManyToManyField(WorkExperience, related_name='persons', blank=True)
def __str__(self):
return self.name
Then I need to see your forms.py to better understand how you handle it in your view.
This form is updated by a generic view:
models.py:
class CustomUser(User):
user_bio = models.TextField(blank=True, null=True)
birth_date = models.DateField(null=True, blank=True)
def __str__(self):
return self.username
class SafeTransaction(models.Model):
trans_recipient = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'trans_Recipient',null = True)
trans_recipient_email = models.CharField(max_length = 1000, blank=True, null=True)
trans_sender = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'safe_Transactions', null = True)
date = models.DateTimeField(auto_now_add=True, blank=True)
subject = models.CharField(max_length = 1000, blank = True)
#trans_type = models.CharField(choices=(1,'Buildingwork'))#DROPDOWN BOX
trans_unread = models.BooleanField(default = True)
arbitrator_name = models.CharField(max_length=1000,blank=True, null=True)
payment_condition = models.TextField(blank=True, null=True)
amount_to_pay = models.DecimalField(blank=True, null=True, max_digits=50, decimal_places=2)
is_finalised = models.BooleanField(default=False)
views.py:
class SafeTransUpdateView(UpdateView):
'''
This view lets the user Update a SafeTransaction receipt
'''
form_class = SafeTransactionForm
model = SafeTransaction
template_name = "myInbox/safeTrans_update.html"
forms.py :
class SafeTransactionForm(forms.ModelForm):
''' SafeTranSactionForm '''
#version one of trans recipient
trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput())
#version two of trans_recipient
#trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))
def clean_trans_recipient(self):
data = self.cleaned_data['trans_recipient']
try:
return CustomUser.objects.get(username=data)
except CustomUser.DoesNotExist:
raise forms.ValidationError("No user with this username exists")
class Meta:
model = SafeTransaction
fields = [ 'trans_recipient',
'trans_recipient_email',
'subject',
'arbitrator_name',
'payment_condition',
'amount_to_pay']
So in the forms, I'm mainly trying to inherit a TextInput widget from a ChoiceField. Upon actually submiting the form with this version :
trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput()) I am told that the choice I typed in is invalid.
As for the second version : trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'})), upon submitting this form, first an error of :
invalid literal for int() with base 10: 'inbox'
After which, the item is actually updated!
I have tried a few approaches, but stuck on these two because they seem the most viable. I don't think it would make sense to leave the trans_recipients as the default drop-down field which Django provides for the ForeignKey model attribute, as it would quickly become unweildy with a large userbase.
I would like to know a convenient way to search with a TextInput widget and query my database for the typed term, and in this case update an Item with the generic UpdateView class.
I created models called Interview, Users, Interview_interviewer like wise...
Interview_interviewer table has foreign keys from other models.
I just want to save data from both 2 tables to Interview_interviewer(Without django forms) table which is many to many table. So I just created the views and template for it. When button clicks it save the Interviewers to table along side with the interview. But when do it, It gave me and error called "User matching query does not exist".
/home/govinda/DMG/test3/myapp/views.py in hod_inter_interviewer_2
usr = User.objects.get(id=pid)
What should I do?
class Interview(models.Model):
Time = models.TimeField()
Date = models.DateField()
Venue = models.ForeignKey('Venue')
HOD = models.ForeignKey(User)
Vacancy = models.ForeignKey('Vacancy', on_delete=models.CASCADE)
Department = models.ForeignKey(Department, on_delete=models.CASCADE)
InterviewType = models.ForeignKey(InterviewType, on_delete=models.CASCADE)
Interviewer_Review = models.TextField(blank=True, null=True)
HOD_Review = models.TextField(blank=True, null=True)
HR_Review = models.TextField(blank=True, null=True)
NoOfPasses = models.PositiveIntegerField(blank=True, null=True)
NoOfFails = models.PositiveIntegerField(blank=True, null=True)
NoOfOnHolds = models.PositiveIntegerField(blank=True, null=True)
InterviewNo = models.IntegerField(blank=True, null=True)
Post = models.ForeignKey(Post, on_delete=models.CASCADE)
and
class Users(models.Model):
User = models.OneToOneField(User)
FullName = models.CharField(max_length=100)
Post = models.ForeignKey(Post)
UPhoto = models.FileField(upload_to=User_directory_path,null = True,blank=True)
Department = models.ForeignKey(Department)
UserRole = models.ForeignKey(UserRole)
def __str__(self):
return u'{}'.format(self.User)
and
class Interview_Interviewer(models.Model):
Interview = models.ForeignKey(Interview)
Interviewer = models.ForeignKey(User)
def __str__(self):
return u'{}'.format(self.Interviewer)
views are...
def hod_pre_interviwer_list(request, iid):
inter = Interview.objects.get(id=iid)
a = UserRole.objects.get(Role="Interviewer")
viewer = Users.objects.filter(UserRole=a.id)
return render(request, 'hod_inter_create_2.html', {'viewer': viewer, 'inter': inter, 'a':a})
def hod_inter_interviewer_2(request, iid, pid):
inter = Interview.objects.get(id=iid)
usr = User.objects.get(id=pid)
a = UserRole.objects.get(Role="Interviewer")
viewer = Users.objects.filter(UserRole=a.id)
usr_id = Users.objects.get(User=a.id)
inter_id = inter
person_id = usr_id
form = Interview_Interviewer(Interview=inter_id, Interviewer=person_id)
form.save()
return render(request, 'hod_inter_create_2.html', {'viewer': viewer, 'inter': inter})
urls are...
urlpatterns = [
url(r'^hod/hod_vacancy/test/part2/inter_list/(\d+)/$', hod_pre_interviwer_list, name="inter1"),
url(r'^hod/hod_vacancy/test/part2/inter_list/(\d+)/(\d+)/$', hod_inter_interviewer_2, name="inter2"),
]
template is...
<a type="submit" class="btn btn-primary" href="/hod/hod_vacancy/test/part2/inter_list/{{ inter.id }}/{{ viewer.id }}">Add</a>
Try using named groups in your url patterns
urlurl(r'^hod/hod_vacancy/test/part2/inter_list/?P<iid>[0-9]+)/?P<pid>[0-9]+/$', hod_inter_interviewer_2, name="inter2"),
If that doesn't work then i suggest trying User.object.get(pk=pid) as in most doc examples.
And make sure that there is a user with that id (iid) in the url.
You should also use get_object_or_404 for getting any single object from a model in the view as it gives a more user friendly and appropriate error.