Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get response data from long polling?
I do a long polling in Django (1.11). But I don’t understand why JsonResponse returns undefined values? ajax $('.txt_link > a').on('click', function() { $.ajax({ type: 'GET', url: '', success: function(data){ console.log(data.title) //undefined } }) }) view class ProviderCreateView(CreateView): form_class = ProviderForm template_name = 'provider_create.html' def form_valid(self, form): ... def get_context_data(self, **kwargs): ctx = super(ProviderCreateView, self).get_context_data(**kwargs) ctx['organizations'] = Organization.objects.filter(user=self.request.user) last_organization = Organization.objects.filter(user=self.request.user).first() if self.request.is_ajax(): while True: curr_organization = Organization.objects.filter(user=self.request.user).first() if last_organization != curr_organization: template_ajax = render_to_string( template_name='provider_create.html', context=ctx ) return JsonResponse({ 'success': True, 'template': template_ajax, 'pk': curr_organization.pk, 'title': curr_organization.title }) time.sleep(2) return ctx -
How to get users YT, Twitter likes into my website users database in Django
User log into my Django website account and the likes of videos( from yt)/tweets that have been approved by my website admin or with a certain hashtag are shown on my accounts as points. What are most points to consider: -while creating an account. -with API -Does user can connect YT and twitter accounts to account on my website? -If connecting user account with yt/twitter is difficult maybe an easier option would be manually confirming user yt/twitter username with email and than reading of likes from the videos or tweets with certain hashtags by playing up with API? Could you list main points or maybe libraries I can use from Django? As you can see the architecture is quite flexible. The main point is: how can I easily get those likes to my user account. Kind regards, ep -
mysqlclient 1.3.13 or newer is required; you have 0.9.3
I use vagrant, I created virtual machine and I'm trying to run my Django project on the vbox , i installed all of the requirements but i got this error django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. even i have installed mysqlclient 1.4 -
django custom user model user creation issue: permissions not working
I'm making a custom user model in django, but somehow any new users created through the creation form is missing their assigned permissions (is_active, is_staff, is_admin), preventing them from logging in at all. Can anyone show me where did I go wrong? Any suggestion is greatly appreciated! Code snippets: models.py class MyUserManager(BaseUserManager): use_in_migrations = True def create_user(self, ID, name, email, privilege, password=None): if not ID: raise ValueError('Users must have a ID number') user = self.model( ID=ID, name=name, email=self.normalize_email(email), privilege=privilege, ) if self.privilege == 'Admin': self.is_superuser = True else: user.is_active = True user.is_staff = False user.is_admin = False user.set_password(password) user.save(using=self._db) return user def create_superuser(self, NIP, name, email, privilege, password): new_user = self.create_user( ID, name, email, privilege, password=password, ) new_user.is_superuser = True new_user.save(using=self._db) return new_user class employee(AbstractBaseUser, PermissionsMixin): ID = models.IntegerField(verbose_name="ID", unique=True) name = models.CharField(verbose_name="Name", max_length=50, blank=True, unique=True) email = models.EmailField(verbose_name="email", max_length=225, default='this@mail.com') Department = models.CharField(max_length=50, choices=DEP_CHOICES, default='') Role = models.CharField(max_length=50, choices=ROLE_CHOICES, default='') privilege = models.CharField(max_length=10, default='User') is_admin = models.BooleanField() is_staff = models.BooleanField() is_active = models.BooleanField() forms.py class CustomUserCreationForm(UserCreationForm): ID = forms.CharField(max_length=50) password = forms.CharField(widget=forms.PasswordInput) class Meta(UserCreationForm): model = employee fields = "__all__" class CustomUserChangeForm(UserChangeForm): ID = forms.CharField(max_length=50) password = forms.CharField(widget=forms.PasswordInput) class Meta: model = employee fields = "__all__" admin.py class UserAdmin(BaseUserAdmin): … -
How to combine values filter with a Queryset of a certain Foreignkey field on my Django Model
I have this field in my model: class PlayerDetailPage(Page): picture = models.ForeignKey('wagtailimages.Image', null=True, on_delete=models.SET_NULL, related_name='+', help_text=_('Player profile picture.')) And I want to create a inclusion tag, where I access different fields on this Wagtail page model. For db efficiency I use values but on the picture field I want the full query set. Not just a value in a dictionary because I need to render the image. Right now I have this view: PlayerDetailPage.objects.values('title', 'path' , 'slug', 'owner__age', 'owner__nationality', ) So far so good, I am pulling only the fields I need and I get a nice dictionary with one query. However for the picture field I want the full query set because it is a Wagtail picture field. It has some nice render options attached. How can I combine this in my view to get the best db efficient query? -
how to extend admin permission to my code
can you please help me to extend my admin permission to my code? I have created a model to add events, and have setup user group and list of users in django admin workspace. I have also setup some permission to the individual groups. It works very well in django admin, but I do not know how to execute the same permissions in the backend. For example, I have setup a user in a group which has no right to view the event, but that user is still able to view it in the actual website. I think I have much carry out and additional step to extend this permission to my actual code. Can you please help. -
How to draw Pie chart in html djnago using dictionary data from view.py
I am trying to draw pie chart in django app using javascript where data for pie chart comes from views.py as a dictionary. For example my data is like: city['Mumbai'] = 2141 city['New Delhi'] = 5471 I need to draw pie chart which has two fields and will look like this :- Piechart -
How to replace Choices field in Django ModelForm with TextInput
I am working with Python 3.7.3 and Django 2.0.13. Basically I want to show a form on my website, on which a user (=participant in model definition below) can be entered. The Django ModelForm makes this to a Choice Field automatically and shows a Dropdown with all users. I don't want to show a list of all users in the dropdown menu and want a TextInput field instead. Code: First, relevant part from models.py: class Invite(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) host = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "invites_as_host") participant = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "invites_as_participant") accepted = models.BooleanField(blank = True, default = False) declined = models.BooleanField(blank = True, default = False) date_created = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) class Meta: unique_together = ["game", "host", "participant"] forms.py: class GameInviteNewForm(forms.ModelForm): class Meta: model = Invite fields = ["participant"] What I tried is to overwrite the participant input field like this: class GameInviteNewForm(forms.ModelForm): participant = forms.CharField( label=_("User to invite"), max_length=100, widget = forms.TextInput ) class Meta: model = Invite fields = ["participant"] This does indeed show an TextInput Field on the website, but if I enter a username ("test") I get an error: Internal Server Error: /app/game/invite/7 Traceback (most recent call last): File "/home/dremet/anaconda3/envs/django/lib/python3.7/site-packages/django/core/handlers/exception.py", line … -
can I get the sum of the total_price from transaction table to display in portfolio.I have tried annotate and aggregate but neither work for me
I'm trying to display the sum value of total_price to my portfolio.html. Is this possible. If so what am i doing wrong? I have tried annotation and aggregation but cant seem to get the correct results Function Below def portfolio(request): context = { 'transactions': Transaction.objects.filter(owner=request.user).values('currency').annotate( sum_amount_purchased=Sum('amount'), sum_total_price_purchased=Sum('total_price'), sum_amount_sold=Sum('sales__amount_sold'), sum_amount_current=F("sum_amount_purchased") - F("sum_amount_sold"), avg_amount_per_coin=Avg("amount_per_coin"), sum_total_price_current=ExpressionWrapper(F("sum_amount_current")*F("avg_amount_per_coin"), output_field=DecimalField()), sum_total_income=Sum('sales__total_price_sold'), sum_profit_loss=F("sum_total_price_current") + F("sum_total_income") - F("sum_total_price_purchased"), ), 'total_values': Transaction.objects.filter(owner=request.user).aggregate( total_spends=Sum('total_price') ) } return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'}) Transaction model below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) loop in html below <div class = "col-md-6"> {% for total_value in total_values %} <h1> Total Spent: {{ total_value.total_spends }}</h1> {% endfor %} </div> -
How to hide or show fields in Django form depending on the selected category?
I make a real estate agency website. When adding a new listing, I need to hide or show fields depending on the selected category. This my listing: For example, when I select houses and land, the Landmark field should be hidden, and when I select Apartments, this field should appear. I know that this is done using JS, but could you at least throw some example of how this is done. Listing model: class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риелтор') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область') city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город') district = models.ForeignKey(District, on_delete=models.CASCADE, verbose_name='Район') title = models.CharField(max_length=200, verbose_name='Заголовок') landmark = models.CharField(blank=True, max_length=200, verbose_name='Ориентир') ... def __str__(self): return self.title Category model: class Category(models.Model): name = models.CharField(max_length=100, verbose_name='Название') slug = models.SlugField(blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('category_view', kwargs={'category_slug': self.slug}) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def pre_save_category_slug(sender, instance, *args, **kwargs): if not instance.slug: slug = slugify(translit(str(instance.name), reversed=True)) instance.slug = slug pre_save.connect(pre_save_category_slug, sender=Category) views.py @login_required def listing_add(request): logos = Logo.objects.all() feedbacks = Feedback.objects.all() categories = Category.objects.all() form = ListingForm() if request.method == "POST": form = ListingForm(request.POST, request.FILES) if form.is_valid(): listing = form.save(commit=False) listing.realtor = request.user.realtor listing.save() return redirect('dashboard') return render(request, 'listings/listing_add.html', { 'logos': … -
Django Admin: How to show and hide fields on the basis of an app?
Here is the current scenario: I have a model Transaction in the app "payment" I want to add paypal_xyz_field in that model Transaction, once the new app payment_paypal is being installed. ie: Extend Transaction in app paypal and add field paypal_xyz_field What will be the approach? If I will extend the Transaction model then I will have to show both paypalTransaction and Transaction in the admin. In admin, I want to show only one model "Transaction" with paypal_xyz_field, paymill_xyz_field, stripe_xyz_field not paypalTransaction, stripeTransaction etc. Also, want to auto add/remove the field from DB/admin on the basis of apps -
Django) How to inquire field of another model in ManyToMany relationship
I want to inquire data field from model which contains another model in ManyToMany relationship. For instance, I want to calculate total cost from Dinner model, which has ManyToMany relationship with Menu model. Here goes simplified code. class Menu(models.Model): cost = models.IntegerField() class Dinner(models.Model): menus = models.ManyToManyField(Menu) objects = DinnerManager() class DinnerManager(models.Manager): def get_total_cost(self): total_cost = 0 for each_menu in self.menus.all(): total_cost += each_menu.cost return total_cost So my question is this: how should I set for each_menu in self.menus.all(): total_cost += each_menu.cost these two lines to get my class method work? (or if other parts is wrong, please let me know. I'm fairly new to django..) -
UNIQUE constraint failed: auth_user.username while updating user info
I am trying to give a user the option to change his/her first/last name through a ModelForm. When I press submit, I get hit with the UNIQUE constraint failed: auth_user.username error. Here are my codes: students/forms.py: class EditProfileForm(UserChangeForm): def clean_password(self): # Overriding the default method because I dont want user to change # password pass class Meta: model = User fields = ( 'first_name', 'last_name', ) students/views.py: class ChangeNameView(SuccessMessageMixin, UpdateView): template_name = 'students/edit_profile.html' model = User form_class = EditProfileForm success_message = "Your name has been updated" def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): form.instance.student_profile = StudentProfile.objects.get(slug=request.user.student_profile.slug) return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): """If the form is valid, save the associated model.""" form.instance.username = self.request.user self.object = form.save(commit=False) return super().form_valid(form) def get_success_url(self): return reverse('students:student_profile_view', kwargs={'slug': self.object.student_profile.slug}) also fyi, User model is foreign key with StudentProfile. students/models.py: class StudentProfile(models.Model): user = models.OneToOneField(User, related_name='student_profile', on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True) description = models.CharField(max_length=120, null=True, blank=True) objects = models.Manager() def __str__(self): return self.user.username def get_absolute_url(self): return reverse("students:student_profile_view", kwargs={"slug": self.slug}) I am pretty new to class based view so maybe I'm doing something wrong there? -
Tinymce adds new line when encountering <p> tag
I am currently writing a JS code in Tinymce HTML editor var des = content.match("<p>(.*)</p>")[1]; var link = content.match("<a(.*)</a>"); but the tinmyce editor is adding newline when it encounters a tag below is how its shows in HTML editor var des = content.match(" (.*) ")[1]; var link = content.match("<a(.*)"); This is my Tinymce config TINYMCE_DEFAULT_CONFIG = { 'theme': "advanced", 'width': '80%', 'height': 800, 'valid_elements': '*[*]', 'force_br_newlines' : False, 'force_p_newlines' : False, 'forced_root_block': '' } because of the forced new line,I am unable to get the entire code in one variable, it throws error How do I solve it ? -
Django odd behaviour with Q objects and `and_` (vs `and`)
I have been trying to dynamically construct list of filters based on some function arguments. I build a list of predicates using Q objects and finally I construct one predicate with: filters = [] ... some code appending Q objects to filters ... combined_filter = reduce(and_, filters) Then I query my database objects with: MyModel.objects.filter(combined_filter) I have noticed a bit odd behaviour when I try to combine Q objects with operator.and_. For example comparing output of: items = Item.objects.filter(and_(is_metal, ~is_wood)) print([i.name for i in items]) items = Item.objects.filter(is_metal and ~is_wood) print([i.name for i in items]) items = Item.objects.filter(is_metal, ~is_wood) print([i.name for i in items]) I get: ['Table', 'Container'] ['Container'] ['Table', 'Container'] What is the reason for different behaviour between and_ and and? My expected output is to get just ['Container'] (see below for full example, "Container" is the only thing with only "metal" as material, "Table" should be excluded because it also has "wood"). Followup question would be: how do I get behaviour of and when using reduce? My django version is 2.0.7 I have reproduced that exact problem on https://repl.it/repls/AgonizingBossyEfficiency In case above link dies all code I've modified is below: models.py: from django.db import models class Material(models.Model): name … -
Server returns 502 Bad Gateway after switching to gunicorn socket as systemd service
I try to setup gunicorn socket for django application and nginx server using it as systemd service. However afrter running guncicorn.socket service nginx server return 502 Bad Gateway. After restarting gunicorn.service and checking its status it's alive but and socket file is in /run/gunicorn diercotory buy after using curl --unix-socket /run/gunicorn/socket http --trace-ascii dump.txt it returns == Info: Rebuilt URL to: http/ == Info: Trying /run/gunicorn/socket... == Info: Connected to http (/run/gunicorn/socket) port 80 (#0) => Send header, 68 bytes (0x44) 0000: GET / HTTP/1.1 0010: Host: http 001c: User-Agent: curl/7.47.0 0035: Accept: */* 0042: == Info: Recv failure: Połączenie zerwane przez drugą stronę == Info: Closing connection 0 curl: (56) Recv failure: Połączenie zerwane przez drugą stronę after that socket file disappears and next message is hesmeron@hesmeron-All-Series:/etc/systemd/system$ curl --unix- socket /run/gunicorn/socket http --trace-ascii dump.txt == Info: Rebuilt URL to: http/ == Info: Trying /run/gunicorn/socket... == Info: Immediate connect fail for /run/gunicorn/socket: Nie ma takiego pliku ani katalogu == Info: Closing connection 0 curl: (7) Couldn't connect to server And here is gunicorn.service traceback ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: failed (Result: service-start-limit-hit) since nie 2019-04-28 15:30:19 CEST; 1h 58min ago Listen: /run/gunicorn/socket … -
What is the difference between `assertIn` and `assertContains` in Django?
I am studying some Django testing codes and I find assertIn and assertContains quite similar, I read the documentation wherein they didn't say anything about assertIn or maybe I couldn't find it. This example below checks if 'john' appears at the content of self.email.body self.assertIn('john', self.email.body) similary this example checks if csrfmiddlewaretoken appears at content of self.response self.assertContains(self.response, 'csrfmiddlewaretoken') Looks like there syntax is different, but there functionality is the same. Hence, what is the difference? If you could kindly help me understand this with some basic examples, I would really appreciate it. Thank you so much -
How to set up django debug toolbar along with static files and media files in URLs (DJANGO 2.0)
How can i set up django debug toolbar when using django static files and media files Below is my configuration in urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) elif settings.DEBUG: urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), I am not sure whether the line with 'elif' is the right way to do it. (The web app crashes when i try to launch it in dev) -
Searching with multiple values in django
I want to create simple search in Django. I want to find all objects in which any word from keywords array is in meme.title or meme.author or meme.tags, and user.request is meme.user. from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Meme(models.Model): user = models.ForeignKey(User, on_delete='CASCADE') title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True, max_length=1000) author = models.CharField(max_length=100) page_link = models.TextField(blank=True, max_length=500) img_link = models.TextField(max_length=1000) tags = models.CharField(max_length=100) def __str__(self): return self.title For example if I have keywords = ['funny', 'old', 'black_humor'] and current user is XYZ I want to find all memes that have that meme.user field is XYZ and title, author or tags contains any word from keywords. -
Can I set max_value in sales form amount_sold to be a property coins_remaining from transaction view?
I'm creating a crypto-currency application. In my app a user can have many transactions and a transaction can consist of many sales. I have a form for entering sales and I'm trying to put the max_value constraint equal to a property (coins_remaining) in the transaction table. Is it possible to do this? If so how would I go about it? Sale Form Below class SaleForm(forms.ModelForm): amount_sold = forms.IntegerField(min_value=0.1, label='Enter number of coins sold ', error_messages={'min_value': 'You must enter some coins '} ) total_price_sold = forms.DecimalField() date_sold = forms.DateField( label='Enter Date of Sale ', help_text='Please use calendar by clicking arrow on the right ', widget=forms.TextInput( attrs={'type': 'date'} ) ) note = forms.CharField(label='Write a note below ', widget=forms.TextInput(attrs={'placeholder': 'Keep a Note? '})) class Meta: model = Sale fields = ('date_sold', 'amount_sold', 'total_price_sold', 'note') Transaction Model Below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) @property def coins_remaining(self): return self.amount - sum(self.sales.all().values_list('amount_sold', flat=True)) Sale Model Below class Sale(models.Model): amount_sold … -
Stylesheet formatting not working in Django project
I have a HTML file which links stylesheets as follows: <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="css/owl.carousel.css"> <link rel="stylesheet" href="css/owl.theme.default.min.css"> index.html is at the root of the project so when I open it the page is formatted as expected. I tried to copy this css code to my Django project. I placed the css folder in the project root. The above html code is in templates/base.html and I run python manage.py runserver from the project root. When I do this the formatting doesn't work. I tried things like href="css/bootstrap.min.css" and even /full/path/to/css/bootstrap.min.css but they didn't work. I also tried <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> which does work. How do I correctly reference stylesheets that are in a Django project folder? -
How to show column from another table in list_display without foreign key relation?
I have these database relationships: Now in my admin.py in the list_display I want to display the orders table plus the quantity row from order_items. To do so, I would use this sql query: select order_id, quantity from orders inner join order_items on orders.order_id = order_items.order_id; Now I don't know how to do this in the correct way with django without using a raw query. So what do I add in the line list_display = ('order_id') in order to show the quantity row? -
$.each only the last element is shown
I'm trying to filter a list with AJAX, I have an issue where the html only shows the last element. I have read a lot of similar SO questions and to no avail. I have variables, so I don't know whats the issue. $("#programme").change(function () { event.preventDefault(); var selected_programme = $(this).val(); $.ajax({ url: '{% url "gps_list" %}', data: { "selected_programme": selected_programme, }, dataType: 'json', success: function(response) { var json = $.parseJSON(response); $.each( json, function( key, values ) { var valname = values.fields.name; var valco = values.fields.country; var valpro = values.fields.programme_type; var valwhat = values.fields.what; console.log(valname, key); console.log(valco); console.log(valpro); console.log(valwhat); $("#names").html(valname); $("#country").html(valco); $("#pro_types").html(valpro); $("#whats").html(valwhat); }); }, error: function(response) { alert("oh no!"); } }); }); -
Problems with {% include %} function in django
Would like to include the 'newest_feature.html' contents: {% for feat in newest_feature %} <p>{{ feat.name }}</p> {% endfor %} into feature.html: {% include 'newest_feature.html' %} Got my views: def newest_feature(request): newest_feature = Feature.objects.filter(published=True).order_by('- date_posted')[0:1] return render(request, 'newest_feature.html', {'newest_feature': newest_feature}) and contexts: def newest_feature(request): return render_to_response('newest_feature.html') my settings: TEMPLATES = [ ... 'OPTIONS' : { 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'products.contexts.newest_feature', Problem is. If I use only views and newest_feature it displays perfectly on newesfeature link. But when I try to include it just using same views it displays HTML tags, but nothing in {{}}. So tried to create context processor, but it drops an error. Any ideas what could be wrong? Thank you! -
How to fix Python template tags for calling variables in HTML page, like {{ my_name }}
I created a variable in my python script. I want to display the value of this variable on my page. So I passed the variable to a dictionary and call the key on my HTML file. However, when I refresh my page it does not show any error and yet the value too does not show. I am new to python, I do not know what the problem could be. Please is there any way to enable this template tag {{ }} before use? Like so: Python function from django.shortcuts import render def about(request): my_name = 'Hello! My name is Andi@ITech' return render(request, 'about.html', {"my_name":my_name}) HTML File {% extends 'base.html' %} {% block title %} About Andi@ITech {% endblock %} {% block content%} <a href="{% url 'home' %}">Home</a> | <a href="{% url 'about' %}">About</a> <br><br> <em>About Me</em> <br> {% if 2 > 21 %} Halo! {% else %} GOODBYE {% endif %} <br> {{ my_name }} <-- this line of code does not show anything --> {% endblock %} I expected the following sentence to display on my page : Hello! My name is Andi@ITech.