Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrate bootstrap to Django doesn't show style
I'm trying to integrate this bootstrap https://startbootstrap.com/templates/shop-homepage/ to my e-commerce site https://github.com/Taiel-Kadar/myshop I have my Homepage divided in 3 files, base.html, detail.html, list.html, that inhertis from base.html. I'm strugguling like 3 days ago on how to integrate the bootstrap on that code, i've loaded the "HEAD" part of the index.html from the bootstrap to the base.html and modified the code. Then i omit the navbar. Next on the "Page content" part of the index.html i copy the code of the "/.col-lg-3" and paste it on "list.html" i tweak the code a little beat, and run it. No error is displayed, but the bootstrap its not loading and the page looks like sh#t. Without going further on especulation i dont know where should i place the Carousel, on the list.html or on the product.html, or I THINK i should do it on the base.html after <div id="content"> {% block content %} {% endblock content %} </div> And what about what is next of the carousel where the items go, that part i should integrate it on the list.html? I'm gonna let my base.html and list.html code here, and on the bottom i will put the code of the bootstrap index.html that … -
IPN is not received anymore
I have a problem with my IPN sandbox PayPal. A few days ago it sent the ipn after a test-purchase but since a few days ago it doesn’t sent them anymore. What can I do to fix that error? Kind regards, Saud Ahmed signals.py from django.shortcuts import get_object_or_404 from .models import CourierPayment from paypal.standard.ipn.signals import valid_ipn_received from django.dispatch import receiver @receiver(valid_ipn_received) def payment_notification(sender, **kwargs): ipn = sender if ipn.payment_status == 'Completed': # payment was successful payment = get_object_or_404(CourierPayment, id=ipn.invoice) if payment.price == ipn.mc_gross: # mark the order as paid payment.paid = True payment.save() apps.py from django.apps import AppConfig class CourierConfig(AppConfig): name = 'courier' def ready(self): # import signal handlers import courier.signals init.py default_app_config = 'courier.apps.CourierConfig' -
django.core.exceptions.FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted
Hi I am seeing this issue when I do: qs = ( self.get_queryset() .annotate( trigram = Greatest( TrigramSimilarity('username', search_text), TrigramSimilarity('first_name', search_text), TrigramSimilarity('last_name', search_text)) ).filter( Q(username__unaccent__trigram_similar=search_text) | Q(last_name__unaccent__trigram_similar=search_text) | Q(first_name__unaccent__trigram_similar=search_text), trigram__gte=0.3 ).order_by('-trigram') ) I have install pyscopg2 as well however, I do not know what's causing this issue? I have already added the unaccent extension as well to my database. But I still see this error Thanks in advance! -
Django "This field is required." in Postman
serializers.py class CardSerializer(serializers.ModelSerializer): image = serializers.CharField(read_only=True) class Meta: model = Card fields = ('id', 'template', 'data', 'MD5', 'image_md5', 'image', 'target_url', 'title', 'description', 'created', 'updated', 'createdBy') read_only_fields = ['MD5', 'image_md5', 'image', 'createdBy'] def create(self, validated_data): user = self.context.get('request').user if not user.id: raise ValidationError("Login Required") validated_data['createdBy'] = user return super(CardSerializer, self).create(validated_data) def update(self, instance, validated_data): new_ins = Card(**validated_data) md5 = new_ins.gen_md5() lookup = Card.objects.filter(MD5=md5).first() if lookup: return lookup return super(CardSerializer, self).update(instance, validated_data) postman enter image description here -
how can i add phone number field from class profile to class user?
i need to add phone number into my required models field , so Im do this, but is not working correctly so if every one knows how can i add Phone number , please help me: #models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from phonenumber_field.modelfields import PhoneNumberField class UserManager(BaseUserManager): def create_user(self, phone_number, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("User Must have an Email Address") if not password: raise ValueError("User Must have a Password") if not phone_number: raise ValueError("User Must have a Phone Number") user_obj = self.model(email=self.normalize_email(email)) user_obj.set_password(password) # change user password user_obj.phone_number(phonenumber_field) user_obj.staff = is_staff user_obj.active = is_active user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj # staff user def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, phone_number=PhoneNumberField, is_staff=True ) return user # admin user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, phone_number=PhoneNumberField, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) # full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) # can log in staff = models.BooleanField(default=False) # staff user non super user admin = models.BooleanField(default=False) # super user timestamp = models.DateTimeField(auto_now_add=True) phone_number = PhoneNumberField() USERNAME_FIELD = 'email' # username REQUIRED_FIELDS = [] # FULL_NAME object = UserManager() def __str__(self): … -
How to address the following error on a Django Project: "django.contrib.auth.models.DoesNotExist: Group matching query does not exist."
I am trying to run migrations on my django project and I'm getting this really bizarre error that I haven't been able to address for a while now, and I don't understand it. here's the error I'm getting: Anaconda3\envs\mbt\lib\site-packages\django\db\models\query.py", line 415, in get raise self.model.DoesNotExist( django.contrib.auth.models.DoesNotExist: Group matching query does not exist. I've tried to run python manage.py makemigrations python manage.py migrate auth python manage.py migrate my_app_name I've also inserted the group names directly into my postgresql database just in case they're not posting. This error is preventing me from running the server locally. I thought that the Group model was generated automatically and there wasn't much I needed to do to get started using it. It's definitely visible in my database. any help would be greatly appreciated! thank you!! -
Error in Connecting Multiple Database Django ( 'DatabaseOperations' object has no attribute 'geo_db_type' )
I am using multiple databases in Django, On the current server, PostGIS is installed and am trying to connect POSTGRESQL from another server, settings.py DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'db_name_1', 'USER': 'user_name_1', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, 'users_db' : { 'NAME' : 'db_name_2', 'ENGINE' : 'django.db.backends.postgresql_psycopg2', 'HOST' : '', 'PORT' : '', 'USER' : 'user_name_2', 'PASSWORD' : '', }, # 'users_db' : dj_database_url.config(default='postgres://user_name_2:password_2@host_2:0000/db_name_2') } Now as per documentation. Error python3 manage.py migrate --database='users_db' AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' UPDATE As per other StackOverflow pages, I found dj-database-url i used it but still problem persists. for dj-database-url 'users_db' : dj_database_url.config(default='postgres://user_name_2:password_2@host_2:0000/db_name_2') Any help will be appreciated, Thanks & Regards -
Django save object in foreign key field
I have two models order and date. The date model is associated with the order model with a foreign key. Whenever I fill the date form, the values get saved into the date model, not into the date field in order model . I have to manually assign the dates to an order. I wan tot function to automatically assign the dates to an order once I submit the form. models.pyclass Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) views.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.date = date_instance order.save() else: form = DateForm() … -
How to move an icon?
Code runs fine what am trying to get done is to move the Facebook icon on left of the screen instead of the middle of the screen how could I do that? import React from 'react'; import { Link } from 'react-router-dom'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faFacebook } from '@fortawesome/free-brands-svg-icons' function Header() { return ( <div> <header className="header"> <div className="col1"><FontAwesomeIcon icon={faFacebook}/></div> <div className="col2"> <div className="menu"> <Link to="/about"><h3>About</h3></Link> <Link to="/car"><h3>Cars</h3></Link> <Link to="/contact"><h3>Contact</h3></Link> <Link to="/search"><h3>Search</h3></Link> <nav/> </div> </div> </header> </div> ); } export default Header; -
Fieldsets with back-referencing other tables related to the User table
I have been working on this admin page where the admin can take a look at each customer's entrance of a specific endpoint. So far, I successfully created the list display where it shows how many times a customer visited this endpoint. Below is the screenshot: However, my client stipulates that the details of each visit must be recorded and shown on the admin's page (e.g. the time/date when the customer visited) So I created a separate table called "Count" with the foreignkey that points at the user like so: class User(AbstractBaseUser): email = models.EmailField( verbose_name='email', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) level = models.IntegerField(default=1) objects = UserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Count(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='counts') date_time = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'counts' The problem is when I try to show the date/time details of each visit on each customer's admin page. The admin.py looks like this so far: from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserChangeForm, UserCreationForm from .models import User, Count class … -
html value=" " not displaying
<div id="minus_vacancies"> <h4>Mínimo de vagas</h4> <div> <input type="button" id="decrease_btn" name="decrease_btn" value="-" onclick="subtractVacancies(this)"> </div> <div> <input id="vacancies_qtt" type="text" name="vacancies_qtt" value="0" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"> </div> <div> <input type="button" id="increase_btn" name="increase_btn" value="+" onclick="addVacancies(this)"> </div> </div> Hey! I am making a Decrement/Increment buttons with the value on the middle. The buttons work fine but I can´t see the number. Its not displaying the value="0" of the vacancies_qtt Why? Thanks in advance -
How to use template data in another Div
How do I use the value from {{ i.user.first_name }} in the value="{{ }}". Check lines with arrows. {% for i in searched_inf %} <div> <p>Result: <a href="{{ i.ig_link }}" target="_blank">IG link ========> for {{ i.user.first_name }} {{ i.user.last_name }}</a> <button onclick="myFunction()">Send Message</button> </p> </div> {% endfor %} <div id="msg" style="display: none"> <form action="" method="POST"> {% csrf_token %} <label>Send to:</label> ========> <input type="text" name="msg_receiver" value="{{ }}"> <br> <br> <label>Message:</label> <textarea name="msg_content" rows="4" cols="50"></textarea> <br> <br> <input type="submit" value="Submit"> </form> </div> -
Django passing CSS via the View?
I am struggling with the online service I use to print my PDF files when using my localhost. It will not load my css files with a static URL. They only link to a Http source. (I am fine with JS because I load with a CDN.) trying to find a workaround? Is it possible to pass the CSS file into the template via the context from the view? I was thinking something like: css_path = ( os.path.abspath ( os.path.join ( settings.APPS_DIR, 'static', 'css' ) ) ) p = os.path.join ( css_path , 'report.css' ) css = open (p, 'r') and then: context = { 'css': css, } template = "reports/sample.html" return render ( request, template, context ) I can not get it to show in proper format on the template. I just get: <_io.TextIOWrapper name='/Users/me/PycharmProjects/project/project/static/css/report.css' mode='r' encoding='UTF-8'> Or is this just a really stupid idea? (I am sure it is bad coding principals) Otherwise I just have to write all the lengthy CSS inside my page (and no scss) and that really blows. thanks. -
How template traversal is implemented
How to implement for i in range(5) with django template syntax? my code is: {% for i in range(5) %} but it is wrong! -
CSS Dropdown menu shows up as horizontal instead of vertical
I'm trying to develop a website using django and I'd like to add a navigation bar dropdown menu, but for some reason, it keeps showing up as horizontal, instead of vertical. I'm following the tutorial that W3 Schools has on their website https://www.w3schools.com/css/tryit.asp?filename=trycss_dropdown_button Despite all of my efforts it still doesn't work, I've tried to look at other questions, but most of them seem to be using a different method using lists, or their using a framework like react. I moved my project over to this jsfiddle.net and that just seemed to make the problem even worse, because now my second list item in the dropdown doesn't show up at all. Here is the code I'm working with http://jsfiddle.net/iggy12345/ao04gfne/4/ Here is the code pasted below: My html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <div class="header"> <a class="active" href="{% url 'home' %}">Home</a> <div class="dropdown"> <a href="/">Profile</a> <div class="dropdown-content"> <a href="{% url 'logout' %}">Logout</a> <a href="/">Customize Profile</a> </div> </div> </div> </body> </html> My css file: .dropdown { float: left; overflow: hidden; display: inline-block; } /* Dropdown content (hidden by default) */ .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); … -
Creating a unique (attribute) title in a Model
I have a blog project and users can create posts with similar titles, How can I prevent a user or even the admin from proceeding without getting an error that the title already exists so that I can avoid future errors in the website such as get() returned more than one Post-it returned 2! I have tried to use class meta for unique together but still, post was saved with the same title Here is the post model class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField(blank=True, null=True, max_length=120) def __str__(self): return self.title class Meta: unique_together = ('title', 'slug') -
Rendering several forms with helpers Crispy Django
I'm having an issue using several forms with django-crispy-forms for Django. From the documentation, we must set self.helper.form_tag = False in out Form. Documentation here Then wrapp the forms with a Form tag in the HTML. class SearchForm(forms.Form): X = forms.IntegerField(label='X', min_value=0, max_value=10) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.form_tag = False self.helper.layout = Layout( 'X', Submit('submit', 'Submit', css_class='btn-success') ) class PredictForm(forms.Form): Y = forms.IntegerField(label='X', min_value=0, max_value=10) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.form_tag = False self.helper.layout = Layout( 'Y', Submit('submit', 'Submit', css_class='btn-success') ) Then in the HTML file I have: <form action="my_action" class="uniForm" method="post"> <div id="box" class="box">{% crispy formSearch formSearch.helper %}</div> <div id="box2" class="box2">{% crispy formPrediction formPrediction.helper %}</div> </form> In my View.py: def index(request): if request.method == 'POST': formSearch = SearchForm(request.POST) formPrediction = PredictionForm(request.POST) # Do stuff else formSearch = SearchForm() formSearch.fields['X'].initial = 5 formPrediction = PredictionForm() formSearch.fields['Y'].initial = 5 return render(request, 'index.html', {'formSearch': formSearch}, 'formPrediction': formPrediction) What I get is 2 crispy forms that are displayed on my web page, but the first forms tries to load the fields of the seconds forms. It seems like my second form is duplicated. I get this error: KeyError: … -
Sending data to a url -
This is my html template {% for i in searched_inf %} <div> <p>Result: <a href="{{ i.ig_link }}" target="_blank">IG link for {{ i.user.first_name }} {{ i.user.last_name }}</a> <button> <a href="{% url 'messages' %}">Send a message</a> </button> </p> </div> {% endfor %} As you can see when the button is pressed, user is redirected to the messages url. I have a separate messages view to handle this url. I want to send data from this template. When the button is clicked, I want to send the i.user.first_name value, so that I can access it in the messages view. -
When the user list is displayed, I want the background color of the row to be sky blue for my favorite users.Is there an efficient way to do this?
I have a question ~! When the user list is displayed, I want the background color of the row to be sky blue for my favorite users. However, it is too inefficient to run the loop again for each row when printing the user model. Is there any good way to solve this? In other words, how can I make the background color of my favorite user row change when displaying the user list? Is there a good way to make the color of the rows of my favorite users different without doing too many queries? If there is such a way I would appreciate it if you let me know thanks Link <a class="nav-link" href="/wm/userlist/byajax">User List</a> below is related code url path('userlist/byajax', views.user_list_for_memo_view.as_view(), name = 'user_list_for_memo'), view class user_list_for_memo_view(ListView): paginate_by = 10 def get_template_names(self): if self.request.is_ajax(): return ['wm/_user_list_for_memo.html'] return ['wm/user_list_for_memo.html'] def get_queryset(self): query = self.request.GET.get('q') print("query : ", query) if query != None: object_list = User.objects.all().filter(Q(username__contains=query)).order_by('-profile__skill_note_reputation'); return object_list else: print("user list 출력 확인 ===========================================================") object_list = User.objects.all().filter(profile__public="yes").order_by('-profile__skill_note_reputation'); print("result : ", object_list) return object_list template (C:\django_inflearn2\wm\templates\wm_user_list_for_memo.html) {% load static %} {% if object_list.exists %} {% for u in object_list %} <tr> <td>{{u.id}}</td> <td id=user_name_{{u.id}}> <a href="/accounts/user_profile_information_view/{{u.username}}"> {{u.username}} </a </td> {% … -
Django multiprojects share some APP in one database with diferent Authentication
I am developing django projects which I will use as backend for mobile Apps, For that I need to have two django sites which run on different port, one is on port 8080 as API server and one is on port 80 as CMS server, but I need to share some apps between projects with different authentication per each projects and all projects will use same database (All projects need to use same tables in the database except table which is used for Authentication and Session). Is there any complete example settings for this case ? or better some step by step how to do it in right way ? I have read and learn this question, but I face problem for Authentication, Session and User (I think this is because both projects will use the same tables name for auth, session and user, even though I need to have different auth and user for both projects CMIIW). Every suggestion really appreciated. -
Django on Google Cloud: css files blocked due to MIME type mismatch
I'm attempting to set up a Django 3.0 API on a Google Cloud Flexible environment (using Gunicorn to serve). The API itself works but when I attempt to navigate the the Django admin page, all of the css files fail to load giving the error: The resource was blocked due to MIME type ("text/html") mismatch (X-Content-Type-Options: nosniff) I would like to change the MIME type rather than getting rid of nosniff but I haven't been able to find any documentation on how to do either. I will need to serve both css and js files. This is my first Django application so I'm not 100% sure what information will be helpful, but here is my settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = <redacted> DEBUG = True ALLOWED_HOSTS = [ '127.0.0.1', # For local deployment 'xxxxxxxxxxx.appspot.com' # Gcloud URL ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'drf_yasg', 'rest_framework', 'rest_framework.authtoken', 'django_nose', 'myapp', ] 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', ] ROOT_URLCONF = 'myapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myapp.wsgi.application' DATABASES = { <redacted> } AUTH_USER_MODEL = … -
Why is the Context of another Model not working in Template
I am have a project where Users have Items (for images) Posts (for articles) Which are 2 separate apps, in the Home template I have a list view of the items only and I am trying to include the Post as well Here is the model for the items (which is for images) : class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views.py class HomeView(ListView): model = Item template_name = "home.html" ordering = ['-timestamp'] Here is the Urls.py app_name = 'core' urlpatterns = [ path('', HomeView.as_view(), name='home'), I am trying to add the Context of Post so that I can include it in the HomeView Here is the model for posts (which is for articles) class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the urls.py app_name = 'score' urlpatterns = [ path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), What I am trying to do is in the Home page list the items and add a condition that if the user has a post the button appears and if the user has no posts it shows nothing. Here is the template home <a href="{% url 'core:designer-posts' item.designer.username %}"> <button style="margin-top: 10px;text-transform: none;" button type="button" class="btn btn-primary btn-sm … -
Django allauth - login now working after i18n implementation
Without making any change on the login code and just by implementing i18n on the whole application, my login forms stopped working. I can see the form in the template, I can fill the input, but either if I put correct or wrong credentials when I click on the button to log in it just seems to refresh the page and do not log in nor show error messages. The input fields are also empty. If I go to django admin and I log in with the default django admin login, it works fine and I can enter with my admin user. I checked the installation guide and the configuration steps two more times but there is nothing changed and everything seems to be on it's place. I tried updating from django allauth 0.42.0 to 0.43.0 but the problem is not solved. Everything works fine except the login. I have a custom login form, but as I said it was working fine. The only thing I do is modify the layout with crispy-forms: class CustomLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(CustomLoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) # Add magic stuff to redirect back. self.helper.layout.append( HTML( "{% if redirect_field_value %}" "<input type='hidden' … -
How to return a objects from a Django model based on date
I have a function in models.py below that I want to use to return a list of events whos dates are less than todays date (meaning they have not happend yet) and not return them if the date has passed and then display it in index.html with a for loop Index.html <!-- Events section --> <section class="container text-center"> <h1 class="section-title"><span class="st-span">Upcoming Events</span></h1> {% if events %} {% for event in events.get_upcoming_events %} <div class="row"> <div class="col-md-6"> <img class="card-img-top dropshadow" src="{% static 'core/images/banner/carousel-1.jpg' %}" alt="Event image"> </div> <div class="col-md-6 m-auto px-5"> <h4 class="card-title border-bottom pb-3"><strong>{{ event.title }}</strong></h4> <p class="card-text">{{ event.description|truncatechars:255 }}</p> <a class="btn btn-primary" href="{% url 'event-detail' event.title %}">View Event</a> </div> </div> {% endfor %} {% else %} <p>No events at the moment, please check back regulary for updates</p> {% endif %} </section> Models.py from django import forms from django.db import models from django.utils.timezone import now import datetime as dt class Event(models.Model): title = models.CharField(max_length=255) location = models.CharField(default='', max_length=255) description = models.TextField(default='') start_date = models.DateField(verbose_name='Start Date', default=now) start_time = models.TimeField(verbose_name='Start Time', default=now) end_date = models.DateField(verbose_name='End Date', default=now) end_time = models.TimeField(verbose_name='End Time', default=now) # add event image field def __str__(self): return f'{self.title}' def has_not_ended(date): if date < dt.date.today(): return False return True … -
Jinja TemplateSyntaxError with set
I have some Jinja HTML: {% for workout in workouts %} <div class="workout"> <h1>{{ workout.name }}</h1> <div class="tags"> <!-- TODO: Fix set error --> {% set tags = workout.tags.split(',') %} {% for tag in tags %} <p>{{ tag }}</p> {% endfor %} </div> <p> {{ workout.description }} </p> <div class="actions"> <button>Edit</button> <button>Start</button> </div> </div> {% endfor %} However, the set assignment is raising a TemplateSyntaxError. The error page says it's expecting a {% endfor %}. The docs seem to agree with what I wrote so I'm not sure where the error is coming from. Thanks!