Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Factory Boy with Django ManyToMany models
I have 3 models on the same module, app.models.py, as following. Some other models may appear in code but it isn't relevant. Optionals class Optional(models.Model): name = models.CharField(_('Nome'), max_length=255) type = models.CharField(_('Tipo'), max_length=50, null=True, blank=True) description = models.TextField(_('Descrição'), null=True, blank=True) provider = models.ForeignKey('providers.Provider', null=True, blank=True) charge = models.ForeignKey('Charge', null=True, blank=True) def __str__(self): return self.name Coverage class Coverage(models.Model): code = models.CharField(_('Código'), max_length=20, null=True, blank=True) vehicle_code = models.CharField(_('Código do veículo (ACRISS)'), max_length=4, null=True, blank=True) charge = models.ForeignKey('Charge', null=True, blank=True) Vehicle class Vehicle(models.Model): code = models.CharField(_('Código'), max_length=100) description = models.CharField(_('Descrição'), max_length=255, null=True, blank=True) model = models.CharField(_('Modelo'), max_length=100, null=True, blank=True) brand = models.CharField(_('Fabricante'), max_length=100, null=True, blank=True) group = models.ForeignKey('Group', null=True, blank=True) optionals = models.ManyToManyField('Optional', related_name='vehicle_optional') coverages = models.ManyToManyField('Coverage', related_name='vehicle_coverage') def __str__(self): return self.code I'm trying create fixtures from this models using factory_boy. class CoverageFactory(factory.Factory): class Meta: model = Coverage charge = factory.SubFactory(ChargeFactory) class OptionalFactory(factory.Factory): class Meta: model = Optional provider = factory.SubFactory(ProviderFactory) charge = factory.SubFactory(ChargeFactory) class VehicleFactory(factory.Factory): class Meta: model = Vehicle group = factory.SubFactory(GroupFactory) optionals = factory.SubFactory(OptionalFactory) coverages = factory.SubFactory(CoverageFactory) On my tests it is instantiated this way: optional = OptionalFactory( name="GPS", type="13", description="", charge=charge, provider=provider ) coverage = CoverageFactory( code="ALI", vehicle_code="ABCD", charge=charge ) vehicle = VehicleFactory( code="ECMM", description="GRUPO AX - MOVIDA ON", … -
Django: NoReverseMatch not a valid function
Running my local Django dev server (2.2) in a virtual environment, I encounter a trace back. The essential keywords that are part of this error include “django.urls.exceptions.NoReverseMatch” and “not a valid view function or pattern name.” I’m doing a code-along kinda Udemy course by Nick Walter. Part of the course material involves writing a rudimentary blog using Django. I’m close to the end of Nick’s blog module. I figure I have referred to a function inaccurately somewhere or perhaps I have misconfigured my urlpattern. There are a few other SO members who have encountered similar errors with the resolution typically involving correcting a typo. I've tried removing the pluralization of my post_details views function. I’ve tried variations in my urls.py with different combinations of regular expressions (and without). I feel like I am overlooking something trivial here. It’s gotten to the point where I am comparing my code to the course instructor’s end-of-module source code and I can’t for the life of me figure out what I am doing wrong. Here is my code: urls.py: from django.urls import path, re_path # from . import views from posts.views import * from redactors.views import * from counters.views import * from django.conf.urls.static import … -
How to automatically update the exchange rate in django-currencies?
I use django-currencies to translate the price at the exchange rate on the templates. In order to update the exchange rate you need to enter the command: python manage.py updatecurrencies I set up celery to update the exchange rate once a day, but I don’t understand how exactly I should call this command? Perhaps there are other ideas how to update currency? -
Django App Not Communicating with JavaScript Code Block
I have a Django application that accepts an Elasticsearch query in a form and produces a downloadable report. An earlier iteration worked great, but we decided to add a component that checks every ten seconds if the report is done being created ([thank you to goudarziha][1]). Our ultimate goal is to have it check repeatedly for the completed report (and tell the user the report is still processing if not complete), and then either add a button to download the report or just have it automatically begin downloading. However, my application doesn't seem to be calling on the javascript block I have in my form.html. When I run this, it says {"file_created": False} until I manually refresh myself, then it switches to True. I tried the code commented out in check_progress (which is basically what my code in form.html does...) but it returned an error. How do I make them communicate? What am I missing? views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse, HttpResponseRedirect import os import threading from .forms import QueryForm from .models import * @login_required def get_query(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): query = form.cleaned_data["query"] t = threading.Thread(target=generate_doc, … -
Rawsql query array into formatted html table
I have done a rawsql query on a table in my database and gotten an array looking like this : [(19778, 4519, 'sp|P48740|MASP1_HUMAN', 5, 50, 'R'), (19779, 14872, 'sp|P48740|MASP1_HUMAN', 5, 54, 'R'), (19780, 1018, 'sp|P48740|MASP1_HUMAN', 5, 45, 'R'), (19781, 13685, 'sp|P48740|MASP1_HUMAN', 5, 51, 'R')] I want to format this into a html table which the 6 section within each set of parentheses each a column. Of course there will be an unknown amount of items in the array so explicitly calling each will not work. What is the best and most efficient way to do this? -
django how to add multi values to a many to many relationship
I have list of strings from POST request and I want to create blog object with many values of hashtags, with this method it only creates hashtag object with 1 value and then overrides it, what can i do? def myForm(request): tags = HashTags.objects.all() if request.method == 'POST': g = request.POST print(g) if g.get('title') and g.get('desc') and request.FILES.get('file'): obj = Blog.objects.create( title = g.get('title'), text = g.get('desc'), photo1 = request.FILES.get('file')) if g.get('VIN'): obj.Vin = g.get('VIN') if g.getlist('tags'): for i in g.getlist('tags'): print(i) a = HashTags.objects.filter(tag=i) obj.hashtag.tag = g.getlist('tags')[0] return redirect('blog:main') class HashTags(models.Model): tag = models.CharField(max_length=150,unique=True) #unique=True def __str__(self): return self.tag class Blog(models.Model): title = models.CharField(max_length=150) date = models.DateTimeField(auto_now_add=True) text = models.TextField() photo1 = models.ImageField() photo2 = models.ImageField(null=True,blank=True) videoURL = models.CharField(max_length = 5000) hashtag = models.ManyToManyField(HashTags) slug = models.SlugField(null=True,blank=True) pinVideo =models.BooleanField(null=True,blank=True,default=False) pinPhoto = models.BooleanField(null=True,blank=True,default=False) actual: randomtag2 expected: randomtag1 ,randomtag2 -
Making a custom filter and need it do a general search instead of an exact search
I am creating a custom filter class and instead of my search being exact I want it to be general or a contains Here's my code for the custom filter class: class ChoiceFilter(FilterSet): class Meta: model = Choice fields = '__all__' Whenever I try to search something I have to be exact and get the entire string for it to show data. I want it so it doesn't have to do that. For example: If I have answer called 'yes' if I search 'y' I want to the answer 'yes' to pop up instead of needing the entire word. -
Why aren't styles applied?
staticfiles connected. static is prescribed everywhere. Everything seems to be loading, but for some reason they don’t connect ... collectstatic did it successfully. my_project/ __my_project/ ____settings/ ____static/ ____assets/ __app/ __static/ settins.base.py STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( path('static'), ) STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) 'django.template.context_processors.static', 'django.contrib.staticfiles', html <link href="{% static 'assets/fonts/stylesheet.css' %}" rel="stylesheet"> <link href="{% static 'assets/plugins/swipe_navigation/source/stylesheets/swipenavigation.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'assets/plugins/jqueryui/jquery-ui.css' %}" rel="stylesheet" type="text/css"> ... -
How to get into the details view using any primary key from a template to another template?
I make a list view and detail view using function..here i get the queryset..I get the query data in list view but I get the query data in list view in template passing pk in url section.. i put '''league//''' in path for detail view and in list view template put '''{% url 'league-detail' match.pk %}''' in href...bt an error occurs : league() got an unexpected keyword argument 'pk' urls: ''' path('leagues/', views.league, name='league'), path('league//', views.league_detail, name='league-detail'), ''' views: '''python match = Match.objects.all() ''' same for both list view and detail view templates: ''' {% url 'league-detail' match.pk %} ''' but error is: league() got an unexpected keyword argument 'pk' i need to go to the '''league-detail''' template by get actual data using queryset -
Upload an image via Admin control
I am trying to make an app where I can upload images through the Admin side, localhost:8000/admin/example but when I upload an image it gives me a 404 error when I go to the image url. I am new to django and python so I am trying to learn about both of them. Here is what i have for models, urls, and settings models.py item_image = models.ImageField(upload_to = "static/images/products" ) urls.py from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:item_id>/', views.detail, name='detail'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) MEDIA_ROOT = PROJECT_ROOT + '/static/images/products/' MEDIA_URL = '/media/' html file <img src={{item.item_image.url}}> -
Pass data between views via URL encoding or sessions? (Django 2.1)
I am building a search engine that highlights the keyword searched by the user. For example, if the user searches "cheese," the word "cheese" will be highlighted in the search results. I have two views: one for the page that displays the list of search results, and one for the page that displays the content of the search result. I need to pass the keyword from the first view to the second view so that the keyword can be highlighted in both views. View 1: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') context = {'articles': articles, 'search_term': search_term} return render(request, 'query_search.html', context) View 2: def article_detail(request, ArticleID): ArticleID = get_object_or_404(cross_currents_article_detail, ArticleID=ArticleID) context = {'ArticleID':ArticleID} return render(request, 'article_detail.html', context) urls.py: urlpatterns = [ path('', query_search, name='query_search'), path('article/<int:ArticleID>/', article_detail, name='article_detail')] Should I pass the keyword (search_term) via sessions or URL encoding? Currently, the keyword is encoded in the URL of View 1. If I pass the keyword via sessions, would it get messy if the user does multiple queries on my site? Will the stored keyword for another query be confused with keywords for the current query? Any … -
Why aren't custom form error messages being displayed in Django 1.11?
When I first built my application with Django 1.8, I was able to create custom form error messages like this: # forms.py class UserProfileForm(forms.ModelForm): user_age = forms.IntegerField( label = 'Your age', error_messages = {'required': 'Please enter your age}, widget = forms.NumberInput(attrs={'class': 'form-control'})) # create_user_profile.html <form method="post" action="."> {% csrf_token %} <div class="form-group form-errors"> {% if form.errors %} <p class="errornote"> {% if form.errors.items|length == 1 %} Please correct the error below. {% else %} Please correct the errors below. {% endif %} </p> {% endif %} </div> <div class="form-group form-errors"> {% if form.non_field_errors %} {% for error in form.non_field_errors %} <p class="errornote"> {{ error }} </p> {% endfor %} {% endif %} </div> <div class="form-group"> <label for="id_user_age">Your age</label> {{ form.user_age.errors }} {{ form.user_age }} </div> If the user didn't fill out their 'user_age' form field, the template page would display an error message at the top of the page and the error message for that form field like this: Please correct the error below. Your age Please enter your age +--------------------+ | | +--------------------+ However, I recently upgraded from Django 1.8 to Django 1.11 and I've realized that my custom form error messages are no longer being displayed. Instead, if the … -
Referencing multiword model object in Django
This could be simple but it is really giving me headache. I have a muiltiword model ListingImages that is linked to another model Listing. I am retrieving the Listing data and using it to access objects of the ListingImages. However, I am not getting the desired result. Here are my files. models.py class Listing(models.Model): listing_title = models.CharField(max_length=255) class ListingImages(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) image_url = models.ImageField(upload_to=get_image_filename, verbose_name='Listing Images') def get_image_filename(instance, filename): title = instance.listing.listing_title slug = slugify(title) return "listings_pics/%s-%s" % (slug, filename) views.py def index(request): context = { 'listings': Listing.objects.filter(status=True) } return render(request, 'base/index.html', context) snippet of template index.html <img src="{{ listing.listingImages.image_url.url }}" alt=""> However, in the template, I am not getting the image url, but instead I am getting a <img src="(unknown)" alt="">. I don't what I am doing wrong, also, I am not sure how to reference the multiword model ListingImages, whether it should be listingImages or listing-images or listing_images. -
How to join SQL table in Django Rest Framework
I want to join two models and show all the fields of the join, like it's on SQL, For exemple i want to do this request: SELECT course_id, challenge_id FROM Challenges,Course WHERE course_id=course; where one course have many challenges. My Models: class Course(models.Model): class Meta: unique_together = (('course_id', 'owner',),) db_table = "course" REQUIRED_FIELDS = ['owner', 'course_id'] course_id = models.AutoField(primary_key=True) owner = models.ForeignKey(Users, on_delete=models.CASCADE) class Challenges(models.Model): class Meta: unique_together = (('challenge_id', 'course'),) db_table = "challenges" REQUIRED_FIELDS = ['challenge_id', 'course'] challenge_id = models.AutoField(primary_key=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) -
Can't upload CSV to Postgre SQL Database
I have been using PostgreSQL for a while now, and I have connected my IDE PyCharm with my local PostgreSQL. I just dumped the data of one of my database with 295 rows to a csv, and tried to import the same file, and it shows me an error. I checked the csv and the columns multiple times, but it keeps giving me the same error, without importing a single line. The error I keep getting 1:1: ERROR: null value in column "Name" violates not-null constraint Detail: Failing row contains (1, null, null, null, null, null, null, null, null, null, Tempo 407 1500). This is a screenshot of my database: This is my model: class Truckdb(models.Model): Name = models.CharField(max_length=30) Category = models.CharField(max_length=100, blank=True) TruckID = models.IntegerField(blank=True) Length = models.FloatField(blank=True) Breadth = models.FloatField(blank=True) Height = models.FloatField(blank=True) Volume = models.FloatField(blank=True) Weight = models.FloatField(blank=True) Price = models.FloatField(blank=True) display_name = models.CharField(max_length=150, blank=True) This is how my csv looks like: 1,Tempo 407,OPEN,1,9.5,5.5,5.5,287.375,1500,1,Tempo 407 1500 2,Tempo 407,OPEN,2,9.5,5.5,5.5,287.375,2000,1,Tempo 407 2000 3,Tempo 407,OPEN,3,9.5,5.5,5.5,287.375,2500,2,Tempo 407 2500 4,13 Feet,OPEN,4,13,5.5,7,500.5,3500,3,13 Feet 3500 5,14 Feet,OPEN,5,14,6,6,504,4000,3,14 Feet 4000 6,17 Feet,OPEN,6,17,6,7,672,6000,4,17 Feet 6000 7,18 Feet Taurus,OPEN,7,18,7,7,882,8000,6,18 Feet Taurus 8000 8,19 Feet Taurus,OPEN,8,19,7,7,931,9000,10,19 Feet Taurus 9000 9,10 TYRE,OPEN,9,22,7.5,8,1320,14000,11,10 TYRE 14000 10,10 TYRE,OPEN,10,22,7.5,8,1320,15000,12,10 TYRE 15000 11,10 … -
I don't see any syntax errors but I keep getting ModelForm has no model class specified
I am trying to link a form to a model of mine, but i keep getting a value error on the page. I don't see any syntax errors, and I'm not sure where the flaw in logic might be. I already tried changing meta to Meta, it had no effect. I already have some entities in the table could that be causing the issue? # URLS________ path('posts/create_post/', views.create_post, name='create_post'), #MODELS________ class Posts(models.Model): priority = models.CharField(max_length=30) client = models.CharField(max_length=30) title = models.CharField(max_length=150) assigned_to = models.ForeignKey(Users, on_delete=models.CASCADE) exp_comp_time = models.FloatField(max_length=4) percent_comp = models.FloatField(max_length=4) post_date = models.CharField(max_length=20) due_date = models.CharField(max_length=20) latest_mod = models.CharField(max_length=20, null=True) class PostsForm(forms.ModelForm): class meta: model = Posts fields = '__all__' #VIEWS________ def create_post(request): """"Renders the create task page""" if request.method == "GET": form = PostsForm() return render(request, 'app/form.html', {'form': form}) elif request.method == "POST": form = PostsForm(request.POST) form.save() return HttpResponseRedirect('/posts') #FORM.html________ {% extends "app/layout.html" %} {% block content %} <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit Task</button> </form> {% endblock %} The post form page should be loading. Traceback: File "C:\DjangoWebProject1\DjangoWebProject1\office_proj_env\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\DjangoWebProject1\DjangoWebProject1\office_proj_env\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\DjangoWebProject1\DjangoWebProject1\office_proj_env\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args,**callback_kwargs) File … -
Djang-admin is is not recognized
I've been trying to start a Django project and when I try to create a new project, it gives me an error django-admin startproject example The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. I've added Python to environmental variable and of course installed Django package and tried all the other options on googling, nothing worked. Is there something I'm missing? -
How to merge or append excluded django-elasticsearch-dsl result to end of django-elasticsearch-dsl filtered result
I am displaying Listview using elasticsearch ,and I need to filter search result from query and also want excluded queryset appended at the end of filtered queryset,using django-elasticsearch-dsl ,elasticsearch-dsl=6.4.0,<7.0.0 I have tried using "|" operator to append no luck found complete_indexed_list = ['politics','science', 'life', 'movie', 'technology'] user_preferred_list = ['life', 'movie', 'technology'] expected result = ['life', 'movie', 'technology', 'politics', 'science'] -
"How to get query in template from django many to many fields by using parent class??"
"I made a parent class model where i put some fields which are related with many to many fields. I want to get all individual data from many to many field using the query of parent class. When i do these i get the all query set of the field. I tried ,, match = Match.objects.all() in views function.. then i tried {{ match.mega_league.pool_price }} to get the value..but its not working on template... ''' models: class Match(models.Model): mega_league = models.ManyToManyField('MegaLeague', blank=True) class MegaLeague(models.Model): price_pool = models.IntegerField() winner = models.IntegerField() views: match = Match.objects.all() templates: {{ match.mega_league.pool_price }} but it's not working.. ''' when i use {{ match.mega_league.pool_price }} this give me blank result but in database i have data for price_pool and winner also... i need the individual access for price_pool and winner..." -
Custom Form for create and update the blogposts give Page Not Found error
I've create a simple form to create and update the blogposts. After the creation of the update view happen something strange that I can't solve. views.py def createPost(request): if request.method == "POST": form = BlogPostForm(request.POST or None) if form.is_valid(): new_post = form.save(commit=False) new_post.slug_post = slugify(new_post.title) new_post.save() return redirect('post_list') else: form = BlogPostForm() context = { 'form': form, } template = 'blog/editing/create_post.html' return render(request, template, context) def updatePost(request, slug_post=None): update_post = get_object_or_404(BlogPost, slug_post=slug_post) form = BlogPostForm(request.POST or None, instance=update_post) if form.is_valid(): update_post = form.save(commit=False) update_post.slug_post = slugify(update_post.title) update_post.save() return redirect('post_list') context = { 'form': form, } template = 'blog/editing/create_post.html' return render(request, template, context) urls.py urlpatterns = [ path("blog/", views.listPost, name='post_list'), path("blog/<str:slug_post>/", views.singlePost, name='single_post'), path("blog/create-post/", views.createPost, name='create_post'), path("blog/<str:slug_post>/update-post/", views.updatePost, name='update_post'), path("blog/<str:slug_post>/delete-post/", views.deletePost, name='delete_post'), ] post_list.html <div class="row"> {% for post in post_list %} {% if forloop.first %}<div class="card-deck">{% endif %} <div class="card mb-3 shadow" style="max-width: 540px;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="{{ post.header_image_link }}" class="card-img" alt="{{ post.title }}" style="height: 250px;"> </div> <div class="col-md-8"> <div class="card-body"> <h4 class="card-title"><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h4> <p class="card-text">{{ post.description }}</p> <p class="card-text my-0 py-0"><small class="text-muted"><strong>Published: </strong>{{ post.publishing_date|date }}</small></p> </div> </div> </div> </div> {% if forloop.counter|divisibleby:"4" or forloop.last %}</div>{% endif %} {% if forloop.counter|divisibleby:"4" and not … -
using render_to_string library is not working
i have a django code that allow user to add books to a list with javascript function that handle an ajax request once the user click the button. i am using BootStrap 4 the problem is that once the user click the button the console display the below error : File "C:\Users\LTGM~1\Desktop\CRUDDJ~1\env\lib\site-packages\widget_tweaks\templatetags\widget_tweaks.py", line 163, in render_field raise TemplateSyntaxError(error_msg + ": %s" % pair) django.template.exceptions.TemplateSyntaxError: 'render_field' tag requires a form field followed by a list of attributes and values in the form attr="value": class urls.py from django.contrib import admin from django.urls import path from .views import * urlpatterns = [ path('admin/', admin.site.urls), path('books/',book_list, name = "book_list"), path('books/create/',book_create, name = "book_create"), ] views.py from django.shortcuts import render from books.models import Book from books.forms import BookForm from django.http import JsonResponse from django.template.loader import render_to_string def book_list(request): books = Book.objects.all()#list all records return render(request, './book_list.html',{'books':books}) def book_create(request): form = BookForm() context= {'form':form} html_form = render_to_string('./partial_book_create.html',context,request=request,) return JsonResponse({'html_form':html_form}) partial_book_create.html {% load widget_tweaks %} <form method="post"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-lable="Close"> <span aria-hidden = "true">&times;</span> </button> <h4 class="modal-title">Create a new book</h4> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for ="{{ … -
Django JavaScript Block in HTML Not Calling On Function in Views
I have a Django application that accepts an Elasticsearch query in a form and produces a downloadable report. An earlier iteration worked great, but we decided to add a component that checks every ten seconds if the report is done being created (thank you to goudarziha). Our ultimate goal is to have it check repeatedly for the completed report (and tell the user the report is still processing if not complete), and then either add a button to download the report or just have it automatically begin downloading. However, my application doesn't seem to be calling on check_progress in the views.py file. Where am I missing a link to connect the check_progress process with the continuous checker in form.html? Or am I going about this all wrong? views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse, HttpResponseRedirect import os import threading from .forms import QueryForm from .models import * @login_required def get_query(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): query = form.cleaned_data["query"] t = threading.Thread(target=generate_doc, args=(query,)) t.start() return HttpResponseRedirect('/check_progress/') else: return HttpResponse("Your query does not appear to be valid. Please enter a valid query and try again.") else: form = QueryForm() return render(request, … -
How to resolve 'TemplateDoesNotExist' error when Django appears to be searching the correct path
I'm setting up the structure for a new project in Django. I've created the app 'accounts', within which I've added a templates folder containing an html template. However, when I go into the development server and click on a link to this page from my index page (which loads no problem), it returns a TemplateDoesNotExist error message. I've examined the error message and the Template-loader postmortem details the correct pathway for my html template (I've checked this and made sure countless times), suggesting that Django is looking in the right place for it. However, it also says 'source does not exist'. Does anybody have any troubleshooting tips, considering Django appears to be searching the correct pathway? # From settings.py ('accounts' is also included with INSTALLED_APPS): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], # From urls.py: from django.conf.urls import url, include from accounts.views import index urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index, name="index"), url(r'^accounts/', include('accounts.urls')), ] # From urls.py (accounts): from .views import signup urlpatterns = [ url(r'^signup/$', signup, name="signup"), ] # From views.py (accounts): def signup(request): return render(request, 'signup') -
Django Test Fail sometimes and sometime succecss, what is possible reason?
I have written testcase and i found my testcase is ok. I run the test and it fires me ok message, i run frequently the same test, it fires me ok message.. But the problem, sometime it fires me fail message.. what is possible reason? I could share the code here but i found no reason to show the code. coz, the problem is not with code... the problem is awkwardness... I think if the test return succecss message, it should return success message forever, why it returns fail message sometimes? even i dont change any code in the meantime, yet it return fails or success.. for example, i write test and i run it, i found it success.. if run it 2 minutes later, it retruns fail message, (sometime success) whats wrong with system? I hope you got the issue? What is possible solution for this issue? how can skip this situation? -
Including the correct amount of White Space when printing a receipt
I'm writing a till system for a local coffee shop. I'm stuck on printing the itemized receipt. I don't know how many characters in width standard receipt paper is, or barring that how to nicely format the paper -- with items sold, item name, white space, total cost For example, 5 x Coffee 10.00 15 x Tea 10.00 Any tips on having the correct amount of white space? Or how many ASCII characters in width is standard receipt paper? Thanks in advance