Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework using Viewsets with different renderers
does it make sense to use Django Rest Framework also to render my HTML Code with Bootstrap and so on...? If no, what is the best solution to split the API endpoints and HTML view? I exposed an API with DRF Viewsets and JSON serializers. It's working pretty well. Additionally I would like to add a HTML rendered version of this API and design a HTML form for it. Both API and HTML rendered version are supposed to run on the same machine. Thanks in advance -
Getting not not a valid UUID when I migrate in Django
I added a field called transaction_id in my models.py I want that field to be used to track every transaction on my DuesLevy model I imported uuid for this to happen, but each time I migrate I get this error. How do i prevent this error from occurring each time I migrate (python manage.py migrate) "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\fields\__init__.py", line 2344, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["'13615773708697' is not a valid UUID."] This issue have been reported Here but seems no solution yet. I am using Django 3 + MySQL models.py trans_id = uuid.uuid4() trans_str = trans_id.int pass_trans = str(trans_str)[:12] class DuesLevy(models.Model): class_of_dues = models.CharField(max_length=30, default=options.CHOOSE, choices=options.CLASS_OF_DUES, blank=True) payment_circle = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CIRCLE) payment_option = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_OPTION) amount = models.DecimalField(max_digits=8, decimal_places=2) transaction_id = models.UUIDField(max_length=100, unique=True, null=True, blank=True, editable=False, default=pass_trans) payment_channel = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CHANNEL_TYPE) payment_date = models.DateField() date_recorded = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField(blank=True, null=True) def __str__(self): return self.amount def get_absolute_url(self): return reverse('backend:detail_dues', kwargs={'pk': self.id}) -
How to implement Behaviour driven development (BDD) in Django rest framework?
My current company is planing to switch to behaviour driven development also known as BDD. After a long google search I came to the conclusion that behave is the semi official python package for BDD in python. I am wondering how could we practically implement BDD along with drf. What is the correct ideal way to Structure our test files. Where should we keep the BDD feature, step files? Which category would add fall under, unit testing, integration testing or acceptance testing? Thanks Ref : https://behave.readthedocs.io/en/latest/ -
Unable to redirect user to login page after registration using the redirect funtion in django
I am trying to redirect user to login page after registration and i am getting the Reverse for login not found error accounts/urls.py from django.urls import path,include from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), path('articles/', include('articles.urls')), path('accounts/', include('users.urls')), path('admin/', admin.site.urls), ] users/urls.py from . import views app_name = 'users' urlpatterns = [ path('register/', views.register, name='register'), path('login/', views.login, name='login'), ] views.py def register(request): form = RegisterForm() if request.method == 'POST': form = RegisterForm(request.POST) print(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was create for ' + user) return redirect('login') return render(request, 'register.html', {'form': form}) The error i got NoReverseMatch at /accounts/register/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. -
Dropdown menus inside the Django admin
I have a project foreign key in by Phase model. I'm having hard time Create a dependent drop-down list inside my Django admin page. I want to when user select a project from (project drop-down) phase of that project show in second dop-down What would be the best way to achieve this? It would be great if the dropdowns filter items based on the value of its parent. class Project(models.Model): name = models.CharFieldmax_length = 100, unique= True) short_name = models.CharField(max_length= 4, unique= True) slug = models.SlugField(max_length= 100, allow_unicode=True, null=True, editable= False) location = models.OneToOneField(Location, on_delete = models.SET_NULL, null= True, blank= False, verbose_name= 'موقعیت') start_date = models.DateField(default= timezone.now, null= True, blank= True) end_date = models.DateField(default= timezone.now, null= True, blank= True) duration = models.IntegerField(default= 0, editable= False) class Phase(models.Model): title = models.CharField(max_length= 20) class ProjectPhase(models.Model): project = models.ForeignKey(Project, on_delete= models.CASCADE, related_name= 'phase') phase = models.ForeignKey(Phase, on_delete=models.CASCADE, related_name= 'project') start_date = models.DateField(default= timezone.now) end_date = models.DateField(default= timezone.now) duration = models.IntegerField(default= 0, editable= True) -
Failed building wheel for python-ldap on centos8 and python 3.8.2
I am trying to install djang-auth-ldap on centos 8 with python3.8 on venv pip 20.1 from /home/centos/***/python38/lib/python3.8/site-packages/pip (python 3.8) ip install django-auth-ldap Collecting django-auth-ldap Using cached django_auth_ldap-2.1.1-py3-none-any.whl (20 kB) Requirement already satisfied: Django>=1.11 in ./***/python38/lib/python3.8/site-packages (from django-auth-ldap) (3.0.5) Collecting python-ldap>=3.1 Using cached python-ldap-3.2.0.tar.gz (367 kB) Requirement already satisfied: pytz in ./***/python38/lib/python3.8/site-packages (from Django>=1.11->django-auth-ldap) (2020.1) Requirement already satisfied: asgiref~=3.2 in ./***/python38/lib/python3.8/site-packages (from Django>=1.11->django-auth-ldap) (3.2.7) Requirement already satisfied: sqlparse>=0.2.2 in ./***/python38/lib/python3.8/site-packages (from Django>=1.11->django-auth-ldap) (0.3.1) Requirement already satisfied: pyasn1>=0.3.7 in ./***/python38/lib/python3.8/site-packages (from python-ldap>=3.1->django-auth-ldap) (0.4.8) Requirement already satisfied: pyasn1_modules>=0.1.5 in ./***/python38/lib/python3.8/site-packages (from python-ldap>=3.1->django-auth-ldap) (0.2.8) Building wheels for collected packages: python-ldap Building wheel for python-ldap (setup.py) ... error ERROR: Command errored out with exit status 1: how can I fix it? I have to use this package for exists project. can you help me please? thanks -
Table 'login' does not exists in database
I don't know why i am getting this problem now.It was working fine before,did i made some mistake at codes or so?Table exists in database Note: I use djongo (Mongodb) for database class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField( verbose_name='email address', max_length=255, unique=True ) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Meta: db_table = "login" -
How to take in user input in a Django website for internationalization?
I can translate my site but I am confused how to to translate my site in the language my user wants it to be. Should I make a form and take the input to change the language variable in my settings file? -
Why is Django migration not migrating table?
My django migration is not working properly. Out of three models I altered one model(table) in the initial version of my app and ran the makemigrations and then the migration command but the migration for that particular table did not happen properly so I thought there was some problem with the app. I deleted the table from the database and also created a new app and copied all the code from the first app to this one (including the code in the models, views, etc.). But when I use the migration commands, I still do not see the table in the database. The commands I use are python manage.py makemigrations python manage.py migrate Can anyone please help? -
Starting Dev Server for Django on windows
I installed Python 3.7, it was added to Path during installation, Then installed Django using the command "pip install django" and it got installed. I started a new project with the command "django-admin startproject pyshop ." and it created that folder with some .py files in it. Then I tried to run the dev server with the command "py manage.py runserver" and I get the response "Unable to create process using 'C:\Users\Prince M\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver'" in my terminal. What can I do to fix this because this is what I am supposed to do even according to the django documentation. -
ManytoMany objects access in template django
There are 2 objects with a many-to-many relationship, trying to access one in the template through the other and an error POPs up: NoReverseMatch at /decision/livingrooms/kitchen/provans/ Reverse for 'style' with keyword arguments '{'rmslg': 'bathroom', 'stslg': ''}' not found. 1 pattern(s) tried: ['decision/livingrooms/(?P<rmslg>[-a-zA-Z0-9_]+)/(?P<stslg>[-a-zA-Z0-9_]+)/$'] But bathroom styles is not empty html: {% for room in all_rooms %} <li class="menu__item menu__item_interiors"><a href="{% url 'decision:style' rmslg=room.slug stslg=room.styles.slug|first %}">{{ room.name }}</a></li> {% endfor %} -
Django 3 TemplateSyntaxError: 'css/bootstrap.min.css' is not a registered tag library
I added bootstrap.min.css to my simple Django v3 project. So my home.html is something like so: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Boards</title> <link rel="stylesheet" href="{% load static '/css/bootstrap.min.css' %}"> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> <il class="breadcrumb-item active">Boards</il> </ol> <table class="table"> <thead class="thead-dark"> <tr> <th>Boards</th> <th>Posts</th> <th>Topics</th> <th>Last Post</th> </tr> </thead> <tbody> {% for each in boardlist %} <tr> <td> {{ each.name }} <small class="text_muted d-block">{{ each.description }}</small> </td> <td class="allign-middle">0</td> <td class="allign-middle">0</td> <td></td> </tr> {% endfor %} </tbody> </table> </div> </body> </html> And my project structure is: $ tree -I "*.pyc" forum/ forum/ ├── boards │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ ├── models.py │ ├── __pycache__ │ ├── static │ │ └── css │ │ └── bootstrap.min.css │ ├── templates │ │ ├── home.html │ │ └── home.html.bak │ ├── tests.py │ └── views.py ├── database │ └── db.sqlite3 ├── forum │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py 10 directories, 18 files But at the end when I run project I … -
How do I limit a text length and add dots to show continuation python django
Am working on an Ecommerce website using django. My problem is that some products name are longer that the other, which makes the product display look odd. Question: How do I limit the length of product name and add dots to show that it continue Example: product_name = "Men Suede Loafers Moccasins Shoes -Black" will look like product_name = "Men Suede Loafers Mocca...." -
Count(distinct) with multiple fields in django
Here I trying to convert Django rawsql quey to Django queryset. But the problem is - How to implement distinct in two fields. SQL quey - count(distinct ra, category) as order_type Django queyset - order_type=Count('ra', 'category', distinct=True) - giving error queryset = Model.objects.raw("select id,category,count(category) as total_orders, count(distinct ra, category) as order_type, SUM(CASE WHEN service_status = 'success' THEN 1 ELSE 0 END) as total_success_order, SUM(CASE WHEN service_status = 'failed' THEN 1 ELSE 0 END) as total_failed_order from table group by ra;") queryset = Model.objects.values('ra').annotate(category=F('category'),\ order_type=Count('ra', 'category', distinct=True),total_orders=Count('category'),\ total_success_order=Count('service_status', filter=Q(service_status='success')),\ total_failed_order=Count('service_status', filter=Q(service_status='failed'))).order_by() What should be the right syntax? -
Django template get value from foreign keys without context
I have the following data model: class Membership(models.Model): slug = models.SlugField() membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=11) price = models.IntegerField(default=50) stripe_plan_id = models.CharField(max_length=40) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) In my nav bar I would like to show the membership_type if the user is authenticated. Is it possible to do it without a view passing the context? I tried the following: {% if request.user.is_authenticated %} {{ request.user.usermembership.membership.membership_type }} {{ request.user.usermembership_set.membership_set.membership_type }} {% endif %} -
How to align deleteCssClass inside a Jquery Formset?
I'm utilizing a javascript code, called Jquery Formset ( https://github.com/elo80ka/django-dynamic-formset/blob/master/src/jquery.formset.js) and I'm trying to adjust the layout, in particular about the deleteCssClass modifying the script code: .. addText: '+', deleteText: '-', addCssClass: "btn btn-primary", // CSS class applied to the add link deleteCssClass: "btn-primary", // CSS class applied to the delete link .. But the button delete is not in line with the forms, and the result is the following: I have insert the form in a table and I have delete the single Lables replacing them with the table head. Below the code of my tamplate: <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4"> <h2>Inserimento costi</h2> <hr> <div class="form-group"> <form action="." method="post"> {% csrf_token %} <div> {{ form.as_p }} </div> <table class="table"> {{ costi_materiali_form.management_form }} {% for form in costi_materiali_form.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} form-group formset_row1"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ … -
Django App to handle Authentication and sessions for Android app
I want to build an Android app and use my already existing Django app that is serving a website to authenticate users and handle sessions for the App. I was thinking of token authentication which could be, I build a token on Android App using shared secret and send it across to recieve authentication from server. Will that be possible ? Or any other way to do that with minimal or no dependencies ? -
AJAX in Django page refreshing issue
I have a database with user saved items. On their account the list of those items is displayed; a button next of each items can remove them from the database. Whenever I click on one of the items, their is 5 'delete icons' showing up next to each item. I am using Pagination set on 5 items to display them. But as well with console.log() I realize that whatever button I select my first button is selected. I know the AJAX call is working because the first item is removed from my database. My HTML: {% for saved in saved_list %} <div class="card mb-3" style="width: 49%;"> <div class="row no-gutters"> <div class="col-md-2 my-auto"> <img class="mx-auto d-block " style="width:auto; height:auto; max-width:100px; max-height:100px; " src="{{ saved.sub_product.picture }}"> </div> <div class="col-md-9"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'finder:detail' saved.sub_product.id %}" class="aaccount">{{ saved.sub_product.real_name}}/ {{ saved.sub_product.real_brand }}</a> </h5> <img src="/static/finder/img/nutriscore-{{ saved.sub_product.nutrition_grade}}.svg" style="width:70px;"><br> </div> </div> <div class="col-md-1 my-auto mx-auto"> <form class="form_id" method='post'>{% csrf_token %}{{ saved.id}} <button class='substitut' type="submit" value='{{ saved.id}}'><i class='fas fa-trash'></i></button> </form> </div> </div> </div> </div> {% endfor %} My AJAX: $(".form_id").on('submit', function(event) { event.preventDefault(); var product = $('.substitut').val(); console.log(product); var url = '/register/delete/'; $.ajax({ url: url, type: "POST", data:{ 'product': product, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', … -
ValueError at /shop/checkout/ Incorrect AES key length (20 bytes)
Traceback (most recent call last): File "C:\Users\uc\Envs\test\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\uc\projects\MyEcomSite\MyCart\shop\views.py", line 104, in checkout param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(param_dict, MERCHANT_KEY) File "C:\Users\uc\projects\MyEcomSite\MyCart\Paytm\Checksum.py", line 24, in generate_checksum return encode(hash_string, IV, merchant_key) File "C:\Users\uc\projects\MyEcomSite\MyCart\Paytm\Checksum.py", line 103, in encode c = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8')) File "C:\Users\uc\Envs\test\lib\site-packages\Crypto\Cipher\AES.py", line 232, in new return _create_cipher(sys.modules[name], key, mode, *args, **kwargs) File "C:\Users\uc\Envs\test\lib\site-packages\Crypto\Cipher__init__.py", line 79, in _create_cipher return modes[mode](factory, **kwargs) File "C:\Users\uc\Envs\test\lib\site-packages\Crypto\Cipher_mode_cbc.py", line 274, in _create_cbc_cipher cipher_state = factory._create_base_cipher(kwargs) File "C:\Users\uc\Envs\test\lib\site-packages\Crypto\Cipher\AES.py", line 93, in _create_base_cipher raise ValueError("Incorrect AES key length (%d bytes)" % len(key)) ValueError: Incorrect AES key length (20 bytes) [03/May/2020 11:49:35] "POST /shop/checkout/ HTTP/1.1" 500 97074 -
how can i display mysql content using 2 for loops is flask jinja2
I have written a code in flask in which users are allowed to upload images and along with image they can ask questions for taking user questions i have created a form and on submitting form user questions are stored into the database I am able to retrieve the question from database and images and diplay them in HTML using jinja2 What I want is to display the image and below that display its comment from flask import Flask,request,render_template,redirect,url_for,session,logging,flash,send_from_directory from flask_sqlalchemy import SQLAlchemy import pymysql pymysql.install_as_MySQLdb() from flask_mail import Mail app = Flask(__name__) import os app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/akashauto' db = SQLAlchemy(app) class Upload_tb(db.Model): snob = db.Column(db.Integer, primary_key=True) commentb = db.Column(db.String(20), unique=True, nullable=False) datab = db.Column(db.String(20), unique=True, nullable=False) APP_ROOT=os.path.dirname(os.path.abspath(__file__)) @app.route("/plcpro") def problem(): return render_template("plcpro.html") @app.route("/uploader",methods=["GET","POST"]) def uploader(): target=os.path.join(APP_ROOT,"images/") print(target) if not os.path.isdir(target): #if folder does not exist . create a folder os.mkdir(target) if(request.method=='POST'): f=request.files['file1'] text=request.form.get('comment') filename=f.filename f.save(os.path.join(target,filename)) image=os.listdir('./images') existing_entry=Upload_tb.query.filter_by(commentb=text).first() if existing_entry: # flash('Email already exist','danger') return redirect(url_for("plcove")) new_entry=Upload_tb(commentb=text,datab=filename) db.session.add(new_entry) db.session.commit() question=Upload_tb.query.all() return render_template('ans.html',file=filename,text=text,image=image,question=question) @app.route("/uploader/<filename>") def send_img(filename): return send_from_directory("images",filename) This is the Form code <form id="upload-form" action="/uploader" method="POST" enctype="multipart/form-data" onsubmit=" return askvalidateform()"> <div class="form-group"> <label for="name">Enter Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter your name"> <span id="nameerror" class="text-danger"></span> </div> <div class="form-group"> <label … -
Bootstrap and css are both not working correctly in django project
I am using a html5 theme (https://colorlib.com/preview/theme/personal/) in my django 2 project. But, It's style not working correctly. I have linked all css correctly. My Django Project link (https://github.com/shahriar-programmer/personal-django). How can I modify my code to make it properly stylish like the theme preview? -
django orm relations - join three tables at diffrent fields
in my django model i have 3 model like : class Industry(models.Model): section = models.CharField(max_length=16, blank=True, null=True) industry = models.CharField(max_length=16, blank=True, null=True) class Company(models.Model): instrument = models.CharField(max_length=16, blank=True, null=True) symbol = models.CharField(max_length=16, blank=True, null=True) company = models.CharField(max_length=64, blank=True, null=True) industry = models.ForeignKey(Industry, on_delete=models.CASCADE, max_length=16, blank=True, null=True) class DailyData(models.Model): instrument = models.CharField(max_length=16, blank=True, null=True) i want to join DailyData and Company on field instrument . and join this to Industry on field industry . multiplie tables outer join on instrument and industry fields -
I am facing this problem in my about page if i remove my css then it works well otherwise it gives me an error whenever i use to display images
I am facing this problem in my about page if i remove my css then it works well otherwise it gives me an error whenever i use to display images please reply as soon as possible please reply fast for this question if anyone can Django Version: 3.0.5 Python Version: 3.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysiteapp'] 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 "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\newproject\mysite\mysiteapp\views.py", line 27, in about return render(request,'about.html') File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loaders\base.py", line 24, in get_template contents = self.get_contents(origin) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loaders\filesystem.py", line 24, in get_contents return fp.read() File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) … -
django Templates does not exists execpt home url
I am creating a simple website.and having kinda odd error TemplateDoesNotExist at /about/ but my homepage working fine without TempaletDoesNotExist error. mine both home.html and about.html in same directory and I tried many solutions with the reference of this answer the actual problem is one URL is working and another one is not. please help me out thanks TemplateDoesNotExist at /about/ about.hmtl Request Method: GET Request URL: https://www.appname./about/ Django Version: 2.2.9 Exception Type: TemplateDoesNotExist Exception Value: about.hmtl Exception Location: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /home/name/virtualenv/appname/3.5/bin/python3.5_bin Python Version: 3.5.7 Python Path: ['/home/name/appname', '/opt/passenger-5.3.7-4.el6.cloudlinux/src/helper-scripts', '/home/name/virtualenv/appname/3.5/lib64/python35.zip', '/home/name/virtualenv/appname/3.5/lib64/python3.5', '/home/name/virtualenv/appname/3.5/lib64/python3.5/plat-linux', '/home/name/virtualenv/appname/3.5/lib64/python3.5/lib-dynload', '/opt/alt/python35/lib64/python3.5', '/opt/alt/python35/lib/python3.5', '/home/name/virtualenv/appname/3.5/lib/python3.5/site-packages'] Server time: Sun, 3 May 2020 04:48:46 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/contrib/admin/templates/about.hmtl (Source does not exist) django.template.loaders.app_directories.Loader: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/contrib/auth/templates/about.hmtl (Source does not exist) django.template.loaders.app_directories.Loader: /home/name/appname/mysite/templates/about.hmtl (Source does not exist) My templates<dir> /home/name/appname/mysite/templates/home.html /home/name/appname/mysite/templates/about.html app<views.py> from django.shortcuts import render from django.http import HttpResponse def homepage(request): return render(request=request,template_name='home.html') def about(request): return render(request=request,template_name='about.hmtl') app<urls.py> from django.conf.urls import include, url from django.contrib import admin from django.urls import path from . import views app_name = "bugengine" urlpatterns = [ url(r'^$', views.homepage, name="homepage"), url(r'^about/',views.about, name="about"), ] setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Vue.js img src using absolute path (django+webpack)
I am using django + Vue.js & webpack for development. In my App.vue file i try to load img: <img src="/static/webapp/img/logo.png" alt="logo"> In production I use nginx which is directing /static path into static folder that I share and it's working. But in the development when i run my django on localhost:8000 and load this js from my App.vue it's trying to get the image from localhost:8000/static/webapp/img/logo.png. I would like it to take from localhost:8082/static/webapp/img/logo.png (localhost:8082 is where webpack is running) where it can be found. I tryied to change publicPath in my webpack.config.js: if (process.env.NODE_ENV === 'development') { module.exports.output.publicPath = 'http://localhost:8082/' } but it does not change default behaviour and the img asset src is still localhost:8000/static/webapp/img/logo.png. How can I change img assets default base path to another url to make it work? Cheers.