Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My functions are not working in my django project
I'm currently trying to return data in json or api view format with my following text fields (email, country and phone number), However I also have 2 validation functions to validate the value in the email and phone number fields which require the get() method and also using it to pass the text as a argument. I am not sure if the 2 validation functions are working or not as when I entered an invalid email, it is still accepted as a valid data. Please tell me what I am doing incorrectly and what changes should be made to my current code. /* serializers.py */ import re import phonenumbers from rest_framework import serializers from .models import validation from phonenumbers import carrier from validate_email import validate_email class validationSerializer(serializers.ModelSerializer): class Meta: model = validation fields = '__all__' def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, check_mx=True, verify=True): raise serializers.ValidationError("Invalid email") return email def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") clean_number = re.sub("[^0-9&^+]", "", phone_number) alpha_2 = self.cleaned_data.get("country") z = phonenumbers.parse(clean_number, "%s" % (alpha_2)) if len(clean_number) > 15 or len(clean_number) < 3: raise serializers.ValidationError( "Number cannot be more than 15 or less than 3") if not phonenumbers.is_valid_number(z): raise serializers.ValidationError( "Number not correct format or non-existent") … -
How to update instance's particle attribute using Django Modelseirallizer?
I want to update instance's attribute using Django Modelseriallizer. I want to change only 'tel' attribute in 'Activity' model. but my code is not working. this is model class Activity(models.Model): num = models.AutoField(primary_key=True) #번호 name = models.CharField(max_length=100, blank=True, null=True) eventStartDate = models.CharField(max_length=100, blank=True, null=True) eventEndDate = models.CharField(max_length=100, blank=True, null=True) eventTime = models.TextField(max_length=1000, blank=True, null=True) eventPlace = models.TextField(max_length=1000, blank=True, null=True) discription = models.TextField(max_length=1000, blank=True, null=True) longitude = models.DecimalField(max_digits=20, decimal_places=12, blank=True, null=True) latitude = models.DecimalField(max_digits=20, decimal_places=12, blank=True, null=True) tel = models.CharField(max_length=255, blank=True, null=True) img = models.CharField(max_length=255, blank=True, null=True) grade = models.IntegerField(default=0,blank=True, null=True) this is view class ActivityList(APIView): permission_classes = (permissions.AllowAny,) def get(self, request): data = Activity.objects.all() serializer = ActivitySerializer(data, many=True) return Response({"ActivityList":serializer.data}) this is serializer class ActivitySerializer(serializers.ModelSerializer): tel = serializers.CharField() def update(self, instance, validated_data): instance.tel = 'new tel number' instance.save() return instance class Meta: model = Activity fields = ('num', 'name', 'eventStartDate', 'eventEndDate', 'eventTime', 'eventPlace', 'discription', 'longitude', 'latitude', 'tel', 'img', 'grade') # fields = '__all__' -
How to display error message in Django template after HttpRedirect from another view?
I'm creating a simple CRUD application without using the admin page of Django. I only have one template, index.html that displays all the list of student information. I have two views below, one is for displaying only when the user visited the index page. The other view is executed when a user in the index page clicks a submit button for registering a new student (via POST) then redirects to the index view again. I want to display an error message if the student already exists in the database (by using student number). My problem is how can I pass the error message in the index.html template after the HttpRedirect. Or am I doing it the wrong way? def index(request): studentList = Student.objects.all() return render(request, "crud/index.html", {"student_list": studentList}) def addStudent(request): data = request.POST # print(data) if data: try: newStudent = Student.objects.get(student_number=data['student_number']) return HttpResponseRedirect(reverse("crud:index")) except Student.DoesNotExist: newStudent = Student(student_number=data['student_number'], first_name=data['first_name'], last_name=data['last_name'], age=data['age'], sex=data['sex'], email=data['email'] ) newStudent.save() return HttpResponseRedirect(reverse("crud:index")) -
I had an html comment in a Django template, and it was causing a server error when DEBUG=False, why?
Previously I had a favicon.png, I deleted the favicon.png file. This did not create any issues until I switched from DEBUG = True to DEBUG = False in my settings.py file. And I got a 500 server error. To diagnose the issue I added DEBUG_PROPAGATE_EXCEPTIONS = True to my settings.py And I got the following error: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'favicon.png' Only place where there was even a mention of 'favicon.png' was as an html comment in my login html template file, login.html contained the following in head: <title>Login</title> <!-- <link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"/> --> when I deleted the favicon.png html comment so that code became: <title>Login</title> I no longer got a 500 server error, and things worked again. How can an html comment cause an error in my code? I thought it was impossible for an html comment to cause an error. -
How to ForeignKey to a value two tables away?
I have the following models: class Ensemble(Group): name = models.CharField(max_length=100, null=True, blank=True) instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('part'), related_name='ensemble_member', null=True, blank=True, on_delete=models.PROTECT) class EnsembleMember(models.Model): person = models.ForeignKey(Person, verbose_name=_('member'), on_delete=models.PROTECT) instrument ???? = models.ForeignKey(Instrumentation, verbose_name=_('part'), related_name='ensemble_member', null=True, blank=True, on_delete=models.PROTECT) //This is the line in question ensemble = models.ForeignKey(Ensemble, verbose_name=_('ensemble'), related_name='ensemble_member', on_delete=models.PROTECT) class Instrumentation(models.Model): name = models.CharField(max_length=100, null=True, blank=True) class Instrument(MPTTModel): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) instrumentation = models.ManyToManyField(Instrumentation, verbose_name=_('instrumentation'), related_name='instrument', blank=True) I would like to be able to able to link EnsembleMembers to only the instruments available in instrumentation under Ensemble. How would I create this ForeignKey relationship. For example: There are three instruments: Violin, Cello, and Piano An instance of instrumentation with this three instruments is called "Piano Trio". An ensemble called the "Beaux Arts Trio" is linked to the instrumentation "Piano Trio". "Menahem Pressler" is an Ensemble Member and the pianist in the "Beaux Arts Trio". I want to link this instrument to the "Piano". Piano is an allowable instrument to be linked because it is in the instrumentation linked to the Ensemble. How do I setup this last connection in the EnsembleMember model? -
How to use nginx to detect/post server too busy page when Django server is not responsive
When django server CPU is too busy, no GET/POST can reach django server. When it happens, I notice, browser has this page until server CPU is NOT too busy. 502 Bad Gateway nginx/1.4.6 (Ubuntu) How to configure nginx to detect/post server too busy page, because 502 Bad Gateway is not user friendly? -
Django LiveServerTestCase appears to reload fixtures between tests
I'm running this with Django 2.2.5 and Postgres 11 It appears that the Django test framework's LiveServerTestCase reloads fixture data in-between each test without deleting the previous data. I come across this with a consistent error: > ./manage.py test functional_tests Creating test database for alias 'default'... System check identified no issues (0 silenced). .EE ====================================================================== The first test passes but the subsequent tests fail. The error I get is: django.db.utils.IntegrityError: Problem installing fixture '.../fixtures/unit_test.json': Could not load app.Configuration(pk=1): duplicate key value violates unique constraint "app_configuration_site_id_3124a87d_uniq" DETAIL: Key (site_id)=(1) already exists. If I comment out and don't load fixtures the 3 tests work perfectly fine. There is only one record entry with the PK in question in the fixtures. This tells me that the Test reloads the data and fails because it finds an existing record with the same PK. Is there a way to tell it to either overwrite the data with the same PKs or ignore (a-la get_or_create)? Is there a better practice to follow with LiveServerTestCase? It's frustrating because I can't seem to be able to use this test class with fixtures when I need to. Any insight is appreciated. RB -
Django dynamic fields - cannot get data from multiples added rows - ManagementForm data is missing or has been tampered with
I am working on a template that generate multiple rows. I am missing something to all get the data from generated row. I get an exception value : ['ManagementForm data is missing or has been tampered with'] when i submit the form. I think I am missing something to get the data from multiple rows. Here is my code : models.py class Product(models.Model): contractNumber = models.ForeignKey('SupportContract', on_delete=models.SET_NULL, null=True) serialNumber = models.CharField(max_length=800, null=True) reference = models.ForeignKey('ProductDescription', on_delete=models.SET_NULL, null=True) quantity = models.IntegerField() def __str__(self): return str(self.serialNumber) if self.serialNumber else '' form.py class ProductForm(forms.ModelForm): contractNumber = forms.ModelChoiceField(required=False, queryset=SupportContract.objects.all().order_by('number'), label='contractNumber', widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Contract number'})) serialNumber = forms.CharField(required=True, label='serialNumber',widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter serial number'})) reference = forms.ModelChoiceField(required=False, queryset=ProductDescription.objects.all().order_by('name'), label='reference',widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Product descrition'})) quantity = forms.IntegerField(initial=1, required=True, label='quantity',widget=forms.NumberInput(attrs={'class': 'form-control','placeholder': 'Enter a quantity'})) class Meta: model = Product fields = '__all__' def clean(self): super().clean() contractNumber = self.cleaned_data.get('contract_number') serialNumber = self.cleaned_data.get('serial_number') reference = self.cleaned_data.get('product_reference') quantity = self.cleaned_data.get('quantity') ProductFormset = formset_factory(ProductForm, extra=1) template.html <div data-role="dynamic-fields"> {{ form_Product.management_form }} <div class="form-inline" style="margin-left: -15px"> <div class="form-group col-md-2"> {{ form_Product.quantity }} </div> <div class="form-group col-md-2"> {{ form_Product.serialNumber }} </div> <div class="form-group col-md-2"> <button class="btn btn-danger" data-role="remove"> <span class="fas fa-minus"></span> </button> <button class="btn btn-primary" data-role="add"> <span class="fas fa-plus"></span> </button> </div></div></div> views.py def form_exhibit_c(request): ProductFormset … -
If the field is not entered, how to make it not filtered in django
I am creating a lookup field and would like to know how do I do so that if a field is not entered it does not appear in the address bar even if its value is null. http://localhost:8000/pesquisa/?prova= to http://localhost:8000/pesquisa/ views.py def index(request): provas = Prova.objects.all().order_by('idProva') questoes = Questao.objects.filter().order_by('idProva') categorias = Categoria.objects.all().order_by('nomeCategoria') form = QuestaoProvaForm() return render(request, 'polls/index.html',{'categorias':categorias,'questoes':questoes,'provas':provas,'form':form}) def pesquisa(request): template_name = 'polls/pesquisa.html' query = request.GET.get('q', '') prova = request.GET.get('prova', '') questao = request.GET.get('questao', '') categoria = request.GET.get('categoria', '') results = Questao.objects.filter(idProva=prova) return render(request, template_name, {'results': results,'prova':prova,'questao':questao,'questoes':questoes}) -
How to set up WSGI conf file
I am deploying to productions server but cannot get my static files to work for the life of me. My Apache error logs say: [Thu Oct 03 23:12:17.805038 2019] [mpm_event:notice] [pid 5987:tid 139950847048640] AH00491: caught SIGTERM, shutting down [Thu Oct 03 23:12:17.965217 2019] [mpm_event:notice] [pid 6092:tid 140185146706880] AH00489: Apache/2.4.38 (Ubuntu) mod_wsgi/4.6.5 Python/3.7 configured -- resuming normal operations [Thu Oct 03 23:12:17.965310 2019] [core:notice] [pid 6092:tid 140185146706880] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 03 23:12:22.324089 2019] [wsgi:error] [pid 6093:tid 140185001051904] [remote 73.192.250.234:60904] Not Found: /users/static/users/main.css And my .conf file: Alias /static /home/david/sc/static <Directory /home/david/sc/static> Require all granted </Directory> Alias /media /home/david/sc/media <Directory /home/david/sc/media> Require all granted </Directory> I am sure it has to do with the fact that my static files are in /sc/users/static/users/ but nothing I do can get the WSGI to point to that folder.. -
Stop .filter() on first match in Django
Is there a way to stop querying the remaining records in the database after the query returns a match. For instance if I do this: Profile.objects.filter(first_name='Dwight') I want it to stop running the query for all the Profiles as soon as it finds a Profile with the first_name of Dwight. -
How swap article from MySql databse using asynchronous threads in Django
Is possible to achieve something like slider in Django ? I would like swap article which came from MySql database in random time. I pretty sure that I can do that using multithreading , but i don't know how handle requests. Thank you for any answer -
Django, autocomplete_light : autocomplete does not work over https
autocomplete suggests some things like below with a URL over http://.... autocomplete does NOT suggest anything with the same URL over https://... How can I make the autocomplete over https to work like the one over the http? -
Django context variable as inline css property's value
i'm trying to pass in a context variable as the value for css property but i can't seem to get it to work <nav style="background-color: {{ nav_color }};"> i tried wrapping the variable in single quotes but it still won't work even though i know the variable gets passed when i inspect the element using devtools(it gets passed with the quotes and hence is not a valid css property) i.e <nav style="background-color: '{{ nav_color }}';"> // doesn't work -
How to replace Google Map Key generated by JAVASCRIPT script in DJANGO by a custom variable
I am trying to find a way to hide my google map key displayed on the javascript script. The key is generated from django settings. I am not sure how to properly achieve it with javascript script and src settings.py GOOGLE_MAP = "XZZZZZZX" views.py def activity_list(request): """ Render list of foo. """ foo = Foo.objects.all() # Google Map Key google_map_key = settings.GOOGLE_MAP context = { 'foo': foo, 'google_map_key': google_map_key } return render(request, 'snippet/index.html', context) HTML {% extends "base.html" %} {% load static %} {% block content %} <!-- Render Map on HTML --> <div id="map"></div></br></br> <!-- Pass the Google Map key variable to Front end --> <div id="google_map" style="display:none" value="{{ google_map_key }}"></br> {% endblock %} {% block key %} <!-- Grab the Google Map key value from HTML above --> var name_ = document.getElementById('google_name').getAttribute("value"); <!-- Google Map Key --> <script id="name" data-name="value" src="https://maps.googleapis.com/maps/api/js?key=XZZZZZZX&callback=initMap" async defer></script> {% endblock %} How can I possibly replace the google map key with the custom variable from the backend? -
Read-the-docs subdomain not working as intended
I am using private read-the-docs server , let's say hosted on "docs.example.com". I am trying to host my documentation build on subdomain, "project.docs.example.com". When I go to that subdomain, browser displays 404 error.There is not project on this path. What configuration am I missing here. I have these settings already set: In /settings/base.py USE_SUBDOMAIN=True PUBLIC_DOMAIN=docs.example.com DEBUG=True I added domain "project.docs.example.com" in my project and I click on checkbox to use that domain as primary one for hosting documentation of that project. I clicked on checkbox "Use single version", for document to be hosted on subdomain without versions. I set my documentation to "Public documentation" Expected result: When click "View docs" after build is finished successfuly it redirected me to "project.docs.example.com" and I see my documentation. Actual result: It redirected me to "project.docs.example.com" but I see 404 error File not found on this path. After some digging arround I found out that my documentation is visible only on docs.example.com/docs/project. -
How to Filter ".get_fields()" to Exclude Proxy Models in Django?
How can I get a list of fields from a given model, but exclude fields from an abstract model? The docs on .get_fields say the following: include_parents True by default. Recursively includes fields defined on parent classes. If set to False, get_fields() will only search for fields declared directly on the current model. Fields from models that directly inherit from abstract models or proxy classes are considered to be local, not on the parent. Which is great, except that I need to exclude proxy/abstract model fields as well. For example: class AbstractModel(models.Model): some_abstract_field = models.IntegerField() class Meta: abstract = True class SomeModel(AbstractModel): some_field = models.IntegerField() How can I get a list of fields for SomeModel but exclude fields from AbstractModel? The only solutions I can think of: subclassing the ModelBase metaclass for my models to include the distinction between abstract models and child models This sounds like a nightmare for a multitude of reasons... monkey patching my abstract models to include a property that returns list of field names I'll likely end up posting an answer using this route, but surely there is a more pythonic way of doing this. -
who to get (" placeholder ") attribute of input tag using POST request?
I want to get my placeholder attr, when user submit the form. I want the placeholder data. how can it be possible in django framework? -
How to implement multiple forms for one template
I'm new to Django. I have multiple forms for different calculations (etc Form1, Form2, Form3, ...) on my blog page. Each blog post (post/1) will have a button at the page with a link to open specific form template (post_form.html) for that post (e.g. post/1/form/) with a form in it. (Post1 - Form1, Post2 - Form 2, etc..) Could someone help with the logic of implementation of this? How to better set up urls, models and forms? models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category , on_delete=models.CASCADE, default='Concrete') author = models.ForeignKey(User , on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='calc_pics') formId = models.IntegerField() class L_section_prop_calc(models.Model): name = models.CharField(max_length=100, unique=True) tf = models.DecimalField(max_digits=5, decimal_places=3) tw = models.DecimalField(max_digits=5, decimal_places=3) height = models.DecimalField(max_digits=5, decimal_places=3) urls.py path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), forms.py class Calc_L_Section_Prop_Form(forms.ModelForm): class Meta: model = L_section_prop_calc fields = ['tw','tf','height'] I'm do not know if I need to create a model for each form. Is there a better way? Thx -
TypeError: unsupported type for timedelta seconds component: list
I am setting up a CAS(Central Authentication Server) via https://github.com/jbittel/django-mama-cas and getting an error when it tries to create the ticket due to stderr: TypeError: unsupported type for timedelta seconds component: list I've searched on how to convert a django model object value to integer for timedelta() function with no luck on figuring it out myself. def create_ticket(self, ticket=None, **kwargs): """ Create a new ``Ticket``. Additional arguments are passed to the ``create()`` function. Return the newly created ``Ticket``. """ if not ticket: ticket = self.create_ticket_str() if 'service' in kwargs: kwargs['service'] = clean_service_url(kwargs['service']) if 'expires' not in kwargs: expires = now() + timedelta(seconds=self.model.TICKET_EXPIRE) kwargs['expires'] = expires t = self.create(ticket=ticket, **kwargs) logger.debug("Created %s %s" % (t.name, t.ticket)) return t Expected results: CAS logs me in and redirects me back to CAS enabled app. Actual Results: Internal Server Error (500) App 29175 stderr: [ pid=29175, time=2019-10-03 19:08:25,610 ]: Internal Server Error: /login App 29175 stderr: Traceback (most recent call last): App 29175 stderr: File "/opt/rh/httpd24/root/var/www/public/cas_container/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner App 29175 stderr: response = get_response(request) App 29175 stderr: File "/opt/rh/httpd24/root/var/www/public/cas_container/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response App 29175 stderr: response = self.process_exception_by_middleware(e, request) App 29175 stderr: File "/opt/rh/httpd24/root/var/www/public/cas_container/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response App 29175 stderr: … -
How to return result celery to template django
I've a task that have many querys in my database, some consults require time > 30s , and my server heroku , can't. I would like to query and return to template. my code View: `` ` class sales_filter(LoginRequiredMixin, View): def get(self, request): data = {} task = searching.delay() return render(request, 'sales/sales_filter.html', data) `` ` Task: `` ` @shared_task def searching(): data['cod_parceiros'] = mapa.objects.values('cod_parceiro').distinct().\ filter(mes_referencia__icontains=ano).order_by('cod_parceiro') return render(request, 'sales/sales_filter.html', data) `` ` I tried this, but doesn't work. -
Field error for invalid user and Value error for new user registration in DJANGO
Many questions are there with the same keywords, but none of the answers helped. The issue is when an user other than the default user(admin) tries to login, Field error message is shown. When the same user is tried to register Value error is thrown. Hope someone could point out the mistake. Code : form1.py from django import forms from django.contrib.auth.models import User from django.contrib.auth import ( authenticate, get_user_model ) User=get_user_model() class UserLoginForm(forms.Form): username=forms.CharField(required=True) password=forms.CharField(required=True,max_length=120,widget=forms.PasswordInput) def clean(self, *args,**kwargs): username=self.cleaned_data.get('username') password=self.cleaned_data.get('password') if username and password: user=authenticate(username=username,password=password) if not user: raise forms.ValidationError("user does not exists") if not user.check_password(password): raise forms.ValidationError('Incorrect Password') return super(UserLoginForm, self).clean(*args,**kwargs) class UserRegisterForm(forms.ModelForm): username=forms.CharField(required=True) password=forms.CharField(required=True,max_length=120,widget=forms.PasswordInput) email=forms.EmailField(required=True) class meta: model = User fields=[ 'username' 'email' 'password' ] def clean_email(self): username=self.Cleaned_data.get('username') email=self.Cleaned_data.get('email') password=self.Cleaned_data.get('password') email_qs=user.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("Email is already being used") return email code: views.py from __future__ import unicode_literals from django.shortcuts import render,redirect from django.core.mail import send_mail from django.conf import settings from .form1 import UserLoginForm,UserRegisterForm from django.contrib.auth import( authenticate, get_user_model, login, logout ) def login_view(request): next=request.GET.get('next') print("the following is being returned") title='Login' form= UserLoginForm(request.POST or None) if form.is_valid(): username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username,password=password) login(request,user) if next: return redirect(next) return redirect('/contact') templates="login.html" context={'title':title,'form':form,} return render(request,templates,context) def register_view(request): next=request.GET.get('next') title='Register' form= UserRegisterForm(request.POST or None) … -
Django import_export decode ascii code on submit?
Im trying to upload and import data into models from a csv file that contains special ASCII characters, for example "Big Fish Äö√Ñ√¥s", the django import_export would give me an error that reads: Imported file has a wrong encoding: 'utf-8' codec can't decode byte 0x80 in position 511: invalid start byte. This error would show when I select the file and click submit. The feature Im trying to implement would take a csv file that contains thousands of row of data, I was wondering if there is a way that I can go through each row level and clean the data line by line. I have tried implmenting the before_import_row method, but it doesn't seems to be called. my admin.py: '''ptyhon from django.contrib import admin from import_export.admin import ExportActionModelAdmin, enter code hereImportExportMixin, ImportMixin from import_export.resources import ModelResource from .forms import CustomConfirmImportForm, CustomImportForm from .models import Author, Book, Category, Child, EBook class ChildAdmin(ImportMixin, admin.ModelAdmin): pass class BookResource(ModelResource): class Meta: model = Book def for_delete(self, row, instance): return self.fields['name'].clean(row) == '' class BookAdmin(ImportExportMixin, admin.ModelAdmin): list_filter = ['categories', 'author'] resource_class = BookResource class CategoryAdmin(ExportActionModelAdmin): pass class AuthorAdmin(ImportMixin, admin.ModelAdmin): pass admin.site.register(Book, BookAdmin) admin.site.register(Category, CategoryAdmin) admin.site.register(Author, AuthorAdmin) ''' my models.py '''python [![import random import string … -
Python Dictionary should return a value rather than None
I have a csv file which consists a,b 2,3 4,5 4,7 4,7 (where a,b is a column values) Below i have two functions where the first function will read the csv and assign 'a' as key and 'b' as value in a dictionary Second function i will pass 'a' value as an argument and it returns b as a value when i use that function.If there is no value for 'a' i get None. def x (id): dict1= {} with open(file, 'r', encoding='utf') as f: for i in csv.DictReader(f, skipinitialspace= True) dict1[i['a']] = row['b'] print('im happy now' ) def getx (a): return dict1.get(a, None) It works perfectly. Now I have a csv file with four column values a,b,c,d 1,2,r,4 2,g,4,6 3,d,4,6 For this i have written a code like def x (): dict1= {} with open(file, 'r', encoding='utf') as f: for i in csv.DictReader(f, skipinitialspace= True) dict1[i['a']] = dict(dict1[i['b']] = dict(dict1[i['c']] = row['d'])) print('im happy now' ) def getx (a): return dict1.get(dict1['a']['b']['c'], None) My logic is to show dict1[i['a']] = dict(dict1[i['b']] = dict(dict1[i['c']] = row['d'])) as dict1 :{ 'a':{ 'b':{ 'c':2, 'c':4, 'c':4 } } } I'm not sure if what i have written above is right. I need to … -
Django: displaying foreign key model in parent model's detail view template
I have the following two models: class SpecimenImage(models.Model): image = ImageField(upload_to='images/') usi_image = models.ForeignKey('SpecimenRecord', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Unique Specimen Identifier') ... class SpecimenRecord(models.Model): usi = models.CharField(primary_key=True, max_length=20, verbose_name='Unique Specimen Identifier') species = models.ForeignKey(Species, on_delete=models.SET_NULL, null=True, blank=True) locality = models.ForeignKey(Locality, on_delete=models.SET_NULL, null=True, blank=True) date = models.DateField(null=True, blank=True) collector = models.ManyToManyField(Collector, verbose_name='Collector(s)', null=True, blank=True) ... I have a generic detail view for SpecimenRecord: ... class SpecimenDetailView(generic.DetailView): model = SpecimenRecord Here is the urls.py: ... urlpatterns = [ ... path('specimen/<str:pk>', views.SpecimenDetailView.as_view(), name='specimen-detail'), ] My question is, how do I display and loop through all of the SpecimenImage instances associated with a single SpecimenRecord object in the html template? I can easily display the information for each SpecimenRecord by using {{ specimenrecord.usi }}, etc., but I cannot figure out how to display each image. I've tried using the information on the MDN website for generic detail views (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views): {% for copy in book.bookinstance_set.all %} <!-- code to iterate across each copy/instance of a book --> {% endfor %} Here is the code I tried in my template specimenrecord_detail.html: {% extends "base.html" %} {% load thumbnail %} {% block content %} ... {% for copy in specimenrecord.specimenimage_set.all %} <div class="gallery"> <img src="{% thumbnail copy.image '1920' …