Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
I want to make a changing "array" of color options and size options per item in the admin panel
Title and code. I'm working on an E-Commerce site where I will have multiple options per item (color/size). In the code you can see price, price(1-3), the idea is to create a button or option for the admin to add additional sizes and therefor prices without hard coding sizename(1-4) and the same goes for colorName(1-4). I hope that you can understand what I'm going for, I just started learning python and all of this bootstrap and django stuff yesterday. BTW If you know of an easier way to handle all of this, please do let me know, I'm lost as to how to make a shopping cart. I just started this class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(decimal_places=2, max_digits=20) stock = models.IntegerField() image_url = models.CharField(max_length=2083) category = models.CharField(choices=MY_CHOICES, max_length=25, default='Default') multSizes = models.BooleanField(default=False) numberSizes = models.IntegerField(default=1) price1 = models.DecimalField(decimal_places=2, max_digits=20, default=0) price2 = models.DecimalField(decimal_places=2, max_digits=20, default=0) price3 = models.DecimalField(decimal_places=2, max_digits=20, default=0) sizename1 = models.CharField(max_length=255, default='N/A') sizename2 = models.CharField(max_length=255, default='N/A') sizename3 = models.CharField(max_length=255, default='N/A') sizename4 = models.CharField(max_length=255, default='N/A') numberColors = models.IntegerField(default=1) colorName = models.CharField(max_length=255, default='N/A') colorName1 = models.CharField(max_length=255, default='N/A') colorName2 = models.CharField(max_length=255, default='N/A') colorName3 = models.CharField(max_length=255, default='N/A') colorName4 = models.CharField(max_length=255, default='N/A') I want to be able to change the amount … -
Django throwing ValueError: too many values to unpack (expected 2) with no change to the code
I have written a new function in a subfolder and my django project that was running fine is now throwing the following error: File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\urls.py", line 4, in <module> from .views import ( File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\views.py", line 15, in <module> from .forms import IndicatorForm, SearchForIndicatorMetaData File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\forms.py", line 24, in <module> class IndicatorForm(forms.ModelForm): File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\forms\models.py", line 252, in __new__ opts.field_classes) File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\forms\models.py", line 166, in fields_for_model formfield = f.formfield(**kwargs) File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 1873, in formfield return super(IntegerField, self).formfield(**defaults) File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 872, in formfield defaults['choices'] = self.get_choices(include_blank=include_blank) File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 802, in get_choices for choice, __ in choices: ValueError: too many values to unpack (expected 2) Similar questions have been asked in the past and it has always been that someone has used a dictionary rather than an iterable to define choices. I have not done this, but I am getting the same error. The traceback seems to think the issue is somewhere in my forms.py. My forms.py is below: from django import forms from .models import Indicator def get_indicator_ids(): ids = [] indicator_objects = Indicator.objects.all() for indicator in indicator_objects: ids.append(indicator.id) return ids class IndicatorDropDown(forms.Form): def __init__(self, *args, **kwargs): super(IndicatorDropDown, self).__init__(*args, **kwargs) self.fields['indicators'] = forms.ChoiceField(choices=get_indicator_ids()) class IndicatorForm(forms.ModelForm): class Meta: model = … -
Django - How to load paginated Page (next page) into my Template?
I have a model named "Person" (List of names). 6 Persons named "Anne". My Pagination is 2 per Page. When i start a search query on my page for "Anne". I get the Response of "6 Results", it shows me the first two Results and it displays "Page 1 of 3. Next. So far everything fine. but when i press "next" the Browser only updates to ..../post_searchtwo/?page=2 but the next two Results will not show up. (Using Django version 2.2.2 with PostgreSQL 11) thanks in advance. views.py def post_searchtwo(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Person.objects.annotate( search=SearchVector('city', 'last_name', 'first_name') ).filter(search=query) paginator = Paginator(results, 2) # --- Show 2 items per page page = request.GET.get('page') try: post_list = paginator.page(page) except PageNotAnInteger: post_list = paginator.page(1) except EmptyPage: post_list = paginator.page(paginator.num_pages) context = { 'form': form, 'query': query, 'page': page, 'post_list': post_list, 'results': results } return render(request,'search/post_searchtwo.html', context) my template / post_searchtwo.htnl {% extends 'base.html' %} {% load static %} {% block custom_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}"> {% endblock %} {% block content %} <form action="." method="get"> {{ form.as_p }} <input type="submit" … -
How to manage many tags in html?
I have written CSV file in HTML but the problem I am facing is that it has only one big column and I want to manage it in rows So that I don't have to scroll the page. Instead of managing it in HTML manually by giving rows to it, how could I write it in python with some lines of code and manage it in rows? import csv html_about = '' names = [] with open('filo.csv') as data_file: csv_data = csv.reader(data_file) for line in csv_data: names.append(f'{line[0]}') html_output = '\n<ul>' for name in names: html_output += f'\n\t<ul>{name}</ul>' html_output += '\n</ul>' print(html_output) import pandas as pd df = pd.read_csv('filo.csv') with open('table.html', 'w') as html_file: df.to_html(html_file,index=False) -
Local host page not found
Okay so I am a new learner and am following a tutorial https://www.youtube.com/watch?v=D6esTdOLXh4 My problem is that the last part of that video shows a posting site's posts when you click the linking to the post: Page not found (404) Request Method: GET Request URL: http://localhost:8000/posts/details/1%3E/ Using the URLconf defined in djangoproject1.urls, Django tried these URL patterns, in this order: [name='index'] details/<int:id>/ [name='details'] admin/ posts/ [name='index'] posts/ details/<int:id>/ [name='details'] The current path, posts/details/1>/, didn't match any of these. Here's the .py and .html files that I was editing that may be the best place to search for errors posts/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('details/<int:id>/', views.details, name='details') ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Posts # Create your views here. def index(request): # return HttpResponse('HELLO FROM POSTS') # allows post to be shown in posts connected to index.html/ posts = Posts.objects.all()[:10] context = { 'title': 'Latest Posts', 'posts': posts } return render(request, 'posts/index.html', context) def details(request, id): post = Posts.objects.get(id=id) context = { 'post': post } return render(request, 'posts/details.html', context) details.html {% extends 'posts/layout.html' %} {% block content %} <h3 class="center-align red lighten-3">{{post.title}}</h3> <div class="card"> … -
Django saving image from URL to model causes UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I have simple model with overrided save() method, I want to save image from given url, every time save mehod is called. Here is my code: def save(self, *args, **kwargs): super().save(*args, **kwargs) # Creating URL to request URL = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&key=" + settings.KEY URL += "&photoreference=" + self.reference result = urllib.request.urlretrieve(URL) self.image_file.save( os.path.basename(self.reference), File(open(result[0])) ) self.save() I found solution with addding: with open(path, 'rb') as f: contents = f.read() But i dont know where to place it, if i tried i got 'invalid syntax error'