Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I pass the value of two separate inputs into the content field of my form in Django?
In my template I have a form that includes two input elements whose values can be adjusted with javascript. I want to be able to take these values and, on form submit, display them in a sentence in a for loop underneath. index.html: <form action="{% url 'workouts:workout' %}" method="post"> {% csrf_token %} <div class="weight"> <h4>WEIGHT (kgs):</h4> <button type="button" class="weight-dec">-</button> <input type="text" value="0" class="weight-qty-box" readonly="" name="one"> <button type="button" class="weight-inc">+</button> </div> <div class="reps"> <h4>REPS:</h4> <button type="button" class="rep-dec">-</button> <input type="text" value="0" class="rep-qty-box" readonly="" name="two"> <button type="button" class="rep-inc">+</button> </div> <input type="submit" value="Save" name="submit_workout"> <input type="reset" value="Clear"> </form> {% if exercise.workout_set.all %} {% for w in exercise.workout_set.all %} {{ w.content }} {% endfor %} {% endif %} I have given the form above an action attribute for a url which maps to a view, and each of the inputs has a name in order to access their values in the view. I also have written this form in forms.py: class WorkoutModelForm(forms.ModelForm): class Meta: model = Workout fields = ['content'] And for context, here is my model: class Workout(models.Model): content = models.CharField(max_length=50) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None) class Meta: ordering = ('created',) My problem from here is that I have … -
Django Template - filtering content
I have two models - "Products" and "Categories", and every product may be added to existing category. I am trying to find a way to render page with products, filtered by category. Currently I did it for every category by manualy filtering it in template: {% for instance in object_list %} {% if instance.category.categoryname == "Statues" %} {{ instance.name }} {{ instance.description }} {{ instance.price }} {% endif %} {% endfor %} I have same template for every category ("Paintings", "Jewelry" etc) and changed condition in each template. URL "../Statues" leads to prexisting template Is there any way to do it easier? I would like condtition {% if instance.category.categoryname == "Statues" %} to be imported from URL. So when you access "../Jewelry" - template would import "Jewelry" from URL and filter content accordingly. models.py class Category(models.Model): categoryname = models.CharField(max_length=20) description = models.CharField(max_length=200, blank=True, null=True) #To make in name, not objXXX def __str__(self): return self.categoryname class Product(models.Model): name = models.CharField(max_length=20) image = models.ImageField(upload_to='static/photos', default='http://placehold.it/700x400') description = models.TextField(max_length=200, blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey(Category, on_delete=models.PROTECT, blank=True, null=True) #To make in name, not objXXX def __str__(self): return self.name urls.py urlpatterns = [ path('admin/', admin.site.urls), path('<str:categoryname>', category_filter) ] view.py def category_filter(request, … -
Django: searching postgresql JSON field Array of Objects
I have the following json that is appended to a models.JSONField "descriptions": [ { "description": "The Chandra Source Catalog (CSC) is a general purpose virtual X-ray astrophysics facility that provides access to a carefully selected set of generally useful quantities for individual X-ray sources, and is designed to satisfy the needs of a broad-based group of scientists, including those who may be less familiar with astronomical data analysis in the X-ray regime. The first release of the CSC includes information about 94,676 distinct X-ray sources detected in a subset of public Advanced CCD Imaging Spectrometer imaging observations from roughly the first eight years of the Chandra mission. This release of the catalog includes point and compact sources with observed spatial extents ≲30''.", "descriptionType": "Abstract", "lang": "en-US" }, { "description": "The catalog includes real X-ray sources detected with flux estimates that are at least 3 times their estimated 1σ uncertainties in at least one energy band, while maintaining the number of spurious sources at a level of ≲1 false source per field for a 100 ks observation. For each detected source, the CSC provides commonly tabulated quantities, including source position, extent, multi-band fluxes, hardness ratios, and variability statistics, derived from the … -
DjangoCMS copy site slug
we're using djangocms and have german and english pages. Now the slugs for both pages need to be the same. Is there a way to copy the slugs of all german pages to all the english ones without going into the site settings and copy-pasting the german slug to the english slug? I was going for something like manage.py cms copy lang --from-lang=de --to-lang=en --verbosity=2 --skip-content but I haven't tried it yet. Thank you for any help. -
Django ModelFieldChoice select passing value
Hi i'm using ModelFieldChoice to set the foreign key from Provider in the model "Article" (Article belongs to Provider). The select in the template is displayed correctly with all the providers from the database, but when i try to post the form, it throws an error that the select value is required even if i'm passing it. Also i seted values for the article in the database, and when i tried to edit it, all the fields in the form are populated with the correct data except for the select. These are my models, i would appreciate the help, thanks! Sorry if i'm doing something wrong, this is my first time posting in stackoverflow. Article.py Model class Article(models.Model): codigo = models.CharField(max_length=100, verbose_name='Codigo') proveedor = models.ForeignKey(Provider, on_delete=models.CASCADE) descripcion = models.CharField(max_length=200, verbose_name='Descripcion',null=False, blank=True) marca = models.CharField(max_length=100, verbose_name='Marca',null=True, blank=True) rubro = models.CharField(max_length=100, verbose_name='Rubro',null=True, blank=True) nota = models.TextField(verbose_name='Nota',null=True) costo = models.CharField(max_length=50, verbose_name='Costo',null=False, blank=True) created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación",null=True, blank=True) updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de edición",null=True, blank=True) class Meta: verbose_name = "articulo" verbose_name_plural = "articulos" ordering = ['-descripcion'] def __str__(self): return self.descripcion Provider.py Model class Provider(models.Model): razon_social = models.CharField(max_length=100, verbose_name='Razón Social', unique=True) direccion = models.CharField(max_length=100, verbose_name='Dirección', blank=True, null=True) localidad = models.CharField(max_length=100, verbose_name='Localidad', blank=True, null=True) … -
return the absolute url in django media files
I am trying to build graphql api using graphene and when I query an image from my api it returns "/media/images/image.jpg" and I want the full url with the domain name -
Show related model field without adding another fk relation to the model
I've got this 2 models in models.py: class Purity(models.Model): id = models.BigAutoField(db_column='purity_id', primary_key=True) sample = models.ForeignKey(Sample, models.DO_NOTHING) percentage = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) class Sample(AbstractSample): label_commodity = models.ForeignKey(RelatedLabelCommodity, models.DO_NOTHING) user = models.ForeignKey(User, models.DO_NOTHING, related_name='samples') And I'd like to display the purity percentage field in admin.py as: class SampleAdmin(admin.ModelAdmin): list_display = ['---'] Is there any way to this without adding a ForeignKey relationship to Purity in the Sample database table? I found that I could do a sql raw query but it looks also as a security hazard, and I was wondering if there was a better and simpler way. -
Django internationalization doesn't work in my project
I read the documentation, read some blogs and started applying internationalization in my project, but it doesn't work. Probably something is going wrong. Please take a look what is it that I am doing wrong. I am a windows user, so I started installing gettext versions both shared and static from this link. then I made following changes in settings.py: LANGUAGE_CODE = 'fr' MIDDLEWARE = [ "django.middleware.locale.LocaleMiddleware", ... ] LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] I already set the language code to French language. Then in my template namely index.html I added following code: {% load i18n %} <!-- within block content --> {% trans "Hi" %} Now that everything is set I run following code in console: django-admin makemessages -l fr I received this message: UnicodeDecodeError: skipped file requirements.txt in . (reason: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte) processing locale fr I have no idea if above stated error has anything to do with translating the text of the template. Anyway, then in django.po within locale directory I translated that text of template to french as following: #: .\templates\index.html:29 msgid "Hi" msgstr "Salut" and run django-admin compilemessages, but when I run it the … -
How to add custom permissions to token authentication in Django rest framework
I've built an endpoint using Django-rest-framework and I've added token authentication to it by simply adding rest_framework.authentication.TokenAuthentication to the DEFAULT_AUTHENTICATION_CLASSES. This works great. Without the token I get a 403 and with it I get the expected 201. I now want to add a custom permission to it, so I did the following: class CustomPermission(BasePermission): def has_permission(self, request, view): breakpoint() return False def check_permission(self, user): breakpoint() return False class MyViewSet(DetailSerializerMixin, viewsets.ModelViewSet): queryset = MyModel.objects.all().order_by('timestamp') http_method_names = ['post'] permission_classes = [CustomPermission] To my surprise this doesn't do anything. It never reaches the breakpoints and works exactly as without it. Does anybody know what I'm doing wrong here? -
Getting Image from Page Link for django application
I have json file and it contain "Product_url": "https://www.amazon.in/Samsung-Galaxy-Storage-Additional-Exchange/dp/B07PQ7CRBH/ref=sr_1_11?keywords=phone&qid=1563166792&s=electronics&smid=A14CZOWI0VEHLG&sr=1-11", How to get image from this like below one https://images-na.ssl-images-amazon.com/images/I/71ftMiKUwbL._SL1500.jpg -
Registration and login to Django website with mobile app
i have a website running on django(postgresql db) and now i'm developing mobile app with xamarin forms. i've created web api with asp.net core and successfully consume data from website. my question is how can i make registration and login to website from my app. i added username, password and email to postgresql db through web api, but i can't login to website using these credentials. it says incorrect password or username. is it a right way to insert user data to db? my app code: public async void Reg_Clicked(object sender, EventArgs e) { Dictionary<string, string> userData = new Dictionary<string, string> { { "username", EntryUsername.Text }, { "email", EntryEmail.Text }, {"password1", EntryPassword1.Text }, {"password2", EntryPassword1.Text }, }; var jsonData = JsonConvert.SerializeObject(userData, Formatting.Indented); Console.WriteLine(jsonData); // Создать Http-клиент для подключения HttpClient client = new HttpClient(); var content = new StringContent(jsonData, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync("https://localhost/api/UserData", content); var result = await response.Content.ReadAsStringAsync(); Console.WriteLine(result); } catch (Exception) { Console.WriteLine("Failure"); } } my web api code: public async Task<ActionResult<UserData>> PostUserData(UserData userData) { _context.UserDatas.Add(userData); await _context.SaveChangesAsync(); //put in database string connectionString = "Server=server; Port=5432; User Id=user; Password=password; Database=database"; try { connection = new NpgsqlConnection(connectionString); connection.Open(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } … -
DELETE method not responding if run in docker
I have a django application that runs with docker. I use postgres as a database. Any call GET, PUT and POST work great. The main problem here is that when I do any call to an endpoint that should delete something from the database it deletes the data, but it dosen't respond. If I call the endpoint and right after check the database, the data is gone, but the delete call remains in waiting. The situation is different if I run the django application outside the docker (even if I use the postgres dockerized) because the delete endpoints work perfectly and they reply me right after with the correct message.. my docker file is # pull official base image FROM python:3.8.0-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app ENV APP=/home/app RUN mkdir $APP/staticfiles RUN mkdir $APP/mediafiles RUN mkdir $APP/files WORKDIR $APP # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PIPENV_TIMEOUT 3600 # Psycopg dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev openssl-dev libffi-dev libc-dev gcc libxslt-dev # Install dependencies RUN pip install --upgrade pip … -
Cannot resolve keyword 'some_field' into field. Choices are:
I am filtering the Model by related Model but I am encountering some errors specified in the question title. Cannot resolve keyword 'bmodel' into field. Choices are: title, description, number, client_user_id, assignee_id Models are like that: 1st model class AModel(BaseModel): title = models.TextField(null=True, blank=True) description = models.TextField(null=True) number = models.CharField(max_length=200) client_user = models.ForeignKey("User", related_name="client_users", null=True) assignee = models.ForeignKey("User", related_name="user_assignees", null=True) 2nd model class BModel(models.Model): amodel = models.ForeignKey("AModel", related_name="a_model", on_delete=DO_NOTHING) user = models.ForeignKey("User", related_name="entity_user") my queryset class AModelView(GenericViewSet): queryset = AModel.objects.all() serializer_class = AmodelSerializer def get_queryset(self): current_user = 2 qs = super().get_queryset() qs = qs.filter(bmodel__user_id__in=current_user) return qs How can I solve this issue? can anybody help please? Thanks in advance! -
return filtered query-set using Django-Graphene
i'm trying to return filtered results using django-graphene but it gives error about error-message could anyone please let me know why this happening class PatientType(DjangoObjectType): class Meta: model = Patients exclude = ('active',) interfaces = (relay.Node,) class PatientsQuery(ObjectType): get_patient = graphene.Field(PatientType, id=graphene.Int()) all_patients = graphene.List( PatientType, first=graphene.Int(), skip=graphene.Int(), phone_no=graphene.Int() ) upcoming_appointments = DjangoFilterConnectionField(PatientType) @permissions_checker([IsAuthenticated, CheckIsOrganizationActive]) def resolve_upcoming_appointments(self, info, **kwargs) -> List: d = datetime.today() - timedelta(hours=1) settings.TIME_ZONE # 'Asia/Karachi' aware_datetime = make_aware(d) res = Patients.objects.filter(appointments__booking_date__gte=aware_datetime, appointments__booking_date__day=aware_datetime.day, appointments__status=True) if res: return res return [] class Query( organization_schema.OrganizationQuery, inventory_schema.MedicineQuery, patient_schema.PatientsQuery, graphene.ObjectType, ): -
Django orm remove overlapping date_ranges
I'm new to django & I have a table with multiple entries of different date_ranges. I want to get only the unique ranges & then get Count of numbers of days from them. For example Consider following three ranges: 1. 10-09-2017 to 10-09-2019 2. 10-08-2018 to 10-02-2020 2. 04-04-2020 to 04-04-2020 In the above example 1 & 2 have overlapping dates, actual calculation for point 2 should change start_range to the end_range of point 1 and then calculate days based on that (I know it can be a little confusing and I'm happy to explain it further if required) I can use something like following to get difference in days for each date_range calculate_experience = ExpressionWrapper( Case( When(experiences__end__isnull=True, then=date.today()-F('start'))[0].days, default=F('end')-F('start')), distinct=True, filter=Q(is_active=True), output_field=DurationField() ) But I have no idea how to get only unique ranges from this, the only thing that comes to mind is putting these in a list & then iterating over that manually settings ranges & then calculating the difference. Is there a better way to do this? Any help or sense of direction is much appreciated. Thanks! -
How to test Django app with multitenancy on localhost
I am developing a Django app that works with multitenancy through the django-tenant-schemas library. We bind subdomains to our tenants. I need to test a data migration locally before I run it on production but the problem I'm running into is that I cannot access all the tenants. What I need to do is use the application, click buttons and see if everything still works, posing as multiple of our clients. We currently have it set up so that the public schema is bound to 127.0.0.1 on my local machine and our own tenant to localhost. On our staging / production it would be client.ourdomain.com, but as I understand -and tested- it you cannot work with subdomains on localhost, so I'm lost on how to get access to the other tenant schemas. I have tried to edit my /etc/hosts file to bind the following 2 but those don't work: localhost client.localhost 127.0.0.1 client.localhost This seems like it would be a problem many people run into but I cannot seem to find good info on how to do this both in the official docs or elsewhere, although the second link looks to be what I need but they suggest what I … -
How can i enter value into select/option from django model?
this is my first question here. I've a model that looks like this; class Fund(models.Model): name = models.CharField(max_length=500, null=False, blank=False) code = models.CharField(max_length=5, null=False, blank=False) management_price = models.CharField(max_length=15, null=True, blank=True) performance_price = models.CharField(max_length=15, null=True, blank=True) explanation = models.TextField(max_length=1000, null=True, blank=True) And i want to show all Fund names in a select area in the template here; <div class="form-group col-md-12"> <label>Fon*</label> <select id="fundIdSelect" class="form-control select2"> <option value="0">Lütfen Fon Seçiniz</option> </select> </div> And this my relevant views.py; def privacy(request): fund_list = Fund.objects.all() return render(request, 'privacy.html', context={'fund_list': fund_list}) -
At which point does a model object converts its values to the data type of it's backend database?
For example in this model: class Invoice(models.Model): req_date = models.DateField(null = True, blank = True) def save(self, request_user = None, date = None, change_type = None, comment = None, old_obj = None, *args, **kwargs): super().save(*args, **kwargs) print(self.req_date) If i run the save() method, it prints '2020-09-28' (string), however, if i call the model instance right after the save() method (ex: print(invoice.req_date)) it gives me datetime.date(2020, 9, 28). So, at which point does the string become a datetime? I need to catch the "correct value" of the req_date (datetime object) inside the save() method. Is that possible? -
Error when trying to open a repository in Ubuntu 20.04
I coded a Todo App with Django on WSL2 and had it comitted to my github repository. On trying to clone it to my desktop with Ubuntu and running pip3 install -r requirements.txt It gave me the error: ERROR: Could not find a version that satisfies the requirement cloud-init==20.2 (from -r requirements.txt (line 9)) (from versions: none) ERROR: No matching distribution found for cloud-init==20.2 (from -r requirements.txt (line 9)) May I know how to sort out this error? -
Problem with my magnifying glass in Django
I'm trying to build a magnifying glass for my webpage in Django. I'm using a library called AnythingZoomer to magnify text: https://css-tricks.github.io/AnythingZoomer/text.html. The problem is that after adding the Scripts and the CSS that the give you in their project the magnifying effect doesn't work. I added the ids and the code needed in the HTML but it also won't work. Magnifying script (It's in base.html): <script> $(function() { // clone the small area, the css will define the dimensions // default class name for the large area is "large" $("#zoom").anythingZoomer({ clone: true }); // zoom in $('button').click(function(){ $(this).addClass('selected').siblings().removeClass('selected'); // .small p { font-size: 8px; width: 300px; } var origW = 300, origSz = 8, // get multiple multiple = parseInt( $(this).text() ); $('.large p').css({ width: origW * multiple, fontSize: origSz * multiple }); // update anythingZoomer window, // but first turn off clone since cloning the small area again will remove our changes $('#zoom').getAnythingZoomer().options.clone = false; $('#zoom').anythingZoomer(); }); }); </script> <link rel="stylesheet" href="{% static 'css/anythingzoomer.css' %}"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="{% static 'js/jquery.anythingzoomer.js' %}"></script> The text I'm trying to magnify (It's in index.html): <div id="zoom" class="row" class="zoom"> <div class="col-md-12"> <p>La memoria es una de las principales facultades humanas, nos define … -
Sending An Email Attachment In Django (Production)
I am wanting to add an attachment to an email. I am running this on a production server (I can do this in development). I have successfully stored my static files in static_files using whitenoise and they display correctly on the page. I am trying to send one of these static files in this email. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_files') if form.is_valid(): # have also tried '\\attachment\\test.pdf' file_path = os.path.join(settings.STATIC_ROOT+'/attachment/test.pdf') try: msg = EmailMessage('subject', 'body', '#@#.#', '#@#.#') with open(file_path, 'rb') as attach_file: data = attach_file.read() msg.add_attachment('test.pdf', data, 'application/pdf') msg.send() This throws a 500 error. Thank you. -
Introducing custom user model when auth.User FK fields already exist
We're looking to have email confirmation in our site and I started setting up django-simple-email-confirmation. This requires having a custom user model mixin which has built-in email confirmation and various utilities and wrappers: class User(SimpleEmailConfirmationUserMixin, AbstractUser): pass And then you need to change the appropriate settings: AUTH_USER_MODEL = 'appanme.User' Now the problem is that every instance of code were we used auth.User or auth.UserManager the code fails because it's using the wrong active user model. Sovling this appears to be as simple as changing User with get_user_model() (actually not sure how to go about UserManager, maybe get_user_model()._default_manager?) but now I'm concerned about all ForeignKey fields using the auth.User model will be affected or wiped since the model will change. Is this cause for concern? How should I go about using the new custom user model? -
Host Django application in the Lightsail's built in Apache server
I want to have a production ready Django app with Lighsail and for that I'm following two tutorials to achieve this Deploy Django-based application onto Amazon Lightsail Deploy A Django Project From the Bitnami article can see that the AWS documentation follows its Approach B: Self-Contained Bitnami Installations. According to: AWS's documentation, my blocker appears in 5. Host the application using Apache, step g. Bitnami's documentation, where it says On Linux, you can run the application with mod_wsgi in daemon mode. Add the following code in /opt/bitnami/apps/django/django_projects/PROJECT/conf/httpd-app.conf: The blocker relates to the code I'm being asked to add, in particular the final part that has Alias /tutorial/static "/opt/bitnami/apps/django/lib/python3.7/site-packages/Django-2.2.9-py3.7.egg/django/contrib/admin/static" WSGIScriptAlias /tutorial '/opt/bitnami/apps/django/django_projects/tutorial/tutorial/wsgi.py' More specifically, /opt/bitnami/apps/django/. In /opt/bitnami/ can only see the following folders . bitnami_application_password . bitnami_credentials . htdocs . stack and from them the one that most likely resembles /opt/bitnami/apps/ is /opt/bitnami/stack/. Thing is, inside of that particular folder, there's no django folder - at least as far as I can tell (already checked inside some of its folders, like the python one). The workaround for me at this particular stage is to move to a different approach, Approach A: Bitnami Installations Using System Packages (which I'm not entirely sure … -
I want to create a list of lists
I know there is quite a number of similar questions on stackoverflow but they don't seem to be solving my problem. If you look at my code below, you can see that I am creating a temp list of ads called "tempAdList" and when the if condition evaluate true I am creating a list of lists called "ad_list". I am appending to "ad_list" so I am expecting that everytime the "if statement" evaluates true a new list of 4 ads is appended to "ad_list" but for whatever reason I am getting below output which is not what i am looking for. what am I doing wrong here? ads = Advert.objects.all() counter = 1 tempAdList = [] ad_list = [] for i, ad in enumerate(ads): tempAdList.append(ad) if counter == 4: # print(tempAdList) ad_list.append(tempAdList) print(ad_list) tempAdList.clear() counter = 0 counter += 1 adsNum = len(ads) # print("i = {} and adsNum = {}".format(i, adsNum)) if i == adsNum -1 and adsNum % 4 != 0: ad_list.append(tempAdList) output: -
Choices makemigration error: There are some values Django cannot serialize into migration files
I have error Cannot serialize for this: MY_CHOICES = ((c.pk, c.course) for c in CourseInstance.objects.all()) It works, but how critical is it and how to fix it? In general, I'm trying to make a MultipleChoiceField where the values will be from the current model class, but I have no idea how to get "self" in models.py. So I did something like this: my forms.py class UpdatePrintDocForm(ModelForm): CHOICES = ((c.pk, c.course) for c in CourseInstance.objects.all()) the_choices = forms.MultipleChoiceField( choices=CHOICES, widget=forms.CheckboxSelectMultiple() ) class Meta: model = Student fields = ("the_choices",) my models.py class Student(models.Model): MY_CHOICES = ((c.pk, c.course) for c in CourseInstance.objects.all()) the_choices = MultiSelectField(choices=MY_CHOICES, blank=True) my views.py def UpdatePrintDoc(request, pk): student_inst = get_object_or_404(Student, pk=pk) redirect_to = request.GET.get("next", "") if request.method == "POST": form = UpdatePrintDocForm(request.POST) if form.is_valid(): student_inst.the_choices = form.cleaned_data.get("the_choices") student_inst.save() return HttpResponseRedirect(redirect_to) else: initial_data = {"the_choices": student_inst.the_choices} form = UpdatePrintDocForm(initial=initial_data) return render( request, "spacestud/doc_update.html", {"form": form, "studentinst": student_inst}, ) my doc_update.html <form action="" method="post" enctype = "multipart/form-data"> {% csrf_token %} <table> {% for field in form %} <div class="row"> <div class="col-md-2"> {{ field.label_tag }} {% if field.help_text %} <sup>{{ field.help_text }}</sup> {% endif %} {{ field.errors }} </div> <div class="col-md-10 pull-left"> <ul id="id_the_choices"> {% for course in studentinst.course.all %} {% …