Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Can I create several button object from my model?
I am trying to create a chore system in Django where I can assign chores to chosen individuals (users). The page would list a specified amount of chores. The individual would click on a the chore(a button) and the time would be recorded in a database where I can see the time it took to finish the chore. Am I using the best method for this project or should I learn about a CMS system? Here is my model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Chore(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 200) description = models.IntegerField(default=0) time_created = models.DateTimeField(auto_now=True) time_finished = models.DateTimeField(auto_now_add=True) views.py def get_chores(request, pk): user = User.objects.get(pk=request.user.pk) chores = user.tasks_set.all() if request.method == "GET": chore_id = request.GET['id'] if chore_id: chore = Chores.objects.get(id=int(chore_id)) if chore: chore.time_finished = True chore.save() return render(request, 'accounts/chores.html', {'chores': chores}) chores.html <div class="btn-group-vertical"> {% for chore in chores %} <form action="get"> <button type="button" class="btn btn-primary" value="{{ chore.id }}" name="id">{{ chore.description }}</button> </form> {% endfor %} </div> -
How to set the value of _setmaxstdio in Django App
How to use _setmaxstdio(2048) inside a Django project? As defined in the (https://github.com/ldilley/rubircd/wiki/Breaking-File-Descriptor-Barriers) for a C/C++ program. But I am willing to set it inside my Django project. Any quick guide how and where to use this inside Django? Thanks ! -
django 2.0 ModelForm ForeignKey select list not displayed in form
I have been searching answer for this question. So far nothing helps me. I have a model: class Student(models.Model): first_name = models.CharField() last_name = models.CharField() middle_name = models.CharField() birthday = models.DateField( blank=False, null=True) student_group = models.ForeignKey("Group", blank=False, null=True, on_delete=models.PROTECT) And ModelForm class together with UpdateView (to update student): class StudentUpdateForm(ModelForm): class Meta: model = Student fields = ['first_name', 'last_name', 'middle_name', 'birthday','student_group'] def __init__(self, *args, **kwargs): super(StudentUpdateForm, self).__init__(*args, **kwargs) print(kwargs) # self.fields["student_group"].queryset = Group.objects.all() - #THIS IS WHAT I HAVE FOUND SO FAR, BUT IT DOES NOT WORk for key, value in self.fields.items(): print(self.fields[key]) - #HERE I SEE student_group ModelChoiceField object initiated with correct group list print('----------------------------------------------------') class StudentUpdateView(UpdateView): model=Student template_name='my_template' form_class = StudentUpdateForm def get_success_url(self): return reverse('home') def post(self, request, *args, **kwargs): return super(StudentUpdateView, self).post(request, *args, **kwargs) The problem is that when I open URL to edit student, I get all fields except Foreign key field. I see it in kwargs variable, but it is not displayed in the form itself. And I can't find why. Via django admin it works fine, all fields are rendered, together with student_group list. Can you help me find out what I am doing wrong? -
Django ImageField with tempfile
Folks, I need help understanding some details about how Django saves model files. I've written a test that involves creation of files (in a temporary directory via tempfile) and has the following lines: TEMP_DIR = tempfile.TemporaryDirectory() TEMP_DIR_PATH = TEMP_DIR.name ... @override_settings(MEDIA_ROOT=TEMP_DIR_PATH) def create_photo(self, album_number, photo_number): ... p = Photo.objects.create( number=photo_number, album=album, added_by=self.user, image=SimpleUploadedFile( name=..., content=open(..., 'rb').read(), content_type='image/jpeg' ), remarks='-' ) p.full_clean() p.save() return p This code works, except for one thing that confuses me. The line p = Photo.objects.create causes a file to appear in the temporary directory. Then p.full_clean() does nothing to the file. However when I execute p.save(), the file disappears from the temporary directory. If I remove p.save(), the file stays there when the function returns. So my test function def test_image_file_present(self): """When a photo is added to DB, the file actually appears in MEDIA.""" p = self.create_photo(3, 2) image_filename = p.image.file.name if not os.path.exists(image_filename): self.fail('Image file not found') fails if p.save() is there but passes if I remove p.save(). Why would object.save() cause the file to disappear? As a bonus question, what's the purpose of .save() if the file and the Django model object appear already during Photo.objects.create? I've checked that the pre-save signal is sent … -
Django + Heroku deployment
I tried several times now to deploy my Heroku application but I always receive the attached error message. After adding DISABLE_COLLECTSTATIC=1 it works and I can remove it after. But it never works when it's enabled which it should be. Here a picture of my folder structure if it's needed https://drive.google.com/file/d/11L8jpFzYfDYT3Ob4G-soaGhL0pgU24iZ/view?usp=sharing ! Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used. Detected buildpacks: Python,Node.js See https://devcenter.heroku.com/articles/buildpacks#buildpack-detect-order -----> Python app detected -----> Installing python-3.6.6 -----> Installing pip -----> Installing dependencies with Pipenv 2018.5.18… Installing dependencies from Pipfile.lock (d438cb)… -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, … -
Django admin only show M2M elements once
I have a "training" model containing a ManyToManyField to a "trainer" model. Let's take the exemple "training 1" has 3 trainers "A" "B" and "C". And "training 2" only has one trainer "A". In my admin panel when I want to see all the trainings, it shows me something like: "training 1" : "A" "training 1" : "B" "training 1" : "C" "training 2" : "A" Because I already did an inline in order to get all the trainers from one entity, I would like it to only show one of each training, so something like: "training 1" : "A" "training 2" : "A" My models look like this : class Training(models.Model): name = models.CharField( max_length=60 ) trainer = models.ManyToManyField( Trainer, through='Training_trainer' ) class Trainer(models.Model): first_name = models.CharField( max_length=60 ) last_name = models.CharField( max_length=60 ) And my admin.py look like this : class Training_trainerInline(admin.TabularInline): model = Training.trainer.through extra = 3 class TrainingAdmin(admin.ModelAdmin): list_display = ('name', 'get_trainer') list_filter = ('trainer',) fieldsets = ( (None, {'fields': ('name',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('name', 'trainer')} ), ) search_fields = ('name', 'trainer',) ordering = ('name', 'trainer',) inlines = [Training_trainerInline, ] def get_trainer(self, obj): return "\n".join([str(p.trainer) for p in Training_trainer.objects.filter(training=obj)[:1]]) get_trainer.short_description … -
saving via model form in different database
# models.py class Type(models.Model): name = models.CharField(max_length=100, unique=True) created_at = models.DateTimeField(auto_now_add=True, editable=True) def __str__(self): return self.name #forms.py class TypeCreateForm(forms.ModelForm): class Meta: model = Type fields = "__all__" # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "default", 'USER': 'root', 'PASSWORD': 'abcd1234', 'HOST': '0.0.0.0', "PORT": "3306" }, 'database1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "database1", 'USER': 'root', 'PASSWORD': 'abcd1234', 'HOST': '0.0.0.0', "PORT": "3306" }, } #views.py def index(request): db_name=request.POST["db_name"] ob = TypeCreateForm(request.POST) for a in ob: if a.errors: print(a.errors.as_text()) ob=ob.save(commit=False) ob.save(using=db_name) Ok the problem is that I have a model in which a field is unique.I am inputting that field value from user in post body and wanted to save that via model form in a database that is also specified in post body I searched several similar question of saving into another database other than default.Some suggested commit=False will work along with save with using keyword argument. In some answer they suggested to do modification in queryset of the field. But I dont think that worked for me because in my model there is a unique constraint as well so when I will print the errors before saving it will show unique constraint failed if that type is stored in default … -
django def post method isnt working in cbv
i can't figure our why i can't override the post . when i post the form i go to "/" directory and nothing post . i already know knows that the forms works fine because i have it working as a fbv my view class ProfileUpdateView(LoginRequiredMixin, View): template_name = 'accounts/update.html' def get_object(self): user = get_object_or_404(User , username=self.kwargs.get('username')) return user def get(self, request , *args , **kwargs): user = get_object_or_404(User , username=self.kwargs.get('username')) user_form = UserForm(instance=user) if user.is_client: print("client get is working") profile = Client.objects.get(id = user.clients.id) profile_form = ClientForm(instance=profile) if user.is_artisan: profile = Artisan.objects.get(id = user.artisans.id) profile_form = ArtisanForm(instance=profile) return render (request , self.template_name , {"user_form":user_form, "profile_form":profile_form}) def post(self, request, *args, **kwargs): print("post is working") if user.is_client: print("client post is working") profile_form = ClientForm(request.POST,request.FILES, instance=profile) user_form = UserForm(request.POST,request.FILES, instance=user) if user.is_artisan: profile_form = ArtisanForm(request.POST,request.FILES, instance=profile) user_form = UserForm(request.POST,request.FILES, instance=user) if profile_form.is_valid() and user_form.is_valid(): print("form validation is working") created_profile = profile_form.save(commit=False) user_form.save() created_profile.save() reverse("accounts:profile" , kwargs={'username': self.user.username}) return render (request , self.template_name , {"user_form":user_form, "profile_form":profile_form}) template <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ user_form.as_p }} <p> client form</p> ------------------------------------------------ {{ profile_form.as_p }} <button class="btn btn-primary btn-round" type="submit">update</button> </form> -
Setting multiple MEDIA_URL & MEDIA_ROOT in django
I've set Static and Media root as well as url's in my django app, as follows: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/crl/' MEDIA_ROOT = os.path.join(BASE_DIR, 'config/crl/') It is working great, but I want to add another MEDIA_URL & MEDIA_ROOT to serve files from the /certs/ directory as follows: NEW_MEDIA_URL = '/certs/' NEW_MEDIA_ROOT = os.path.join(BASE_DIR, 'config/certs/') Is there any way to do it? I'm using Django 2.0.6 and Python 3.5 -
Using Bootstrap and Semantic UI together
I have a question. Is it possible to use Bootstrap and Semantic UI combined in a Django project? Please can you help me -
Django, nginx and gunicorn csrf cookie not set
I have got a setup with nginx, gunicorn and Django, running on docker containers. Nginx is used as a reverse proxy. Everything works fine, but for POST methods I get the error saying Forbidden (CSRF cookie not set.). The same configuration works fine locally, but on production (ec2 on aws), this doesn't work. Here is the nginx configuration: upstream web { ip_hash; server web:8000; } server { location / { alias /src/frontend/dist/; try_files $uri $uri/ /index.html; } location /static { alias /src/static/; try_files $uri =404; } # works locally, but doesn't work in prodcution on ec2 location /api/ { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://web; # pass to gunicorn # what to serve if upstream is not available or crashes # error_page 500 502 503 504 405 /error.html; } location @rewrites { rewrite ^(.+)$ /index.html last; } listen 80; server_name www.example.com; } I have checked the request headers and the cookie is not getting set. I have tried everything as suggest in SO. I have CsrfViewMiddleware set in the middlewares in Django settings. CSRF_COOKIE_SECURE & SESSION_COOKIE_SECURE are set to False. I have ran out of ideas and things to try. Please advice me on a solution. … -
How to execute Python from virtualenv for Django
I have installed Django 2.0.5 on CentOS 7 server with Python 3.7.0 following the instruction of DigitalOcean post. After adding conf file, I have got following error mod_wsgi (pid=21374): Target WSGI script '/home/user/myproject/myproject/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=21374): Exception occurred processing WSGI script '/home/user/myproject/myproject/wsgi.py'. Traceback (most recent call last): File "/home/user/myproject/myproject/wsgi.py", line 18, in <module> from django.core.wsgi import get_wsgi_application File "/home/user/myproject_env/lib/python3.7/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/user/myproject_env/lib/python3.7/site-packages/django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' Which indicates wsgi.py file executed by Python 2.7.5 which is my server's default Python version. To confirm this I have added version and $PYTHONPATH to error_log from wsgi.py. ERROR:root:Python Version: 2.7.5 ERROR:root:['/home/user/myproject', '/home/user/myproject_env/bin/python3.7', '/home/user/myproject_env/lib/python3.7/site-packages', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages'] It confirms that it is executing Python 2.7.5 instead Python 3.7.0. How can I change the Django Python Path to execute Python 3 from virtualenv? -
Django duplicate my entrie when i store something
When i try to save a post, the post i save, but the current user is not registered and the post is duplicate with a blank entry and the current user is not stored. For add post i not use the admin app but a personnel template and form. See the problem: See Image This is my view code: from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from .forms import NewAdminPostForm from .models import Post, Category # Create your views here. def home(request): posts = Post.objects.all() categories = Category.objects.all() posts_last = Post.objects.order_by('-created_at')[0:3] return render(request, 'front/blog-list.html', {'posts': posts, 'categories': categories, 'posts_last': posts_last}) @login_required def newadminpost(request): if request.method == 'POST': form = NewAdminPostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() Post.objects.create( message=form.cleaned_data.get('message'), category_id=post.category_id, created_by=request.user ) return redirect('listadminpost') else: form = NewAdminPostForm() return render(request, 'back/new-post-blog.html', {'form': form}) @login_required def listadminpost(request): posts = Post.objects.all() return render(request, 'back/list-post-blog.html', {'posts': posts}) Thank You -
Using pywin32 commands in Django
According to https://stackoverflow.com/a/28212496/9611931 a replacement for ulimit in Windows and I want to execute following lines of code in Django project. Where should I set this for Django.?? import win32file win32file._setmaxstdio(2048) Background : Specifically I want to remove Cstack limit error from Django App and i am trying this ulimit solution to remove this error -
python object has no has no attribute 'replace'
model.py -- enter image description here when I am trying replace "name" field value using filter it's showing 'Webpage' object has no attribute 'replace' enter image description here -
Django returning webpage instead of JSON
I am fairly new to Django and am trying to implement a basic REST API in Django. I am having a news list in MySQL Database, and following various tutorials, successfully managed to implement a webservice that responds the news list. http://127.0.0.1:8000/rest/news_infos/ The above URL(local) produces the following page: As you can see, I am getting a webpage here. But what I actually needed is that the above API to return just the json. I don't want to have this kind of pages available in my webservice, just the JSON response. Of course I can get it json only by appending format=json to the request. But that is not what I require. I want the web page to be gone and calling http://127.0.0.1:8000/rest/news_infos/ to return the json instead. Following is my views.py code: from rest_framework import viewsets from .models import NewsContent, NewsInfo from .serializers import NewsContentSerializer, NewsInfoSerializer class NewsContentViewSet(viewsets.ViewSet): queryset = NewsContent.objects.all()[:10] serializer_class = NewsContentSerializer class NewsInfoViewSet(viewsets.ModelViewSet): queryset = NewsInfo.objects.all()[:10] serializer_class = NewsInfoSerializer Please let me know if any other code/info is required. Couldn't find any proper solution online. -
Django : Images not shown on template on using media_root under static_cdn
My settings.py file contains the following: STATIC_URL = '/static/' STATICFILES_DIR = os.path.join(BASE_DIR,'static_blog') STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),'static_cdn','static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'static_cdn','media_root')' and urls.py file contains the following: from django.contrib import admin from django.urls import path from django.conf.urls import url , include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), url('^', include('enc_vip_blog.urls')), ] and on running collectstatic command the project got a directory structure as follows: static_cdn ----> media_root ----> and the image I uploaded My models.py has image field as shown: image = models.ImageField(upload_to='blog/',null=True,blank=True) Still on running the applicaton I am able to see all the stuffs instead of the image. I have used the following in the templates <ul>{%for object in object_list%} <!--use--> <!--<li><a href="{% url 'detail' slug=object.slug%}">{{ object.title }}</a></li>--> <!--or--> <li><a href="{{ object.get_absolute_url }}">{{ object.title }}</a></li> {{ object.body }} {%if object.image%} <img src="{{ object.image.url }}"> {%endif%} {{ object.created }} tagged under {{ object.tags.all|join:', ' }} {%endfor%} </ul> All the stuffs like title , body etc are shown except the image In admin when I try to browse the uploaded image using the link it gives an error? Thanks in advance for any help provided? -
Checking for a Range of Values
I could check for a range of values, use the BETWEEN operator. MySQL [distributor]> select prod_name, prod_price from products where prod_price between 3.49 and 11.99; +---------------------+------------+ | prod_name | prod_price | +---------------------+------------+ | Fish bean bag toy | 3.49 | | Bird bean bag toy | 3.49 | | Rabbit bean bag toy | 3.49 | | 8 inch teddy bear | 5.99 | | 12 inch teddy bear | 8.99 | | 18 inch teddy bear | 11.99 | | Raggedy Ann | 4.99 | | King doll | 9.49 | | Queen doll | 9.49 | +---------------------+------------+ 9 rows in set (0.005 sec) I reference to django docs and found gte, gt, lt, lte but no between. How could I achieve the between functionality? -
Django - TinyMCE cant save content in form
i currently try to implement TinyMCE (django-tinymce4-lite/ - http://romanvm.github.io/django-tinymce4-lite/) into my Webproject but for some reasone i'm unable to save content of that field in my frontend form. I i do it from the django admin backend its working flawless. models.py: #Post Model class Post(models.Model): author = models.ForeignKey('accounts.User', on_delete=models.CASCADE) title = models.CharField(max_length=75) content = HTMLField('Content') tag = models.CharField(max_length=50, blank=True) ... base.html: <!DOCTYPE html> <html lang="en"> <html> <head> **{{ form.media }}** <title>{{ settings.SITE_NAME }}</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-theme.min.css' %}"> ... forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'category', 'tag', 'postcover', 'postattachment',] **content = forms.CharField(widget=TinyMCE(mce_attrs={'width': 800}))** ... any idea why im ubale to save the content at the frontend form? thanks for reading -
Creating django ImageField that is derived from another ImageField in django Models
I am creating a django Project where I had Stored a Picture(Image) in database using ImageField as... original_pic = models.ImageField() Also, I want to Store an Image which will Contain the Same Picture(Image) as original_pic with Watermark in another ImageField as.. watermark_pic = models.ImageField(default=watermarkImage()) In short, I just want to Apply Algorithm on original_pic and save the result in watermark_pic using django models Note: I know the Algorithm for Applying watermark on Image. -
Show first name and last name of user in modelform when User model is used as foreign key
In Django, I have a model that uses the User model as a foreign key: class Message(models.Model): authors = models.ManyToManyField(User) ... I use the ModelForm to create a form: class MessageForm(ModelForm): class Meta: model = Message fields = ['authors'] However, when this form is created, it will show a select on the page that lists the users using their username. I'd like to show their first and last name instead (or, if that's easier, just their first name). How do I achieve this? -
Best tool for simple automated deployment with Django
For a Django project, I'm looking for a tool that would: update the code on my server from a given branch in a remote repository (example: a master branch from Bitbucket) run basic django command (migrate, collectstatic, etc...) restart the project notify me that all went ok (on Slack for instance) I've seen many possible ways of doing this (Ansible, DeployBot, Pipelines, etc...), but I was wondering if there is a tool to recommend for a simple app? -
Get Link for url by clicking on chart label
I need to create link for url in djano dynamically when user clicks on particluar label on chart like when user click in chart on column on 26/06/2018 url should be like 26/06/2018/get_data/. I am using jquery. $("#chart-1").on('click', function (test,key){ //chart ID var label = $('#test'); //div containing data in json var text = jQuery.parseJSON(label.text()); jQuery.each(text, function(i, val) { var array = [] jQuery.each(val,function(key,label){ $('rect').addClass('myclass'); var index = label['label'].indexOf('Undefined'); if (index !== -1) label['label'].splice(index, 1); array.push(label['label']); var url = "{% url 'log:get_data'%}"; var id = array[1]; var url2 = (id + url); console.log(url2) document.location.href = url2; }); }); Including image for the chart -
how to convert datetime from certain timezone to UTC ? django DateTimeField
I am having trouble dealing with dealing with DateTimeField field. The question is, lets say i created datetime with timezone like that x = datetime.tzinfo("Asia/Kuala_Lumpur") y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x) i want to convert "y" to UTC so that I can save it to DateTimeField How do I do that ? Here is rest of my console test >>> a = Attendance.objects.last() >>> a <Attendance: wawa> >>> a.updated_at datetime.datetime(2018, 7, 29, 13, 37, 26, 459259, tzinfo=<UTC>) >>> a.updated_at = timezone.now() >>> a.updated_at datetime.datetime(2018, 8, 11, 8, 49, 5, 381198, tzinfo=<UTC>) >>> a.updated_at = timezone.now() >>> a.updated_at datetime.datetime(2018, 8, 11, 8, 52, 33, 243825, tzinfo=<UTC>) >>> x = datetime.tzinfo("Asia/Kuala_Lumpur") >>> y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x) >>> y datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=<datetime.tzinfo object at 0x113ac6600>) >>> y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x) >>> y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x) >>> a.updated_at = y >>> a.updated_at datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=<datetime.tzinfo object at 0x113ac6600>) >>> a.save() >>> a = Attendance.objects.last() >>> a.updated_at datetime.datetime(2018, 8, 11, 13, 21, 2, 38046, tzinfo=<UTC>) -
Query with Django doesn't work
im new to Django and Python and this is my first post here!: So I've been trying to "print" in some website I made with Django some objects from a database that I made with HeidySQL. The app inside django is called users. So 127.0.0.1:8000/users , inside this i have another page in 127.0.0.1:8000/users/login that is loading fine. I successfullly synced this DB with django, I even managed to see some rows in the django shell, so I concluded everything seems to be connected well. This login.html file atm has this: {% block content %} <h1>{{ allcharacters_query }} </h1> {% for lista in characters_list %} {{ lista.name }} {% endfor %} </body> {% endblock %} The issue is that it doesnt display the names of my characters_list. Here is my views.py: from django.http import HttpResponse from django.shortcuts import render from users.models import Characters from django.template.response import TemplateResponse def index (request): return render(request,'users/home.html') def return_charnames (request): allcharacters_query = Characters.objects.all() return render(request, 'users/login.html',{"allcharacters_query": allcharacters_query}) And this my urls.py file: from django.conf.urls import url, include, patterns from .import views from django.contrib.auth.views import login urlpatterns = [ url(r'^$', views.index,name='index'), url(r'^login/$',login,{'template_name': 'users/login.html' }) ] I dont really know how to fix this, I read lots …