Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django check if Checkbox is selected before submit
i have a little struggle with my checkbox in Django. So the main Problem is how can i check if at least one Button is selected before submit. My idea is like, if no Button is selected but you press submit, then it pops up a little notification with "Please selecte at least one button". cheers for your your help. the 4 buttons: <form method="post" action="{% url 'qrseite' %}"> {% csrf_token %} <input type="checkbox" id="colaControl" name="getranke" value="cola"/> <label for="colaControl"><div class="cola" style="border-radius: 10px;"> <img src="{% static 'img/cola_img.png' %}" width="155" height="auto"> </div></label> <input type="checkbox" id="spriteControl" name="getranke" value="sprite"/> <label for="spriteControl"><div class="sprite" style="border-radius: 10px;"> <img src="{% static 'img/sprite_img.png' %}" width="120" height="auto"> </div></label> <div style="clear:both;"></div> <input type="checkbox" id="fantaControl" name="getranke" value="fanta"/> <label for="fantaControl"><div class="fanta" style="border-radius: 10px;"> <img src="{% static 'img/fanta_img.png' %}" width="110" height="auto"> </div></label> <input type="checkbox" id="pepsiControl" name="getranke" value="pepsi"/> <label for="pepsiControl"><div class="pepsi" style="border-radius: 10px;"> <img src="{% static 'img/pepsi_img.png' %}" width="120" height="auto"> </div></label> <div style="clear:both;"></div> <input type="submit" id="submitControl"> <label for="submitControl"><div class="accept_Button" style="border-radius: 10px;"> Bestätigung <img src="{% static 'img/qrcode_img.png' %}" width="50" height="auto" style="margin-top: "> </div></a> </label> </form> -
Object of type type is not JSON serializable in django
Getting this error when calling get all: Exception Type: TypeError Exception Value: Object of type type is not JSON serializable Exception Location: /usr/lib/python3.7/json/encoder.py in default, line 179 Python Executable: /usr/bin/python My models: class Source(models.Model): name = models.CharField(max_length=50) class SourceDefinition(models.Model): source = models.ForeignKey(Source, on_delete=models.DO_NOTHING) o_id = models.IntegerField a_group = models.CharField(max_length=50) creator = models.CharField(max_length=100) config = JSONField(default=dict) My serializers: class SourceSerializer(serializers.ModelSerializer): class Meta: model = Source fields = ['name'] class SourceDefinitionSerializer(serializers.ModelSerializer): source = SourceSerializer(read_only=True, many=False) class Meta: model = SourceDefinition fields = ['source', 'o_id', 'a_group', 'creator', 'config'] My view I'm accessing: class SourceDefinitionList(generics.ListCreateAPIView): queryset = SourceDefinition.objects.all() serializer_class = SourceDefinitionSerializer What am I missing? It's something to do with the serializer.. I'm trying to access the endpoint for SourceDefinition not Source -
Django taggit - Django-autocomplete-light set up error
I am trying to set up django-autocomplete light for my django-taggit. But I am getting an error: in filter_choices_to_render self.choices.queryset = self.choices.queryset.filter( AttributeError: 'list' object has no attribute 'queryset' In my autocomplete_light_registery.py in my app called home I have: import autocomplete_light from taggit.models import Tag autocomplete_light.register(Tag) in my home/views.py I have: class PostAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Tag.objects.none() qs = Tag.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs and in my home/forms.py I have: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','content','tags',) widgets = { 'tags': autocomplete.ModelSelect2(url='home:post-autocomplete') } I tried to follow the documentation but I do not know what seems to be the issue. -
create object and bulk upload data into django model
New to django.. I have a webrequest from where I am able to get the response back in json format. I created the view where I mapped the fields manually to each object and then used .save method by looping through the records. Example: for item in response: dataload = My_model( person_name = get("person_name",None) ) dataload.save() however this is taking a lot of time, since my data has many columns and rows around(100k)..Hence I wanted to create the object and then do a bulk load.. Example: for item in response: dataobj = my_model.objects.create( person_name = get("person_name",None) ) _models += (dataobj,) my_model.objects.bulk_create(_models) however this is giving me an error "ORA-00001: unique constraint violated" and I believe this is due to the autogenerated id not getting created in the bulk upload process.. Can any expert please help me to fix this and load data faster to the django model. Thank you -
Add a manger to FlatPage model in Django
I'd like to extend the FlatPage model in Django so that I can implement searching within its field. That's what I've done: models.py: from django.db.models import Q from django.contrib.flatpages.models import FlatPage class FlatPageManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = (Q(title__icontains=query) | Q(content__icontains=query) ) qs = qs.filter(or_lookup).distinct() return qs class MyFlatPage(FlatPage): objects = FlatPageManager() views.py: class SearchView(ListView): [...] def get_context_data(self, *args, **kwargs): context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: flatpage_results = MyFlatPage.objects.search(query) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) return qs The above search method works for other models I have, so it should also work for MyFlatPage. Nevertheless, I get no results coming from that query. Am I missing something? -
Image is not coming up properly
I'm working on a little e-commerce site. when I post a product from my site, the image(picture) doesn't show but when I post from the admin panel, the image shows so I don't why. I need help on this please. This is the code. The code below is from the model.py class OrderedItem(models.Model): name = models.CharField(max_length=50) price = models.FloatField() image = models.ImageField(upload_to='pics') def __str__(self): return self.name The code below is from the views.py def additem(request): if request.method == 'POST': stock_name = request.POST['stock_name'] stock_price = request.POST['stock_price'] stock_image = request.POST['stock_image'] new_item = Stock(stock_name=stock_name, stock_price=stock_price, stock_image=stock_image) new_item.save() return redirect('/') else: return render(request, 'post.html') the code below is from the html page <form action="{% url 'additem' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" name="stock_name" id="" placeholder="stock_name"> </div> <div class="form-group"> <input type="text" name="stock_price" id="" placeholder="stock_price"> </div> <div class="form-group"> <input type="file" name="stock_image"> </div> <div class="form-group"> <input type="submit" value="Additem" class="btn btn-primary btn-lg"> </div> </form> -
Reset password link on Django website not working
I have a django website. It has sign up and login functionality for users. It's currently hosted on digital ocean. I am using the gmail smtp server to send mails from the contact form and for reset password. But the reset link sent in the email is not working. When I'm running the localhost, the link works but not when hosted on digitalocean. What could be wrong? Here is my urls.py file's code: from django.contrib import admin from django.urls import path, include from django.conf.urls import url from profiles import views from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.shortcuts import render from detail.views import user_login as login_view from detail.views import user_logout as logout_view def administrator(request): return render(request, 'admin_index.html') urlpatterns = [ path('admin/', admin.site.urls), path('', include('profiles.urls')), path('administrator/', administrator), path('', include('detail.urls')), path('accounts/', include('django.contrib.auth.urls')), path('login', login_view, name='user_login'), # Password reset links (ref: https://github.com/django/django/blob/master/django/contrib/auth/views.py) # ------------------- password change paths ------------- path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'), name='password_change_complete'), path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change.html'), name='password_change'), # ------------------- password reset paths ------------- path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html'), name='password_reset'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The password change part also works fine. Thanks -
LookupError: App 'Hierarchy' doesn't have a 'CustomUser' model
I've been following the Django documentation to create a custom user model. Here is the main error - LookupError: App 'Hierarchy' doesn't have a 'CustomUser' model. I have defined it in my models.py from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager) from django.contrib.auth.admin import UserAdmin class CustomUser(AbstractBaseUser): #I proceeded to create the User details here I also added it correctly as the AUTH_USER_MODEL using - AUTH_USER_MODEL = 'Hierarchy.CustomUser' -
AttributeError: 'NoneType' object has no attribute 'answer' when try to get the latest record with Q filter
>>> from rabbit.models import TrackBot >>> from django.db.models import Q >>> latest_send = TrackBot.objects.filter(~Q(sender=110069554021986) & Q(is_postback=True)) >>> latest_send <QuerySet [<TrackBot: 4d0f034b-f067-4c83-a0f1-92624439c880>]> >>> latest_send.sender Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'sender' >>> How to get the field value ? -
Cant retrieve form data with ajax post request in django
I am trying to retrieve form data {orderId, email} in views.py from a ajax post request. I have used the csrf_token. But the variables get None in httpResponse. Below is the views.py code: @csrf_exempt def track(request): if request.method == 'POST': orderId = request.POST.get('order_id') email = request.POST.get('email') return HttpResponse(f"{orderId} and {email}") Below is the ajax post request: $('#trackerForm').submit(function(event){ event.preventDefault(); $('#items').empty(); var formData = { 'order_id': $('input[name=order_id]').val(), 'email': $('input[name=email]').val(), 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), encode: true }; $.ajax({ type: 'POST', url: '/shop/track/', data: 'formData' }) .done(function(data){ console.log(formData); console.log(data); }) }); I am getting the output of console.log(formData). But I am not getting the out of console.log(data) {the response from views.py} it shows on console screen as " None and None" , which means orderId and email have values None. Please respond to it. It will be a great help. -
Django how to use variable in paramiko function
I've designed django app which is getting variable from user and save it to db sqllite according to session id. My purpose is i want to get this variable and use it in paramiko ssh functions.How can i achieve this also if we think that more than one user will be connected? I made it with global variable but as i know its not recommended.In that case how can i be sure if i used right session-id data? def submit(request): global vlan_Name Session_ID=request.session.session_key vlan_Name = Variable_Settings.objects.get(Session_ID="xxxxxxxx") if request.method == "POST": SSH_FW_Send() return redirect("/final") def SSH_FW_Send(): remote.send("conf t\n") remote.send("name " + vlan_Name +"\n") -
Django modelformset_factory - how to save multiple records with javascript
I have two buttons "Add" and "remove" they are working fine, i can add and remove forms but the problem is when it comes to submit the forms that i have added it only save the first row in the database. Can any one help please! Here are my codes! view.py def create_purchase(request): OrderItemFormset = modelformset_factory(OrderItem, form=OrderItemForm) formset = OrderItemFormset(queryset=OrderItem.objects.none()) if request.method == "POST": form1 = OrderDetailForm(request.POST or None) formset = OrderItemFormset(request.POST, request.FILES, prefix='orderitem') if form1.is_valid() and formset.is_valid(): orderdetail = form1.save() items = formset.save(commit=False) for item in items: item.order_no = orderdetail item.save() messages.success(request, 'Successfully Saved!', 'alert-success') return redirect('v_purchase') else: context = { 'form1':form1, 'formset':formset } return render(request, 'managepurchase/create_purchase.html', context) else: form1 = OrderDetailForm() formset = OrderItemFormset(queryset=OrderItem.objects.none(), prefix='orderitem') context = { 'form1':form1, 'formset':formset } return render(request, 'managepurchase/create_purchase.html', context) Template <table id="id_forms_table" border="0" cellpadding="10" cellspacing="0" style="width:100%"> <thead> <tr> <th scope="col" class="text-info">Product</th> <th scope="col" class="text-info">Quantity</th> <th scope="col" class="text-info">Buying Price</th> <th scope="col" class="text-info">Amount</th> <th scope="col" class="text-info"></th> </tr> </thead> <tbody> {{ formset.management_form }} {% for form in formset %} <tr id="{{ form.prefix }}-row" class="dynamic-form"> <td>{{ form.product }}</td> <td>{{ form.quantity }}</td> <td>{{ form.buying_price }}</td> <td>{{ form.amount }}</td> <td> <a id="remove-{{ form.prefix }}-row" href="javascript:void(0)" class="delete-row btn btn-info btn-sm" style="color:white"><i class="fas fa-minus"></i></a> </td> </tr> {% endfor %} <tr> … -
How to pass context from views.py to templates
I would like to make a like-dislike function for a post. The codes below work well for the PostDetail(ListView) but not working for the blog/home.html at all. May I know how to fix that? Also, I have made the self.total_likes.count() in the model of Post but I don't know how to pass it to the templates with numerous attempts. This is the views.py: def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect(post.get_absolute_url()) This is also in the views.py: def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context=context) class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class PostDetailView(DetailView): model = Post is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context This is the models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes', blank=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) … -
Difference between Django postgres JSON field vs. noSQL
I have a Django-React stack using REST API as the bridge. Ideally, my frontend can adopt a fairly deeply nested JSON structure for storing user inputs. My questions are: What is the main difference between applying a JSONfield in Django Postgres, VS. having to construct a separate noSQL database via e.g. Djongo? I believe the first option works properly incl. API, queries etc. (after prelim. testing). I then became confused about WHY we even need a noSQL database in the first place (within the Django context of course), or at least all the fuss about Djongo/Mongoengine etc. I would have just gone with the first option as it apparently works fine, but I'd still like to clarify the concept in case I missed out any potential catastrophic behaviour... Sorry in advance if this seems ignorant, as I am completely new to web dev. Thanks! -
"ModuleNotFoundError("No module named 'MySQLdb'",)" when deploying a OpenLiteSpeed django solution on GCP
I'm testing Google Cloud Platform, where I've deployed a OpenLiteSpeed Django solution with a Ubuntu VM on Google Compute Engine. When it's deployed, everything works like a charm, and I'm able to reach the "Hello, world" starting page. When I try to add my own simple script by changing the views.py file in /usr/local/lsws/Example/html/demo/app to: import MySQLdb from django.shortcuts import render from django.http import HttpResponse def getFromDB(): data = [] db = MySQLdb.connect(host="ip", user="user", passwd="pw", db="db") cur = db.cursor() cur.execute("SELECT * FROM table") for student in students: data.append(student) return data def index(request): return HttpResponse(getFromDB) and access the IP again I'm met with the following traceback and error: Environment: Request Method: GET Request URL: http://ip/ Django Version: 3.0.3 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/core/handlers/base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/urls/resolvers.py", line 544, in resolve for pattern in self.url_patterns: File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = … -
invalid literal for int() with base 10: 'educationlevel_api'
why i receive this error? """ invalid literal for int() with base 10: 'educationlevel_api' """ ?? how can i configure this problem?? my Homepage/api/views.py @api_view(['GET', ]) def api_detail_educationlevel(request,slug): try: education = EducationLevel.objects.get(id=slug) except EducationLevel.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) if request.method == "GET": serializer = EducationLevelSerializer(education) return Response(serializer.data) Homepage/api/serializers.py class EducationLevelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = EducationLevel field = ('Sequence', 'Description', 'Status') my Homepage/api/urls.py urlpatterns = [ path('<slug>/', api_detail_educationlevel, name="detail"), ] my main urls.py urlpatterns = [ path('api/educationlevel/', include('Homepage.api.urls', 'educationlevel_api')), ] -
Ordering in serializer by using a variable
My variable inside a serializer MySerializer. I want to return it in descending order as per value of du. du = serializers.SerializerMethodField() def get_du(self, obj): modelname = Somemodel.objects.filter('id=id') du = sum(modelname.values_list('t', flat=True)) return du class Meta: model = Anothermodel fields = ('id', 'du' ) The model in APIView i.e Anothermodel and the model in serializermethod is different i.e Somemodel. Is there any other way to do this? My APIView def get(self, request): queryset = Anothermodel.objects.all() serializer = MySerializer(queryset, many=True) return Response({"organization": serializer.data}, status=status.HTTP_200_OK) Output now: { "du": 0, }, { "du" :12 } Expected: { "du": 12, }, { "du" :0 } -
Django overriding save method to save multiple objects at once
i need some help here. I'm trying to create multiple objects at once when saving in admin panel. But the problem is, only the last value in the loop is being saved. I tried setting the primary key to None class Seat(models.Model): seat = models.CharField(default='Seat', max_length=5, unique=True, primary_key=False) available = models.BooleanField() theater = models.ForeignKey(Theater, on_delete=models.CASCADE) def clean(self): if model.objects.count() >= self.theater.capacity: raise ValidationError(' - Maximum seats exceeded!') def save(self, *args, **kwargs): seats_name = [] row_label = [chr(letter) for letter in range(65, 91)] row_track = 0 row_range = 10 col_range = self.theater.capacity // row_range col_track = 0 for n in range(self.theater.capacity): row_track += 1 if row_track > row_range: row_track = 1 col_track += 1 display = "{} | {}-{}".format(self.theater, row_label[col_track], row_track) seats_name.append(display) for seat in seats_name: self.seat = seat super(Seat, self).save(*args, **kwargs) def __str__(self): return self.seat -
while connecting to MicrosoftSQL server using Django facing django.db.utils.OperationalError:
drivers available with me **python shell** '''In [2]: pyodbc.drivers()''' **Output:** **Out[2]: ['SQL Server']** code in settings.py django: **Settings.py in django** '''# Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dbname', 'HOST': 'ansqlserver.database.windows.net', 'USER': 'test', 'PASSWORD': 'Password', 'OPTIONS': { 'driver': 'SQL Server', } }''' **ERROR:** **Trying to connect to MicrsoftSQL server facing below error** File "C:\Local\Programs\Python\Python37\lib\site-packages\sql_server\pyodbc\base.py", line 314, in get_new_connectiontimeout=timeout) django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSNnor SERVER keyword supplied (0) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)') -
Emails Not Sending in Django
Before I explain my issue, I first want to clarify that I feel as though I've tried more or less every solution I've seen on Stack Overflow and none of them have worked for me. The issue I'm experiencing is that no emails are being sent when a user requests for a password reset. I'll add some details/context below. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get("EMAIL_ADDRESS") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_PASSWORD") I've added my email address and password into my env.py file and I have actually received a notification on my phone notifying me that someone is trying to access my account e.g. an email is trying to be sent from another source. I've also turned App Access on Google off. I'm lost for ideas at this point so any support would be greatly appreciated! -
How do I mock a function in Django?
I expect the following call to which_user to return self.user no matter what is passed into it but it's behaving as if it is not mocked at all. def test_user_can_retrieve_favs_using_impersonation(self): with mock.patch('impersonate.helpers.which_user', return_value=self.user): user = which_user(self.user2) What am I doing wrong here? I imported which_user like so: from impersonate.helpers import which_user if that helps. -
How to implement OAuth2 in Django with Google and Facebook auth by graphql authentication?
I am working on a Django project and I want to implement an authentication system which uses graphql api. The authentication should have an OAuth2.0 implementation bay email and password. It should also use social authentication options like Google and Facebook auth. Django allauth package is the most popular social authentication pakage but I don know how to implement it with graphql. -
View Wagtail pdf documents in new tab
I have tried following for opening Wagtail documents in view mode in new tab. Wagtail document links downloading instead of displaying as a page using wagtail hook: before_serve_method: nothing happens https://github.com/wagtail/wagtail/issues/4359#issuecomment-372815142 Remove "attachment" from response's Content-Disposition and "a href={row.url} target="_blank" rel="noopener">{row.title}" in jsx. opens the document in view mode(same tab) in Firefox and IE but not in Chrome? Not sure why browsers response is different and setting target="_blank" doesn't open in new tab for any browser. Setting attachment: False https://github.com/wagtail/wagtail/blob/cfc2bc8470ab16ddfc573e009e9aaf8c3d240fff/wagtail/utils/sendfile.py#L39 This clearly mentions: If attachment is True the content-disposition header will be set. This will typically prompt the user to download the file, rather than view it: Nothing happens. Firstly, if someone can help with "Remove "attachment" from response's Content-Disposition" approach on why Chrome still pop-up download and pdf's open in view mode in Firefox and IE? The next question is about "a href={row.url} target="_blank" rel="noopener">{row.title}" in jsx. Is there something wrong with this? I'm reloading webpack after change and cleared the cache. -
Django show static image based on model value
I have a DetailView in Django that gets the input from a model instance. I also have an images folder at the path static/images/nba_players containing a picture for each player in the format playername.jpg (ie; russellwestbrook.jpg) Now, say in the DetailView the model instance has the player attribute "Russell Westbrook." How can I get the HTML to find the picture for the player represented in the model instance? My initial thought is to strip the player name string of spaces and capital letters in views.py and pass it in as context data. But then I still don't know how in the HTML to reference that specific image. Any help would be great. -
how to set footer in pdf using python (django with pisa)
I tried to set footer on first page only by using pisa official documentation but it comes in all pages so please suggest how to apply footer on first page of pdf