Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am passing an object to a template in Django but I can not call it
I am in Django, I am making a list of objects in my views.py so I can pass it to my template and show those properties in my page. I create the list of objects and their properties like this: views.py: def courseListView(request): object_list = {} courses = Course.objects.all() for course in courses: object_list[course] = { 'prog': int(lessonsCompleted.objects.filter(user=request.user.id, course=course.id).count() / course.lessons.count() * 100), 'title': course.title, 'slug': course.slug, 'thumbnail': course.thumbnail, 'get_absolute_url': '/' + course.slug, } context = { 'object_list': object_list, } return render(request, "courses/course_list.html", context) In this way I am populating a object called object_list with a number of objects I extract from my Course model. In the template I try calling the properties of the objects in object_list like this: template: {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/courses.css' %}"> <div class="container d-flex justify-content-center"> <div class="row"> <h1>Cursos</h1> <div class="container-fluid mt-4 d-flex card-deck justify-content-center"> {% for object in object_list %} <div class="row justify-content-center"> <div class="col-auto mb-3"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="/static/{{ object.thumbnail }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title"><a href="{{ object.get_absolute_url }}">{{ object.title }}</a></h5> <div class="w3-light-grey w3-round-xlarge"> <div class="w3-container w3-blue w3-round-xlarge" id="progress-{{ object.slug }}" style="width:{{ object.prog }}%;">{{ object.prog }}%</div> </div> <div class="card-footer"> … -
Django aggregation of aggregation - Cannot compute Sum is an aggregate
I'm trying to perform an aggregate of an aggregate, but looks like is not possible (SQL doens't allow it) Let's start defining what contains the queryset: DW00 2020-01-01 2020-03-31 653.38 DW00 2020-01-01 2020-03-31 8,346.54 DW00 2020-04-01 2020-06-30 488.00 DW00 2020-04-01 2020-06-30 8,346.54 DW00 2020-07-01 2020-09-30 488.00 DW00 2020-07-01 2020-09-30 8,390.07 R00 2020-01-01 2020-03-31 6,877.11 R00 2020-04-01 2020-06-30 6,877.11 R00 2020-07-01 2020-09-30 6,877.11 The values are respectively: condition_type, calculation_from, calculation_to and net. Now we want sum the row that have same condition_type and same competence period (calculation_from, calculation_to) this translate to rows 1 and 2 merged together, rows 4 and 5 and finally 6 and 7. sap_payments = sap_payments.values('condition_type', 'calculation_from', 'calculation_to') \ .annotate(competence=Sum('net')) \ .order_by() This will return another queryset that contains: {'competence': Decimal('8999.92'), 'calculation_from': datetime.date(2020, 1, 1), 'condition_type': 'DW00', 'calculation_to': datetime.date(2020, 3, 31)} {'competence': Decimal('8834.54'), 'calculation_from': datetime.date(2020, 4, 1), 'condition_type': 'DW00', 'calculation_to': datetime.date(2020, 6, 30)} {'competence': Decimal('8878.07'), 'calculation_from': datetime.date(2020, 7, 1), 'condition_type': 'DW00', 'calculation_to': datetime.date(2020, 9, 30)} {'competence': Decimal('6877.11'), 'calculation_from': datetime.date(2020, 1, 1), 'condition_type': 'R00', 'calculation_to': datetime.date(2020, 3, 31)} {'competence': Decimal('6877.11'), 'calculation_from': datetime.date(2020, 4, 1), 'condition_type': 'R00', 'calculation_to': datetime.date(2020, 6, 30)} {'competence': Decimal('6877.11'), 'calculation_from': datetime.date(2020, 7, 1), 'condition_type': 'R00', 'calculation_to': datetime.date(2020, 9, 30)} Now we want calculate the days diff … -
django double filter with the same field
How to double filter with the same field? this is my sample below, i didnt get any data , i just want to filter the Status = 'cut off completed' and Status = 'cut off completed' but i didnt get any data from it. deliverySchedule = DeliverySchedule.objects.filter(Status = 'cut off completed').filter(Status = 'Active').order_by('deliverySchedule') my data from django admin -
What is the best way to compare time in sql?
I am creating a django project for dental clinic appointment booking. Was wondering what is the best way to compare the date and time using sql or any other methods. Eg the dr has booked an appointment for 10/6/2020 13-1. for the next appointment how do I validate the available slots to avoid overlapping ? -
Django - RelatedObjectDoesNotExist even after default value have been written
I have extended default User model with "phone' field. I would like user to update their phone number after sign up. The problem is that for new created user 'phone' object is seen as empty even after default value have been written in code. If I want update phone number via form - I get an error : RelatedObjectDoesNotExist at /phone User has no profile. When I check user's attributtes via admin panel I see that field has default value (111 in my case), but for some reason when I load template there is empty object error. models.py: # extending profile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(max_length=12, default=111) views.py: def update_profile(request): profile_form = ProfileForm(instance=request.user.profile) return render(request, 'phone.html', { 'profile_form': profile_form }) phone.html <form method="post"> {% csrf_token %} {{ profile_form.as_p }} <button type="submit">Save changes</button> </form> signals.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(max_length=12, default=111) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Django: global template not found after creating settings module
I am struggling with paths in Django. I have the following directory structure: application # created by django | |--application |--apps # apps created by django's startapp command |--app_1 |-- ... |--__init__.py | |--app_2 |-- ... |--__init__.py |--__init__.py | |--settings |--__init__.py |--base.py |--development.py |--production.py |--__init__.py |--asgi.py |--urls.py |--wsgi.py | |--static |--css |--js |--fonts |--images | |--templates |--meta |--head.html |--javascript.html |--includes |--home.html | |--requirements.txt I just created the settings directory using this tutorial Improve your Django project with these best practices. So the __init__.py is has a single line from .development import *. The file development.py has from .base import * DEBUG = True and base.py includes all the stuff of the old settings.py file. After I did that, my templates are not working anymore, and I guess this will also happen to the static files. When I want to access the page, django returned: TemplateDoesNotExist at /blog/includes/home.html This is my setup in base.py for static files and templates. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], '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', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] My BASE_DIR is Django Project\application\application. And this is my … -
I'm using python-social-auth but my app isn't logging out when the user logs out of Google
I have python-social-auth working to authorize my app and everything works great. I can log into my app via OAuth2 and log out via typical Django logout. My problem: if a user logs out of Google (from GMail, for example), it does not log me out of my Django app. I am still authorized as the Google user even though Google is logged out. I have tried refreshing tokens via the load strategy below to "force" a check to make sure Google is still logged in and that isn't working. social = request.user.social_auth.get(provider='google-oauth2') access_token = social.get_access_token(load_strategy()) social.refresh_token(load_strategy()) I feel like I'm going down the wrong road. All I want to do is validate that Google is logged into still so I can consider my OAuth2 session valid. Is there a way to do this integrity check? What am I doing wrong or do I need to do? My research so far suggests what I want is not even possible - I don't like that answer so hoping for a different one here. -
How can i create this type of Django Admin (as shown in the pic)
Chick Here for the Pic..... This is the Admin template, here the Model options are on left side and the content stored in the model is on right side. -
Trouble rendering a variable in Django
I'm trying to "create" a variable and render it in my template but for some reason I can't manage to do it. Here's my view.py: def test(request): person = {'firstname': 'Craig', 'lastname': 'Daniels'} weather = "sunny" context = { 'person': person, 'weather': weather, } return render(request, 'home/dashboard.html', context) and in my template dashboard.html : <h1>Hi {{ person.firstname }} {{ person.lastname }}</h1> Any idea on what I'm doing wrong? -
I can't delete users from my app in Django
I am developing a webpage for elderly people in Django for my internship. I received some code already done from another coworker but for some reason when I try to delete users from the /admin site it gives me and error. In addition, I only have one form to register and login in the webpage but it gives another error. login view: def login_view(request): if request.user.is_authenticated: return redirect(reverse('portada')) mensaje = 'El usuario no estaba registrado' if request.method == 'POST': username = request.POST.get('username') dia = request.POST.get('dia') mes = request.POST.get('mes') year = request.POST.get('year') password = dia + mes + year + 'year' user = authenticate( username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect(reverse('portada')) else: return render(request, 'accounts/login.html', {'error_message': 'Your account has been disabled'}) else: mensaje = 'Se va a registrar un usuario' form = RegistroUserForm(request.POST, request.FILES) if form.is_valid(): cleaned_data = form.cleaned_data dia = form.cleaned_data['dia'] mes = form.cleaned_data['mes'] year = form.cleaned_data['year'] password = dia + mes + year + 'year' user_model = User.objects.create_user(username=username, password=password) user_model.save() user_profile = UserProfile() user_profile.user = user_model user_profile.save() username = request.POST.get('username') dia = request.POST.get('dia') mes = request.POST.get('mes') year = request.POST.get('year') password = dia + mes + year + 'year' user = authenticate(username=username, password=password) if … -
Django Foreign Key to Filtered Object got errors: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I have problem that i never face before. I have custom user model on models.py class User(AbstractUser): username = models.CharField( max_length=50, unique=True) email = models.EmailField(_('email address'), unique=True) phone = models.IntegerField(_('phone number'), unique=True, blank=True, null=True) these users associated with Groups : maker, checker, signer >>> print(Group.objects.all()) <QuerySet [<Group: maker>, <Group: checker>, <Group: signer>]> in other app called cleaning, I want have an object that associated with these users filtered by each group. So in my cleaning app models.py User = get_user_model() user_maker = User.objects.filter(groups__name='maker') user_checker = User.objects.filter(groups__name='checker') user_signer = User.objects.filter(groups__name='signer') class cln_daily(models.Model): . . . user_maker = models.ForeignKey(user_maker,on_delete=models.CASCADE, blank=True, null=True) user_checker = models.ForeignKey(user_checker,on_delete=models.CASCADE, blank=True, null=True) user_signer = models.ForeignKey(user_signer,on_delete=models.CASCADE, blank=True, null=True) but then I got an error that said django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. . . . File "D:\gtipwa\lib\site-packages\django\apps\registry.py", line 141, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. any idea how to use filtered object in foreign key?? I'm not sure but i think the problem is caused by double underscore in object filter. I have no idea how to fix them. -
Wagtail internal link urls arent working properly
in my rich body text fields, when an internal page is used for a link, the url that gets attached to the a tag is "https//example.com/example", ie it's missing the colon and the link doesnt work. I get the error "https's server ip address could not be found". any idea why it is doing this? thanks -
Django: Inject code post pk/id generation and before save in DB
TL;DR: Is there a way to inject code post pk / id generation but before the object is saved in the db? Hello, So I am currently working on duplicating django objects. I have a duplicate function which enforces new object generation upon saving by setting pk and uid to None on a deep clone of my object: def gen_uuid() -> str: """Return a str representation of a uuid4""" return str(uuid4()) class Entry(PolymorphicModel): """Base class providing a custom lock permission, a name and a uid to replace Django's default id DB column.""" uid = models.CharField( unique=True, primary_key=True, db_index=True, default=gen_uuid, max_length=36, help_text="Object's primary key, it cannot be enforced and will be generated randomly. " "Example: c8daa3ac-3dd0-44e9-ba2a-b0cbd1c8d8ae.", ) name = models.CharField(max_length=128, help_text="Name of the object.") folder = models.ForeignKey( Folder, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="files", help_text="Primary key to the folder containing the object.", ) content = JSONField( default=dict, blank=True, help_text="JSON representation of the graph." ) def save(self, *args, **kwargs): """Handles entry saving and duplicate management This function is overridden so the models can be created with the name. This function does not fill missing duplicate numbers. It will create duplicates in such pattern: entry_name entry_name (2) entry_name (3) """ # Does some stuff... … -
No Response after calling the API
I am working on a project, where I am making a call to the API https://apis.justwatch.com/content/titles/en_IN/popular?body=%7B%22page_size%22:5,%22page%22:1,%22query%22:%22The%20Irishman%22,%22content_types%22:[%22movie%22]%7D I am making the call to the API, using the code import requests data = requests.get('https://apis.justwatch.com/content/titles/en_IN/popular?body=%7B%22page_size%22:5,%22page%22:1,%22query%22:%22The Irishman%22,%22content_types%22:[%22movie%22]%7D') print(data.json()) But, today when I made the call to the same API, it gave me None Response, and when I tried making the same API call on my browser, it worked fine. I made a minor change, that while making a call to the API, I added a header specifying the browser details, like header = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" } and now the code is working fine. Can anybody tell me why it is so, that the request was working fine earlier but why I had to specify the header now ? -
SAVE CHECKED STATE OF CHECKBOX AFTER CLOSING THE WEBSITE
I'm working on a django project in which i have a list of checkboxes. I'd like to know how do i save the fact that the checkbox has been checked after i close the website? the checkbox's label are the values of a Model that i created. As database i'm using the default one given by django, sqlite3. here's a little snippet of my code: <ul class="list-group list-group-flush"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"> <label class="form-check-label" for="flexCheckDefault"> {{project.description}} </label> .... </ul> -
Make, migrate model programmatically, and reload / repopulate django application's new settings / configurations
I am making a model programmatically using the following code: modelObj = type(m.get("name"), (models.Model,), m.get("attrs")) After that I am trying to run the makemigrations, migrate, and autoreload command using the following code. def migrate_and_reload(): management.call_command("makemigrations") lm = MigrationRecorder.Migration.objects.filter(app=modelObject._meta.app_label).last() management.call_command("migrate", modelObject._meta.app_label, lm.__dict__.get("name"), "--database==test") from django.utils import autoreload autoreload.restart_with_reloader() But: And, get the Message from autoreloader that the server port is already use If I comment the autoreloader then Migration is not run into the database. However, Makemigration works and a migration file is created in the app's migration folder) My basic goal is to register the dynamic model programmatically, make respective migrations (handle any errors if there), migrate it to Db, and reload the server I will prefer not to reload the server, but seems like I have no other options to reload all the settings or populate the configurations in Django 3.0.3. Any help is welcome -
Django use rowspan in DataTables
I have a problem with DataTables in Django. I want to use DataTables to show some information, and use rowspan to group information by position. Look at the code below. <table id="example" class="display" style="width:100%"> <thead> <tr> <th colspan="2">HR Information</th> <th colspan="3">Contact</th> </tr> <tr> <th>Position</th> <th>Salary</th> <th>Office</th> <th>Extn.</th> <th>E-mail</th> </tr> </thead> <tbody> {% for x in pos %} {% for y in emp %} <tr> {% if forloop.first %} <td rowspan={{emp|length}}>{{ y.position }}</td> {% endif %} <td>{{ y.salary}}</td> <td>{{ y.office}}</td> <td>{{ y.extn}}</td> <td>{{ y.mail}}</td> </tr> { % endfor %} { % endfor %} </tbody> <tfoot> <tr> <th>Position</th> <th>Salary</th> <th>Office</th> <th>Extn.</th> <th>E-mail</th> </tr> </tfoot> </table> But I got "Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined" Could you explain to me, how can I resolve this issue? Have you any idea? -
Why is the data in the serializer not shown in django?
I'm going to make four serializers and put three serializers in one serializer. However, only one of the three serializers operates normally and the other two do not. I made the structure of the three serializer almost identical, but I don't understand if only one works. Please help me solve the problem. JSON { "pk": 1, "author": { "username": "username", "email": "email", "profile": "image_link" }, # AuthorSerializer is worked "title": "title1", "text": "text1", "view": 0, # ImageSerializer is not worked "like_count": 0, # LikerSerializer is not worked "comment_count": 0, "tag": "hash tag", "created_at": "time" } serializers.py class AuthorSerializer (serializers.ModelSerializer) : profile = serializers.ImageField(use_url=True) class Meta : model = User fields = ('username', 'email', 'profile') class ImageSerializer (serializers.ModelSerializer) : image = serializers.ImageField(use_url=True) class Meta : model = Image fields = ('image', ) class LikerSerializer (serializers.ModelSerializer) : id = serializers.IntegerField(source='liker.pk') class Meta : model = Like fields = ('id', ) class PostSerializer (serializers.ModelSerializer) : author = AuthorSerializer(read_only=True) image = ImageSerializer(read_only=True, many=True) like_count = serializers.ReadOnlyField() liker = LikerSerializer(read_only=True, many=True) comment_count = serializers.ReadOnlyField() class Meta : model = Post fields = ('pk', 'author', 'title', 'text', 'image', 'view', 'like_count', 'liker', 'comment_count', 'tag', 'created_at') def create (self, validated_data) : images_data = self.context['request'].FILES post = Post.objects.create(**validated_data) for … -
Issue with forms.ModelForm and ForeignKey
I am writting ToDo application with user login possibility. I want to do that, each user can see his own individual task-list. Problem - I can see the particular tasks for each user after login, but I can not add task via form in my app after adding ForeignKey to my TaskModel. I can only add task in admin panel Should I add ForeignKey - query to my form somehow? Model: from django.db import models from django.contrib.auth.models import User class Task(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) created_time = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=False) def __str__(self): return self.title Form: from django.contrib.auth.models import User class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' class CreateAccount(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] View: def tasks_list(request): tasks = Task.objects.filter(owner=request.user) form = TaskForm() if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks': tasks, 'form': form, } return render(request, 'todo/base.html', context) -
MultiValueDictKeyError, when submitting the form
I am new to django and faced an unpleasant problem that I cannot solve for a couple of days, please help.Everything works for me for two forms, but when I add a third, the third form does not work, and the form with a page change is very important to me. How can I fix the error: ""? Exception Type: MultiValueDictKeyError Exception Value: 'ProfileUpdateForm-valuta' Exception Location: C:\Users\Maxim\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\datastructures.py, line 78, in __getitem__ file views.py: #from django.contrib.auth.views import PasswordChangeView from django.contrib.auth.forms import PasswordChangeForm class ProfilePage(UpdateView): model=Profile template_name="market/profile.html" form_class=UserUpdateForm second_form_class= ProfileUpdateForm third_form_class=PasswordChangeForm def get_success_url(self): obj=Profile.objects.get(user__username=self.object) return reverse_lazy('profile',kwargs={'slug': obj.slug},) def get(self, request, *args, **kwargs): self.object = get_object_or_404(Profile,slug=self.kwargs['slug']) ctx = self.get_context_data(**kwargs) return self.render_to_response(ctx) def get_context_data(self, **kwargs): ctx = super(ProfilePage,self).get_context_data(**kwargs) ctx['UserUpdateForm'] = self.form_class( prefix='UserUpdateForm', data = self.request.POST if bool(set(['UserUpdateForm-submit']).intersection(self.request.POST)) else None, instance=self.request.user, ) ctx['ProfileUpdateForm'] = self.second_form_class( prefix='ProfileUpdateForm', data = self.request.POST if 'ProfileUpdateForm-submit' in self.request.POST else None, files = self.request.FILES if 'ProfileUpdateForm-submit' in self.request.POST else None, instance=self.request.user.profile, ) ctx['PasswordChangeForm'] = self.third_form_class( prefix='PasswordChangeForm', data = self.request.POST if 'PasswordChangeForm-submit' in self.request.POST else None, user=self.request.user, ) return ctx def post(self, request, *args, **kwargs): self.object = Profile.objects.get(user__username=self.request.user) ctx = self.get_context_data(**kwargs) recalculation_of_сost(self,ctx['ProfileUpdateForm']) if ctx['UserUpdateForm'].is_valid(): return self.form_valid(ctx['UserUpdateForm']) elif ctx['ProfileUpdateForm'].is_valid(): return self.form_valid(ctx['ProfileUpdateForm']) elif ctx['PasswordChangeForm'].is_valid(): return self.form_valid(ctx['PasswordChangeForm']) return self.render_to_response(ctx) -
Adding Inline HTML Code to Wagtail Rich Text Editor
I am using Wagtail CMS to build a website. I now want to embed a link with image into a paragraph. As I use the wagtail rich text editor I am wondering if there is any way to use inline html inside the rich text editor. Greetings -
IndexError at /user_upload/ (list index out of range for user model)
Even though the following code works, it throws the mentioned error. This is for importing data to user model. def user_upload(request): template = "client_admin/user_upload.html" data = User.objects.all() if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = User.objects.update_or_create( username=column[0], first_name=column[1], last_name=column[2], email=column[3], ) context = {} return render(request, template, context) and user model is class User(AbstractUser): is_approved = models.CharField(max_length=80, choices=APPROVAL_CHOICES, default='t-2') is_member = models.BooleanField(default=False) is_premium_member = models.BooleanField(default=False) -
How to use DRF OrderingFilter inside @action view?
I can't find information on how to use OrderingFilter from django rest framework inside ModelViewSet @action, does anyone know how would i implement that? I have categories and those categories have products that i get with that action, i want to order those products with a query string. Basically i would need to know how to use it on a queryset, but i cant find any info about that. Example url: http://example.com/categories/2/get_products/?ordering=price And here is the code, thanks for any help. class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer @action(detail=True) def get_products(self, request, pk=None): categories = Category.objects.get(id=pk).get_descendants( include_self=True).values_list('product_type__id', flat=True) products = Product.objects.filter( product_type__id__in=list(categories) ) paginator = ProductPagination() paginated_products = paginator.paginate_queryset(products, request) serializer = ProductSerializer( paginated_products, many=True, context={'request': request}) return paginator.get_paginated_response(serializer.data) -
Problem while changing input value through jquery and django?
Here I have the many values but in the input values only one value(last) will be placed. I want to display all the values in the input. How can I do this ? Example. I have values like this [10,12,13,14] but in the input only one value changes. I want to place all these values in my html input value. I think I need some changes in my script. I want to do something like this. $("#input").val(data.name); views.py def attribute_values(request): attribute = Attribute.objects.get(pk=request.GET.get('pk')) values = list(attribute.attributevalues_set.all()) serializer_values = serializers.serialize('json', values) data = { 'values': serializer_values } return JsonResponse(data, safe=False) script $("#select").change(function () { var attribute_pk = $(this).val(); console.log(attribute_pk) $.ajax({ url: ' {% url 'attribute_values' %}', data: { 'pk': attribute_pk }, dataType: 'json', success: function(data) { var values = data.values; data = $.parseJSON(values); console.log(data) $.each(data, function (index, el) { var name = el.fields.name; $("#input").val(name); }) } }); }); -
adding multiple image in django model
I am trying to add multiple images to a django model, it works in admin but i am completely blank on how to show it on my template. here is what i tried, it doesn't give any error but the image doesn't show. models.py class Export_Trade_Data(models.Model): country = models.ForeignKey( BannerandInformation, on_delete=models.CASCADE, null=True) # country_name = models.CharField('Country Name', max_length=100, default='') trade_text = models.TextField('Text for Trade Data', null=True) # date added date_added = models.DateTimeField('Date Updated', auto_now=True) def __str__(self): return "Export Trade Data" class ExportImage(models.Model): country = models.ForeignKey( BannerandInformation, on_delete=models.CASCADE, null=True) export_trade_data = models.ForeignKey(Export_Trade_Data, on_delete=models.CASCADE) export_sample_image = models.ImageField( 'Export Sample Image', upload_to='country', null=True) def __str__(self): return "Export Trade Data" views.py def country(request, country): exch_val = '' banners = BannerandInformation.objects.filter(country=country) for b in banners: country_name = b exch_r = b.exch_rate exch_cur = exch_r.split("/")[0] ######Export_Trade_Data Model####### etrds = Export_Trade_Data.objects.filter(country_id=ct_id) ######ExportImage Model####### expics = ExportImage.objects.filter(country_id=ct_id) for s in expics: etd_pic = s.export_sample_image content = { "etrds": etrds, "etd_pic": etd_pic, } return render(request, 'country/country-page.html', content) country-page.html <tbody> {% for expics in etrds %} <tr> <img src="/country/{{expics.export_sample_image}}" height="604px" width="527px" alt=""> </tr> {% endfor %} </tbody>