Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter many-to-many relationship by user and show in template Django
I'm stucked with a problem. I'm developing e-Learning application and have this model (simplified for better understanding): class Course(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=255) enrolled = models.ManyToManyField(get_user_model(), through='Enrol', related_name="course_enrolled") teacher = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="course_teacher") class Section(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=255) course = models.ForeignKey(Course, on_delete=models.CASCADE) class Classe(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=255) content = models.TextField() section = models.ForeignKey(Section, on_delete=models.CASCADE) completed = models.ManyToManyField(get_user_model(), through='ClassCompleted', related_name="classes_completed") class Enrol(models.Model): student = models.ForeignKey(get_user_model()) course = models.ForeignKey(Course, on_delete=models.CASCADE) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class ClassCompleted(models.Model): student = models.ForeignKey(get_user_model()) classe = models.ForeignKey(Classe, on_delete=models.CASCADE) completed = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) My View for the Course page. This page has to show the Sections and Classes. @login_required def ead_course(request, course_id): try: course = Course.objects.get(id=course_id) except Course.DoesNotExist: raise Http404 # Check if student is enroll or is a teacher if request.user.course_enrolled.filter(id=course_id).exists() or course.teacher.id is request.user.id: return render(request, 'ead/ead_course.html', {'course': course}) return HttpResponse("Without permission") And finally my template ead_course.html: {% for section in course.section_set.all %} {{ section.name }} {% for class in section.classe_set.all %} {{ class.name }} {% endfor %} {% endfor %} Everything is fine until now, I'm showing for user all the sections and the classes. The big problem is: I … -
How to create Django Model with combination of 2 models
I want to create one Django models which is the combination of 2 models like, class Employee(models.Model): name = models.CharField(max_length=45) age = models.IntegerField() dob = models.DateField() addr = models.CharField(max_length=45) class designtion(models.Model): emp_id = models.charField(max_length=45) role_name = models.charField(max_length=45) starts_from = models.DateField() ends_on = models.DateField() i want to create a combined models from these 2, class EmpDetails(models.Model): name = models.CharField(max_length=45) role_name = models.charField(max_length=45) i am using django-rest-framework is their any best way to do like this? -
Format a string into Date or any other datatype in Django
I am using Python 3.6 with Django 1.11. My Back-end DB is Salesforce. I am trying to save date field in Salesforce which is accepted from user in the form of String str_var = '11/09/2017' want it to be converted like not_a_str_var = 11/09/2017 I tried with several datetime, date functions but no success. I have also tried using strptime() and strftime() methods. Please suggest -
passing the input value of search bar as a parameter in button onclick
How can I pass the value entered by user in the search bar with the link in the button. <form> <input type="text" id="search" class="st-search-input search-field" value="abc"/> <button type="submit" onclick='window.open("test4?abcd=\"search.value\"");'>Submit</button> </form> -
`~Q` do not work in my filter?
I want to query the status != 4: from django.db.models import Q ... queryset = User.objects.filter(is_staff=True, is_admin=True, ~Q(status = 4), ) But I gets wrong: How to do with that? seems the ~Q do not work? -
cannot load image in html template in django application
I am trying to put an image in html template in my django applicarion but its is not displayed. When i inspect, it says image cannot be loaded. HTML code: <div class = "col-md-4"> <img src= "/static/images/abc.jpg" alt="sorry"/> </div> location of the image abc.png is /home/user/demo/mysite/mysite/static/images/abc.png and my django application is bookmark which resides in mysite(demo/mysite) Is it the correct way of giving path in a django application or something else needs to be done. -
How do I make Heroku run yarn install or npm installl in a subdirectory
Let's say I have a project with the following directory structure project/ ... subdir/ node_modules package.json yarn.lock As you can see my yarn.lock, package.json, and node_modules are a subdirectory. Heroku expects them to be in the root directory. Heroku just runs "yarn install" from the root of the project. I'm trying to figure out how to tell Heroku to run "yarn install" from the one_raft_first_site subdirectory. How do I do this? -
Restrict multiple user access to a model in django admin
I have multiple admin users in my system, and all of them can able to login into the system at a time into the django admin area (http://127.0.0.1:8000/admin). I have a model called Book and all of this users can able to view/edit/save this model at a time in the django admin interface. class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=45) author = models.CharField(max_length=45) category = models.CharField(max_length=45) comment = models.CharField(max_length=1024, blank=True, null=True) class Meta: managed = False db_table = 'book' What i want to achieve is i want to restrict the multiple user access to the Book model. For example when a user1 viewing/editing/saving a book object in django admin interface i want to restrict other users to access this Book model, basically all actions should be restricted. -
request parameter cannot be gotten
Request parameter cannot be obtained. I want to search whether "file" is in request parameter or not. I written the following code: def common_logic(request): data = request.POST.get('data', None) if 'file' in request.POST: file = request.FILES['file'].temporary_file_path() else: file = None return file However, when I set file parameter, always else statement is read. When I print out print(request.POST), <QueryDict: {'data': ['100']}> is shown so file parameter cannot be obtained. I want to get file parameter and search whether request.POST has file or not. Why can't I get file parameter? How can I get this? -
How to view an image uploaded in Django
Hello I would like to ask on how to view an image that I uploaded in django admin to selected html page, this is my html, there is no problem with the object title but I cant seem to load the image. <h3>{{object.title}}</h3> {% if object.productimage_set.count > 0 %} <div> {% for img in object.productimage_set.all %} {{ img.image.file}} <img class='img-responsive' src='{{ img.image.url }}'/> {% endfor %} </div> def image_upload_to(instance, filename): title = instance.product.title slug = slugify(title) file_extension = filename.split(".")[1] new_filename = "%s.%s" %(instance.id, file_extension) return "products/%s/%s" %(slug, new_filename) class ProductImage(models.Model): product = models.ForeignKey(Product) image = models.ImageField(upload_to=image_upload_to) def __unicode__(self): return self.product.title -
Deploying django on azure - scriptprocessor could not be found
I am having some trouble setting up my website on Azure. My website is developed using Django and I am using wfastcgi to run it on the server; but the server keeps giving an error that says, "scriptProcessor could not be found in application configuration." Here is the error exactly: Here is my web.config file: <?xml version="1.0"?> <configuration> <appSettings> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="D:\home\Python27" /> <add key="DJANGO_SETTINGS_MODULE" value="iasf.settings" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="Python27_via_FastCGI" /> <remove name="Python34_via_FastCGI" /> <add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\Python27\python.exe|D:\home\Python27\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <rewrite> <rules> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" /> </conditions> <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> </configuration> -
Python3 + Google App Engine + MySQL
I have been struggling with this for quite awhile now and I cannot seem to find the answer anywhere... I am using this tutorial to set up a django app using Google app engine: https://cloud.google.com/python/django/appengine I am now on the step "Run the app from your local computer" I am recieving the following error when I try and run the django mirgate commands: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 61] Connection refused)") Any idea where how I can fix this? I tried to install mysqlclient using pip however i got the following error also: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/yt/ykmtcb9j4tzfxh3rmzfmzxkh0000gp/T/pip-build-xzqmic32/mysqlclient/ Any help would be greatly appreciated! -
Django Manager isn't available; 'auth.User' has been swapped for 'users.MyUser'
I created Custom UserModel in Django 1.11 and I need a function which allows users to sign in I think my custom user model is incompatible with my function How can I fix? error message enter image description here users.models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from apps.teams.models import Team import uuid class MyUserManager(BaseUserManager): def _create_user(self, username, password, **extra_kwargs): user = self.model(username=username, **extra_kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password, **extra_kwargs): extra_kwargs.setdefault('is_active', True) extra_kwargs.setdefault('is_superuser', True) extra_kwargs.setdefault('is_staff', True) if extra_kwargs.get('is_superuser', None) is not True: raise ValueError('관리자 권한이 필요합니다.') return self._create_user(username, password, **extra_kwargs) class MyUser(AbstractBaseUser): """ 유저 모델 """ POSITION_TYPES = ( ('a', '대표'), ('b', '팀장'), ('c', '과장'), ('d', '대리'), ('e', '주임'), ('f', '사원'), ('g', '인턴'), ) uid = models.UUIDField( primary_key=True, editable=False, default=uuid.uuid4, verbose_name='팀 고유 아이디' ) username = models.CharField( max_length=20, unique=True, verbose_name='아이디' ) name = models.CharField( max_length=10, verbose_name='이름' ) email = models.EmailField( verbose_name='이메일' ) team = models.ForeignKey( Team, verbose_name='소속', null=True, blank=True ) position = models.CharField( max_length=2, choices=POSITION_TYPES, default='g', verbose_name='직급' ) birth = models.DateField( null=True, blank=True, verbose_name='생일' ) date_joined = models.DateField( null=True, blank=True, verbose_name='입사일' ) date_exited = models.DateField( null=True, blank=True, verbose_name='퇴사일' ) is_superuser = models.BooleanField( default=False, verbose_name='관리자 여부' ) is_staff = models.BooleanField( default=False, verbose_name='스태브 여부' ) is_active = … -
How can I configure GeoNode to PUBLIC IP?
I am new to GeoNode, I Installed geonode on my server with my local ip, then its work perfectly, then I linked PUBLIC IP to my server, after that I can access geonode from public IP, but layer preview not worked, So as here said Configuring GeoNode for Production I changed GeoServer Proxy URL (It was http://localhost:8080/geoserver and I changed it to http://PUBLIC_IP/geoserver and tried as http://PUBLIC_IP:8080/geoserver, from browser I can access geoserver from those 2 url ) now layer preview working fine, but file upload not working, Its time out. If I set GeoServer Proxy URL with local IP its working, I changed django_site postgres table domain to public IP but not worked. How can I fixed it. -
Django - cannot assign - must be an instance
I tried phrasing this question recently and got totally confused. I've extended the default user model with this in my models.py: class Biography(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) biography = models.TextField(max_length=500, blank=True,default='Details') I've included this in the forms.py: class EditProfileForm(forms.Form): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') biography = forms.CharField(label='Biography', widget=Textarea(attrs={'rows': 5})) I have a view to edit the profile and want to add "biography" to it, but have absolutely no clue where to start. Here's the view: def edit_profile(request): user = request.user products = Product.objects.filter(user=user) form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name}) if request.method == 'POST': if form.is_valid(): user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.save() return render(request, 'profile.html', {'user':user, 'products':products}) context = {"form": form} return render(request, "edit_profile.html", context) I tried to replicate what is already there with this: def edit_profile(request): user = request.user products = Product.objects.filter(user=user) biography = Biography(user=user) form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'biography':user.biography}) if request.method == 'POST': if form.is_valid(): user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.biography = request.POST['biography'] user.save() return render(request, 'profile.html', {'user':user, 'products':products}) context = {"form": form} return render(request, "edit_profile.html", context) I definitely missed the point somehow. The last time I asked this question I was somewhat chastised for not knowing how to solve … -
Django Social Auth not adding new user with saved Google credentials to the database
Scenario: Whenever a user tries to login via Google, if they're not already in the database, they're redirected back to an anon user state when they shouldn't be. If the user tries to login via Google with an existing email address (they're already in db), then they're authenticated just fine. In the request, even if the user authenticates via Google and is successful (gets an access token and everything), the request still believes it's an anonymous user. Working with Django Social Auth, and before this used to work but it doesn't any more. Code: views.py def index(request): try: # print(request.user) returns AnonymousUser even after authenticating profile = Profile.objects.get(email=request.user.email) return render(request, 'tablefor2/index-logged-in.html') except: return render(request, 'tablefor2/index-logged-out.html') HTML <a href="{% url "social:begin" "google-oauth2" %}"><button class="save btn btn-default">GET STARTED</button></a> settings.py MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tablefor2.urls' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], 'debug': DEBUG, }, }, ] LOGIN_URL = '/' LOGIN_REDIRECT_URL = '/' WSGI_APPLICATION = 'tablefor2.wsgi.application' SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'first_name', 'email'] SOCIAL_AUTH_USER_MODEL = 'tablefor2.Profile' … -
Cannot query field "furniture" on type "RootMutation"
I am wanting to create a furniture object in graphiql by using following query where I get an error Cannot query field "furniture" on type "RootMutation". This is the query I did for creating a furniture object mutation { newFurniture(input: {name: "graphFurniture", content: "This furniture is cool", category: "Bedroom Items"}) { clientMutationId } furniture{ // error is shown here name content category { name } } } Here is my code for mutation class FurnitureNode(DjangoObjectType): class Meta: model = Furniture class NewFurniture(graphene.ClientIDMutation): furniture = graphene.Field(FurnitureNode) class Input: name = graphene.String() content = graphene.String() category = graphene.String() @classmethod def mutate_and_get_payload(cls, input, context, info): furniture = Furniture(name=input.get('name'), content=input.get('content'), category=Category.objects.get(name=input.get('category'))) furniture.save() return NewFurniture(furniture=furniture) class NewFurnitureMutation(graphene.ObjectType): new_furniture = NewFurniture.Field() Why am i getting such error? -
How to use Django Subquery inside Annotate and Sum
I am trying to calculate total revenue for a day. Each DailyTotal contains a count of items sold (items_sold) and a Price those items were sold that day (items_price) (every items is sold for the same price all day). That part is working, but now I need to convert multiply that value by the exchange rate for that day/country. rate = ExchangeRate.objects.filter( date=OuterRef('date'), country=OuterRef('country'))) calc_with_rate = Sum(F('items_sold') * F('items_price') * Subquery(rate.values('rate')), output_field=FloatField(),) results = DailyTotal.objects.filter(**query_filters).annotate( revenue=calc_with_rate) but I get: unsupported operand type(s) for +=: 'int' and 'NoneType I assume it is because rate.values('rate') is not returning a an int.. but I can't do rate.values('rate')[0] or I get: This queryset contains a reference to an outer query and may only be used in a subquery. so I am not sure how to complete this query? -
difference between Response and HttpResponse django
What is the difference between Response and HttpResponse in django i am kinda confusing. Return Respose and return HttpResponse -
Django MySQL connection too slow
My django app is slow. So I profiled that. 69066 function calls (67072 primitive calls) in 0.206 seconds Ordered by: internal time List reduced from 734 to 147 due to restriction <0.2> ncalls tottime percall cumtime percall filename:lineno(function) 2 0.081 0.040 0.101 0.051 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:81(__init__) 6 0.043 0.007 0.043 0.007 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:268(query) 4 0.017 0.004 0.017 0.004 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:254(autocommit) 2 0.013 0.006 0.013 0.006 {function Connection.set_character_set at 0x10622d6a8} I think query is not problem. But connections.__init__ is take a lot of times. So I test very simple function. This is the same function with above profile. But I change auth token to wrong. 2244 function calls (2175 primitive calls) in 0.119 seconds Ordered by: internal time List reduced from 426 to 85 due to restriction <0.2> ncalls tottime percall cumtime percall filename:lineno(function) 2 0.079 0.040 0.095 0.047 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:81(__init__) 4 0.015 0.004 0.015 0.004 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:254(autocommit) 3 0.013 0.004 0.013 0.004 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:268(query) 2 0.008 0.004 0.008 0.004 {function Connection.set_character_set at 0x10622d6a8} Still connections.__init__ take long. This is another simple function to get user list 9818 function calls (9552 primitive calls) in 0.101 seconds Ordered by: internal time List reduced from 553 to 111 due to restriction <0.2> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.041 … -
django allauth bootstrap - TemplateDoesNotExist
I am trying to get the bootstrap forms working for Django-Allauth, but I cannot get it working, and I cannot find much documentation on it. It references these bootstrap forms in the example of the django-allauth repo located at https://github.com/pennersr/django-allauth/tree/master/example. In the directions, it states that all you have to do to get the bootstrap forms working is install django-bootstrap-form and include "bootstrapform" in your INSTALLED_APPS in your settings file. I have done this in my project, but it still appears to be pulling templates from the /account folder instead of the /bootstrap folder. While debugging, I tried just replacing the login.html form in the /account folder with the one from the /bootstrap folder. In this case, I get a TemplateDoesNotExist exception at /accounts/login/ bootstrapform/form.html I figure if I can at least get the bootstrapform stuff working I can just replace the templates inside the /account folder and be fine... Any idea what may be happening? -
Django/MySQL: Making non-unique field unique fails even if field values are unique
I currently have this: class Committee(models.Model): # ...some fields... committee_xml_id = models.IntegerField() I need to make the field committee_xml_id unique, i.e. make it so: class Committee(models.Model): # ...some fields... committee_xml_id = models.IntegerField(unique=True) I have also tried making it so: class Committee(models.Model): # ...some fields... committee_xml_id = models.IntegerField(unique=True, db_index=False) Alas, the result is the same. Having run ./manage.py makemigrations and subsequently, ./manage.py migrate, the problem is this: django.db.utils.OperationalError: (1061, "Duplicate key name 'appname_committee_committee_xml_id_d1210032_uniq'") At first glance, it seems like the problem is that there is already non-unique data in the table, but the problem is precisely that there isn't. There are only 45 rows in the table, and the field committee_xml_id contains only unique entries. The following query gives no results, as expected when there are no duplicates: SELECT com.committee_xml_id, COUNT(*) FROM appname_committee AS com GROUP BY com.committee_xml_id HAVING COUNT(*) != 1 For rigor, here is the same query without the HAVING-condition, showing clearly that there are indeed no duplicates: SELECT com.committee_xml_id, COUNT(*) FROM appname_committee AS com GROUP BY com.committee_xml_id Result is: # committee_xml_id, COUNT(*) 78, 1 79, 1 124, 1 125, 1 129, 1 130, 1 131, 1 132, 1 133, 1 134, 1 137, 1 139, 1 140, 1 … -
NoReverseMatch: Reverse for 'deleted' with no arguments not found. - Django
I'm a new face to Django so please be considerate to if ever my problem is something stupid. So I have been practicing Django, and currently making a CRUD, however I've run into problems with tegards to NoReverseMatch, I went through answers in stackoverflow but still I couldn't find where I went wrong. Can you help me a bit guys? Actually it was working, when I resetted the DB, somehow it had the error, maybe i moved something or whatever unlucky thing i did. I've been at it for 3 hours actually. Just this error. So please help me: The traceback says that the NoReverseMatch is on this url Delete which i properly partnered and connected with url(r'^delete/(?P\d+)/', Delete.as_view(), name="deleted"), in my urls.py. Here's the gist of the code: First here's the urls involved. deleteupdate/urls.py (Delete and Update are from models imported to the file) urlpatterns = [ url(r'^', views.list, name='list'), url(r'^delete/(?P<pk>\d+)/', Delete.as_view(), name="deleted"), url(r'^update/(?P<pk>\d+)/', Update.as_view(), name="updated"), url(r'^(?P<student_id>)/', views.detail, name='detail'), ] main/urls.py urlpatterns = [ url(r'^$', include('index.urls')), url(r'^admin/', admin.site.urls), url(r'^list/', include('deleteupdate.urls')), ] Here's the HTML: {% if all_students %} <ul> {% for user in all_users %} <li><a href="/list/{{ user.id }}"></a> <button type="button"> <a href="{%url 'deleted'%}">Delete</a> </button> <button type="button"> <a href='{% … -
Is there a way to raise Permission Denied without rendering 403.html?
I'm trying to raise just the status of the error. PermissionDenied automatically renders 403.html for me. Is there a way to just raise the status without this? class IsMemorandumAdmin(UserPassesTestMixin): def test_func(self,user): permission = Permission.objects.get(name="Can CRUD Memorandums") return permission in user.user_permissions.all() def handle_no_permission(self,request): raise PermissionDenied the mixin API requires me to throw an exception of BasePermission type. If possible, an HttpResponse(status=401) would be nice -
Django save related ManyToMany model
I have two models with ManyToMany relationship as this: class Subject(models.Model): teachers = models.ManyToManyField( Teacher ) subject = models.CharField( 'Materia', max_length = 50, unique = True ) level = models.CharField( 'Nivel', max_length = 3, choices = LEVEL_CHOICES ) class Teacher(Person): # fields definition Following the docs I know I can save Subject model without saving Teacher field. That's fine. Now I want to add a Subject to Teacher, so I need a form with selected teacher, and a choice field with all the subjects. I found this question that relates to what I want to accomplish, but I think it doesn't address what I'm looking for. First I populate the subject choice filed, as shown in the ModelForm code below. forms.py class SubjectTeacherForm(ModelForm): subject = forms.ChoiceField(choices=[(m.id, m.subject) for m in Subject.objects.all()]) class Meta: model = Subject fields = ['teachers', 'subject'] urls.py #here I send the teacher id to the view url(r'^materias/asignar/profesor/(?P<teacher_id>\d+)/$',MateriaTeacherCreateView.as_view(), name='materia-create-teacher'), views.py class SubjectTeacherCreateView(SuccessMessageMixin, CreateView): model = Subject template_name = 'edu/subject/subject_create.html' form_class = SubjectTeacherForm def form_valid(self, form): # here I want to add the relation teacher = Teacher.objects.get(pk=self.kwargs['teacher_id']) self.object.teachers.add(teacher) return redirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super(SubjectTeacherCreateView, self).get_context_data(**kwargs) # here I define the selected teacher to pass to the …