Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cant add a django tag {% csrf_token %} to html created using format_html. The tag keeps returning as plain text
i have a table column as follows actioncolumn = tables.Column(verbose_name="action",orderable=False,empty_values=[]) def render_actioncolumn(self): edit_btn=''\ ' edit '\ '' delete_btn=''\ 'delete'\ '' return format_html('{{% csrf_token %}} ' + edit_btn +' '+ delete_btn + ' ') the tag {% csrf_token %} reurns as plain text. the extra curlies in {{% csrf_token %}} are to work around the special charcters used in strings -
Which filter is better and faster
I am relatively new to django and python, so i would really like to know which of these two implementation is the better or faster approach. I am currently using the filter, but i thought of it, and cos i really like list comprehension, i wrote the same code using list comprehension. Both codes do exactly the same thing, but I just want to know from developers with more experience which is better and why. Below are both codes. posts = Post.objects.filter(approved=True).order_by('-date_posted') posts = [post for post in Post.objects.all().order_by('-date_posted') if post.approved] -
How to add or remove quantity cart django and also in templates?
Views.py def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/home.html", {"cart": cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Expired product") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) request.session['cart_items'] = cart_obj.products.count() return redirect("cart:home") models.py class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True)enter code here products = models.ManyToManyField(CartItem, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=65, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=65, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': products = instance.products.all() total = 0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal = total instance.save() m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through) def pre_save_cart_receiver(sender, instance, *args, **kwargs): if instance.subtotal > 0: instance.total = … -
Can I create a table user to make login in the web with differents attributes as the table user in admin in django?
I want to create a table called Professor for example, which could have attributes DNI, pets, parents, for example, and allow them to make the login to application. -
What is the best approach for installing python + django + postgis (geodjango) in docker?
I would appreciate if anyone could share their strategy and perhaps code for dockerfile and docker-compose to successfully create a container which will run django with postgis. More specifically: What image are you based on? What image did you use for postgres-postgis? What dependencies did you install as prerequisites for the various python packages and postgis? Specifically how did you install GDAL? What commands did you run in psql? Thanks in advance! -
Django: how to access all posts from a specific user
I am working on a project and I am a beginner in Django. I am trying to get all the product posts from specific user and then show them. What I want to do is the user which is logged in can see product posts created by himself. But my template syntax seem to have an error. This is the code I am using to get all the product posts. <section class="page-section bg-light mb-0"> <div class="container"> {% for product in products.all if product.creator.username == 'naveen' %} {% endfor %} </div> </section> For checking purposes I am using a user by 'naveen' but later on I will show it by user who is logged in. The error it is showing me is: TemplateSyntaxError at / 'for' statements should use the format 'for x in y': for product in products.all if product.creator.username == 'naveen' -
Got AttributeError when attempting to get a value for field `addrs` on serializer `EmployeeSerializer`
Can someone please help me to how to write this program? using pthon 3 and django 3 I'm getting this error The serializer field might be named incorrectly and not match any attribute or key on the Employee instance. Original exception text was: 'Employee' object has no attribute 'addrs'. This is my models.py file class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) salary = models.IntegerField() location = models.CharField(max_length=100) def __str__(self): return self.name class Address(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) place = models.CharField(max_length=50) city = models.CharField(max_length=50) dist = models.CharField(max_length=50) state = models.CharField(max_length=50) def __str__(self): return self.place This is my serializers.py file class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): addrs = AddressSerializer(required=True) class Meta: model = Employee fields = ['name', 'position', 'salary', 'location', 'addrs'] This is my views.py file class EmployeeView(APIView): def get(self, request): employee = Employee.objects.all() serializer = EmployeeSerializer(employee, many=True) return Response(serializer.data) def post(self, request): serializer = EmployeeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class EmployeeViewId(APIView): def get_object(self, id): try: return Employee.objects.get(id=id) except Employee.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def get(self, request, id): employee = self.get_object(id) serializer = EmployeeSerializer(employee) return Response(serializer.data) def put(self, request, id): employee = self.get_object(id) serializer = EmployeeSerializer(employee, data=request.data) if serializer.is_valid(): serializer.save() return … -
Django freeze when use Form
Django freeze when I try to render a form. This is my forms.py: from django.forms import ModelForm from .models import Evento class EventoForm(ModelForm): class Meta: model = Evento fields = ['codreserva','fecha','incidencia','descripcion'] And this is my model: class Evento(models.Model): codreserva = models.ForeignKey(Reserva, on_delete=models.CASCADE, verbose_name='Cod. Reserva') fecha = models.DateTimeField(verbose_name='Fecha') incidencia = models.ForeignKey(Incidencia, on_delete=models.CASCADE, verbose_name='Incidencia', null=True, blank=True) descripcion = models.TextField(null=True, blank=True) usuario = models.ForeignKey(User, on_delete=models.PROTECT) activo = models.BooleanField(default=True, verbose_name='Activo') fechacierre = models.DateTimeField(verbose_name='Fecha cierre', null=True, blank=True) Just doing this: e = EventoForm() e.as_table() Django freeze for minutes, and stop webbrowser Debugging, I can see it stop in boundfields.py. My Django version is 2.2.12 an Python 3.8 and I try with diferent browser. -
Using the django-embed-video to make blog posts
I am new to Python and am trying to make a music style blog where one can post YouTube videos, Soundclound links etc. using the Django admin page. I have tried using the URLfield model but it doesn't seem to work. I then found django-embed-video, but have only managed to get it to work as a separate model. models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from embed_video.fields import EmbedVideoField class Item(models.Model): video = EmbedVideoField() # same like models.URLField() def __str__(self): return self.video class Post(models.Model): title = models.CharField(max_length=100) url = models.URLField(max_length=500, default='') # same like models.URLField() content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post from embed_video.admin import AdminVideoMixin from .models import Item admin.site.register(Post) class ItemAdmin(AdminVideoMixin, admin.ModelAdmin): pass admin.site.register(Item, ItemAdmin) home.html template {% extends "blog/base.html" %} {% load embed_video_tags %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <iframe src="{{ post.url }}"></iframe> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} … -
Django Allauth Login with Amazon extra fields
I've added Allauth with Amazon provider to my Django website for better and fast login. I obtain similar information: { "user_id": "amznl.account.K2LI23KL2LK2", "email":"mhashimoto-04@plaxo.com", "name" :"Mork Hashimoto", } The library the "name" in fist_name and last_name with a workaround, and ok, but i need also more information as prefer/last/almost one shipping address and more.. what I can obtain it? Here there are some information to make it, but I haven't understood well (Amazon docs). I try to explicit in settings.py just for test : SOCIALACCOUNT_PROVIDERS = { 'amazon': { 'SCOPE': "profile" } } But if I try to make a Login I receive: GET /accounts/amazon/login/callback/?error_description=An+unknown+scope+was+requested&state=2uIPayVsbkFp&error=invalid_scope HTTP/1.1" 200 55965 Without SOCIALACCOUNT_PROVIDERS, work but I receive only three informations... -
How to validate many to many field objects before insert into database in django model
I have model "cart" and it has a many to many field named "products". I wanna check if there is a product in products that is not active, prevent from creating the cart object class Product(models.Model): price = models.PositiveIntegerField(blank=True) active = models.BooleanField(default=True) objects = ProductQuerySet.as_manager() class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="cart") products = models.ManyToManyField(Product, blank=True) subtotal = models.IntegerField(default=0, blank=True) objects = CartManager.as_manager() -
Update Post clicking on a button: Django
Hope someone can help me! I'm pretty sure that there's a little error I can't detect. In my website I've got a list of items with an update button. Once i click on the button I keep having this error about the url: Reverse for 'edit_info' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['search/(?P<slug>[-\\w]+)/edit/$'] Am I missing something maybe on the urls.py file? Here's the code, Thanks a lot! views.py def edit_info(request, slug): instance = get_object_or_404(Info, slug=slug) if request.method == 'POST': form = InfoForm(request.POST, instance=obj) if form.is_valid(): instance = form.save(commit=False) instance.utente = request.user instance.save() return render(request, 'search/user.html') else: form = InfoForm(instance=obj) template = 'search/option.html' context = {'form': form} return render (request, template, context) urls.py urlpatterns = [ path('', homeView.as_view(), name='home'), path('option/', views.AddInfo, name='option'), path('delete/<int:id>', views.DeleteInfo, name='delete'), re_path(r'^search/(?P<slug>[-\w]+)/edit/$', views.edit_info, name='edit_info'), path('signup/', core_views.signup, name='signup'), path('user/', userListView.as_view(), name='user'), path('searches/', searchesView.as_view(), name='searches'), ] template html: <div class="info_band"> <!-- insert table info --> <table> <tr><th><h3>{{o.band}}</h3></th></tr> <tr><td> Anno: </td><td> {{o.anno}} </td></tr> <tr><td> Disco: </td><td> {{o.disco}} </td></tr> <tr><td> Etichetta: </td><td> {{o.etichetta_d}} </td></tr> <tr><td> Matrice: </td><td> {{o.matrice}} </td></tr> </table> </div> <div class="mod"> <table> <tr> <td> <a href="{% url 'edit_info' slug=instance.slug %}"><button type="button" class=" btn btn-default"> Update </button></a> </td> </tr> <tr> <td> <button>Delete</button> </td> </tr> </table> … -
For nginx, am I listening to port 443 or port 3000 for this url https://localhost:3000?
I am trying to navigate through the weeds of nginx and reverse proxy passing and one area that I am getting confused on is the port mappings. Here is an example nginx configuration file: server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name www.domain.com; passenger_enabled on; root /home/ubuntu/app/public; include snippets/self-signed.conf; include snippets/ssl-params.conf; } What I am specifying here is that my app should listen to port 443 because it has a self signed certificate on it. It won't accept port 80 http but only 443. Here is an example I found about proxy_passing to localhost. Which is what I want to do. Here is the example: server { listen 443; server_name localhost; ssl on; ssl_certificate server.crt; ssl_certificate_key server.key; ssl_session_timeout 5m; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Client-Verify SUCCESS; proxy_set_header X-Client-DN $ssl_client_s_dn; proxy_set_header X-SSL-Subject $ssl_client_s_dn; proxy_set_header X-SSL-Issuer $ssl_client_i_dn; proxy_read_timeout 1800; proxy_connect_timeout 1800; } } Here is what I don't understand and could use some clarification. What port/url am I listening to in the second example? In the server block I see this: listen 443; server_name localhost; That means we are … -
Keeping track of non registered user in a django website
I'm making a django website and want to keep record of the people who didn't registered in my website like what all they searched in my website and all.For that what should I do to get all that information?? -
Dajngo: refreshing page resubmit last form
I have a view like: def some_view(request, page_url): form = UserTicketForm(request.POST) if request.method == 'POST': if form.is_valid(): first_name = request.POST.get('first_name') ticket_text = request.POST.get('ticket_text') data = dict( form=UserTicketForm, ) return render(request, 'front/some_page.html', data) and in HTML page it has: {% csrf_token %} {% bootstrap_form form %} {% block submit %} <div class="button_holder"> <button type="submit" name="register-submit" class="btn btn-primary" value="send"> submit </button> </div> {% endblock %} each time I refresh the page, it resubmits the last submitted form. how can fix this issue? -
Adding Items to cart
whenever am trying to add items to cart it is not showing in cart.No errors are there template also working fine but http://127.0.0.1:8000/admin/ecom/orderitem/ in this items are not showing. I am trying to solve this from three days but it is not working. This is views from django.shortcuts import render, get_object_or_404, redirect from .models import Item, Checkout, Order, Orderitem from django.urls import reverse_lazy from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView class CheckoutEditView( CreateView ) : model = Checkout template_name = 'checkedit.html' fields = '__all__' success_url = reverse_lazy('blank') def item_list(request): context = { 'items':Item.objects.all() } return render(request,'item_list.html',context) class CheckListView(ListView): model = Checkout template_name = 'blank.html' def check2(request): return render(request,'ckeck2.html') def front(request): return render(request,'front.html') def blank(request): return render(request,'blank.html') def product(request): return render(request,'product-page.html') def checkout(request): return render(request,'checkout-page.html') def home(request): return render(request,'home.html') class ArticleDetailView(DetailView): model = Item template_name = 'home.html' context_object_name = 'batman' def home_page(request): return render(request,'home-page.html') def add_to_cart(request,slug): item = get_object_or_404(Item,slug=slug) order_item = Orderitem.objects.create(item=item) order_qs = Order.objects.filter(user=request.user,ordered = False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity +=1 order_item.save() else: order = Order.objects.create(user=request.user) order.items.add(order_item) return redirect("core:article_page",slug=slug) whenever am trying to add items to cart it is not showing in cart.No errors are there template also working fine but http://127.0.0.1:8000/admin/ecom/orderitem/ in this … -
Permission issue in custom user model in django
I am trying to create a custom user model in my Django application. In my app user_app i have added the below code in my models.py : from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class RestrauntManager(BaseUserManager): def create_user(self, username, email, phone, restraunt_name, is_staff=False, is_admin=False, is_active=True, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have a username') if not password: raise ValueError('User must have a password') if not phone: raise ValueError('User must have a phone number') if not restraunt_name: raise ValueError('User must have a restraunt name') user = self.model( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name ) user.set_password(password) user.staff = is_staff user.active = is_active user.admin = is_admin user.save(using=self._db) return user def create_staffuser(self, email, username, phone, restraunt_name, password=None): user = self.create_user( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name, is_staff = True ) return user def create_superuser(self, email, username, phone, restraunt_name, password=None): user = self.create_user( email = self.normalize_email(email), username = username, phone = phone, restraunt_name = restraunt_name, password = password, is_staff = True, is_admin = True ) user.save(using=self._db) return user class Restraunt(PermissionsMixin, AbstractBaseUser): email = models.EmailField(verbose_name = 'email', max_length=60, unique=True) username … -
Read a select option on Django
I am attempting to get the value of the data from the select option which will actively decide what will be displayed on the same page. I need to get the child.id value and was wondering if there is a way to find this data without having to create a whole new page. <select id="child"> {% for cl in children %} {% if cl.parent == user %} <option value="{{child.id}}">{{ cl.first_name }} {{ cl.last_name }}</option> {% endif %} {% endfor %} </select> -
ajax call to submit data form in django RESTFRAMEWORK
I am trying to make a POST request to Mayan EDMS(a Django app to store documents), through an API to upload a document, but each time I try to submit the form I get a permission denied error. here is an HTML form with a file field and other fields, HTML form <form method="POST" id="DocForm" enctype="multipart/form-data"> {% csrf_token %} <textarea name="description"></textarea> <input type="file" /> <select class="form-control" name="document_type"> <option value="1">Default</option> </select> <button>POST</button> </form> this function get csrf token from a form ajax/js code to get csrf token ////getting crsf token /////////////////////////////////// // function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // test that a given url is a same-origin URL // url could be relative or scheme relative or absolute var host = document.location.host; // host … -
Django rest framework, imitate the Django admin behavior when using Foreign Key
I have a Django rest framework API model that contains a foreign key field. I want to show the user In the browsable API a kind of dropdown menu to choose existing objects or create a new one just like in the admin interface, Is there something like this existing? The models: class Mission(models.Model): id = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) mission_name = models.CharField(name='MissionName', verbose_name="Mission Name", unique=True, max_length=255, blank=False, help_text="Enter the mission's name", primary_key=True ) uav_lat = models.FloatField(name="UavLatitude", verbose_name="UAV Latitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) uav_lon = models.FloatField(name="UavLongitude", verbose_name="UAV Longitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) uav_elevation = models.FloatField(name="UavElevation", verbose_name="UAV Elevation", max_length=100, default=1, blank=False, help_text="Enter the above ~Sea Level~ planned uav Elevation. " ) area = models.CharField( name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(verbose_name="Date Added", default=now()) gdt = models.ForeignKey(KnownLocation, on_delete=models.PROTECT) class Meta: get_latest_by = 'date_added' KnownLocation model: class KnownLocation(models.Model): name = models.CharField(name="Name", unique=False, primary_key=True, max_length=150, blank=False, help_text="Enter the name of the location's name") area = models.CharField(name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(default=timezone.now) latitude = models.FloatField(name="Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="Longitude", unique=True, max_length=255, blank=False, … -
Django REST serializer with multiple foreign keys
Hi everybody and good morning. My application is a sort of 'repository manager', able to list, search and create datasets of files. I have a models.py like the following: class Author(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) email = models.EmailField() phone = models.CharField(max_length=20, blank=True) # optional def __str__(self): return self.name class Dataset(models.Model): name = models.CharField(max_length=150) # dataset title description = models.TextField(blank=True) # dataset description --> optional slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) remote = models.URLField(max_length=300) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(str(self.author.pk) + "-" + str(self.name)) super(Dataset, self).save(*args, **kwargs) class File(models.Model): creator = models.ForeignKey(Author, related_name='author', on_delete=models.CASCADE) # the original creator of the file dataset = models.ForeignKey(Dataset, related_name='dataset', on_delete=models.CASCADE) # dataset to which belongs name = models.CharField(max_length=100) # file name with path description = models.CharField(max_length=300, blank=True) # file description --> optional url = models.URLField(max_length=300) # hot link to file def __str__(self): return self.name So I am working with nested serializers. The creation of an object Dataset is working in this way: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('name', 'surname', 'email', 'phone') class FileSerializer(serializers.ModelSerializer): creator = AuthorSerializer(required=False) class Meta: model = File fields = ('name', 'description', 'url', 'creator') class DatasetSerializer(serializers.ModelSerializer): author = AuthorSerializer() … -
How to chain custom methods of subclass of Django QuerySet so that types match
Consider following example code: class MyQuerySet(models.QuerySet): def my_method(self): return self.annotate(_something=47) def my_method_2(self): return self.annotate(_something2=42) def second_method(self): return self.my_method().my_method2() Problem is that PyCharms type checker highlights my_method2() call ("Unresolved attribute reference 'my_method2' for class 'QuerySet'"). I could disable warning inside IDE on case-by-case basis, but type-checker is right, types do not match. (I don't even understand why such code works, I suppose methods like filter and annotate preserve these attributes.) Is there some clean way to change returned values to MyQuerySet? Or are there any type hints that would make type-checker happy? (Setting return type of my_method to MyQuerySet only moves the problem.) -
Importing external library (say pytube) in Django
Fairly new to Django. I am trying to import Pytube to my django project. I am on my virtual environment and installed pytube va Pip. How to I import it. not working the way like 'from Pytube import Youtube' -
How to filter queryset data with exact matching word?
I am creating one Django project, here I define some fields like: class Data1(models.Model): message = models.TextField() and making input word in msg variable msg = "hello" I want to filter all message field strings in which the msg variable exists. when I am using list_data = Data1.objects.filter(message__icontains=msg).all() it's not giving me desire output is there any way to filter query objects with exact word match in strings. -
App linking to root instead of actual application on redirect
I'm having some trouble working with paths in Django. I have python experience but not Django experience at all. Here is what I have templates/AppName/base.html <header id="header"> <div id="logo"> <div id="top_menu"> Home | Calendar | About | <a href="/contactus">Contact Us</a> </div> </div> </header> template/AppName/contact_us.html {% extends 'Orchestrator/base.html' %} {% block content %} <h2>New post</h2> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} AppName/urls.py from django.urls import path from . import views app_name = 'AppName' urlpatterns = [ path('', views.index, name='index'), path('contactus/', views.contact_us, name='contactus') ] AppName/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .forms import ContactUs def index(request): return render(request, 'AppName/base.html') # Forms # def contact_us(request): form = ContactUs() return render(request, 'AppName/contact_us.html', {'form': form}) AppName/forms.py from django import forms class ContactUs(forms.Form): firstname = forms.CharField(max_length=100) lastname = forms.CharField(max_length=100) So, the rendering of the starting page, meaning 127.0.0.1:8000/AppName Works just fine, but when I want to make the Contact Us button redirect to AppName/contactus, Django is actually redirecting to 127.0.0.1/contactus. Any idea on how to solve this?