Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django InconsistentMigrationHistory
I'm trying to setup a Django project and am faced with the following error: WARNINGS: ?: (rest_framework.W001) You have specified a default PAGE_SIZE pagination rest_framework setting,without specifying also a DEFAULT_PAGINATION_CLASS. HINT: The default for DEFAULT_PAGINATION_CLASS is None. In previous versions this was PageNumberPagination. If you wish to define PAGE_SIZE globally whilst defining pagination_class on a per-view basis you may silence this check. Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 82, in handle executor.loader.check_consistent_history(connection) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/db/migrations/loader.py", line 291, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration events.0001_initial is applied before its dependency commons.0001_initial on database 'default'. make: *** [migrate] Error 1 I am running this from within a virtual environment, and have a docker-compose container for a postgres db running. Not sure how to start debugging this or why its happening. Any help would be appreciated -
Why is python manage.py runserver not working?
Using this code use to work C:\Users\HP>project2_env\scripts\activate (project2_env) C:\Users\HP>cd C:\Users\HP\django_project3 (project2_env) C:\Users\HP\django_project3>python manage.py runserver Today when I tried to run python manage.py runserver the computer just hung. I could not run any SQL queries on my websites database (using CMD). Although I could load the website within Google Chrome. The computer simply got this far. System check identified no issues (0 silenced). December 02, 2019 - 12:36:39 Django version 2.2.6, using settings 'django_project3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [02/Dec/2019 12:37:19] "GET / HTTP/1.1" 200 3667 When I ran the python command I got this error message (project2_env) C:\Users\HP\django_project3>python Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 Warning: This Python interpreter is in a conda environment, but the environment has not been activated. Libraries may fail to load. To activate this environment please see https://conda.io/activation In Anaconda Prompt I ran this code but the problem still persisted. (base) C:\Users\HP>C:\Users\HP\Anaconda3\Scripts\activate base Can someone give me tips on solving the problem or does anyone have any idea what settings I need to check? -
Why do Django-admin commands recommend using self.stdout() vs print()?
The documentation on writing custon django-admin commands includes the following: When you are using management commands and wish to provide console output, you should write to self.stdout and self.stderr, instead of printing to stdout and stderr directly. By using these proxies, it becomes much easier to test your custom command. Note also that you don’t need to end messages with a newline character, it will be added automatically, unless you specify the ending parameter: self.stdout.write("Unterminated line", ending='') I'm not quite satisfied with this explanation as it doesn't really explain why it's "much easier to test your custom command." Does anyone have a good example or can expand further on what they're getting at? I wrote a custom command using print() statements and had no issues testing, but it feels like I may be missing out on some features. -
Postgres Materialized Path - What are the benefits of using ltree?
Materialized Path is a method for representing hierarchy in SQL. Each node contains the path itself and all its ancestors (grandparent/parent/self). The django-treebeard implementation of MP (docs): Each step of the path is a fixed length for consistent performance. Each node contains depth and num_child fields (fast reads at minimal cost to writes). The path field is indexed (with a standard b-tree index): The materialized path approach makes heavy use of LIKE in your database, with clauses like WHERE path LIKE '002003%'. If you think that LIKE is too slow, you’re right, but in this case the path field is indexed in the database, and all LIKE clauses that don’t start with a % character will use the index. This is what makes the materialized path approach so fast. Implementation of get_ancestors (link): Match nodes with a path that contains a subset of the current path (steplen is the fixed length of a step). paths = [ self.path[0:pos] for pos in range(0, len(self.path), self.steplen)[1:] ] return get_result_class(self.__class__).objects.filter( path__in=paths).order_by('depth') Implementation of get_descendants (link): Match nodes with a depth greater than self and a path which starts with current path. return cls.objects.filter( path__startswith=parent.path, depth__gte=parent.depth ).order_by( 'path' ) Potential downsides to this approach: … -
How to store the user input in dynamic web pages to local storage in django using javascript?
I am learning django through the videos. I am trying a web application like this given link https://www.modsy.com/project/room, so I dynamically got the html pages data from the database And my html code is ><div class="row"> {% for i in room %} <div class="col-4"> <div class="card6 mt-3" style="width: 12rem;"> <img src="{{i.image.url}}" alt="..." width="185" height="100"> <div class="card-body"> <p class="card-text"><b>{{i.content}}</b></p> </div> </div> </div> {% endfor %} </div> So on click of any card by the user and click the next button the imagepath,content and id should store in the local storage in console. Can you please help me how can i achieve this with an example.Thanks in advance -
How to get a http long connection by django and requests?
Some articles said if the http server and http client both use Connection: keep-alive in there header, then the tcp connection will be a long connection. So I did my test below. Client code: import requests import time url = 'http://server url' def session_req(url): s = requests.Session() r = s.get(url, headers={'Connection':'keep-alive'}) print(r.headers) print(r.status_code) while True: time.sleep(10) if __name__ == '__main__': session_req(url=url) From the client print we can see the server add Connection: keep-alive too But the tcp connection still not a long connection. # ss -tan FIN-WAIT-2 0 0 server ip:8004 client ip:40238 As you can see the tcp is not established So anything wrong about my code? How to make a long http connection? -
Django adding multiple m2m related model records using .set works fine, but how to also add additional model fields other than ids?
I have photos model and tags model with m2m relationship through phototags model. class Photo(models.Model): tags = models.ManyToManyField(Tag, through = 'PhotoTag', related_name="tags") In a view I create a list of tag ids that I use in photo.tags.set(form_tags_ids) to create the new phototag relationships. This works fine and successfully populates both photo_id and tag_id fields in phototags model. However, I also have other additional fields in phototags model, other than the related models' ids, that I want to populate at same time eg created date, user_id to record who made relationship and when it was created. What would be best way to populate these other columns? The only thing I can think of is to not use .set and loop through the list of tag ids and manually create the phototag records but then I lose benefit of m2m in avoiding duplicate assignment of tag to photo, etc. -
How to pass data from one view another view using sessions in django?
HTML <div class="content-section"> <form method="GET" action="{% url 'doctor:search' %}"> <input name ="q" value="{{request.GET.q}}" placeholder="search.."> <button class="btn btn-success" type="submit"> Search </button> </form> </div> I want to save {{request.GET.q}} from this html into session variable and use it in all the views ORIGINAL VIEWS.PY class SearchResultsView(ListView): model = Search template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content', 'comment'] def form_valid(self, form): query = self.request.GET.get('q') form.instance.author = self.request.user form.instance.patient = User.objects.get(username=query) return super().form_valid(form) [query = self.request.GET.get('q')] in 'SearchResultsView' and in 'PostCreateView' needs same value. I want to use input value from html and use it in both these classes using session variable VIEWS.PY Trying to implement session variable class SearchResultsView(ListView): model = Search template_name = 'all_users/doctor/search.html' def get_queryset(self): # new **request.session['query'] = self.request.GET.get('q')** **query = request.session['query']** object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content', 'comment'] def form_valid(self, form): **query = request.session['query']** form.instance.author = self.request.user form.instance.patient = User.objects.get(username=query) return super().form_valid(form) When i use this code i get "name 'request' is not defined" error. -
Django - Multiple user types (ability to switch between them)
I am doing some pre-planning on a project I am working on and my approach to it. A part of the app is the ability to have multiple user types. For example, a Company and a Contractor account type. Though it's important to note that a company can also be a contractor. So the approach I was going to attempt to implement is similar to Upwork where there is one account, but they can switch between being a client and a freelancer if they wish. It would be ideal if the user didn't need to log out while switching between the two. I'm newer to the django framework and was hoping someone could shed light on the best possible approach to accomplish this while also taking into account scale-ability. -
Django Changing Content Based on Menu Selection
I have a todo website that allows users to put reminders in a certain list. I have a dropdown menu with all lists the user has created. I want content in a div to be changed based on what the user selects, and found a solution with javascript here. I have a custom template tags that returns unique ids and reminders: <div class="col-md-6 inline mb-5"> <div style="display: flex;"> <h3 class="ml-2">Reminders:</h3> <div class="ml-2" style="margin-bottom: -5px;"> <select class="dropdown" placeholder="Sort By:" id="remind_sort"> {% get_dropdown_ids user.username as dropdown_ids %} {% for option_id, list_item in dropdown_ids.items %} <option value="{{ option_id }}">{{ list_item.title }}</option> {% endfor %} </select> </div> </div> {% get_list_items_ids_regular user as list_ids %} {% for div_id, reminder_list in list_ids.items %} <div class="group events-content-section ml-2" id="{{ div_id }}"> {% for reminder in reminder_list %} <div class="mb-2" style="display: flex; align-items: center;"> <ul class="reminderUl"> <li> <span class="reminderSpan"> <button type="button" class="update-reminder btn btn-info" data-id="{% url 'update-reminder' reminder.pk %}"> <i class="fas fa-pencil-alt"></i> </button> </span> <span class="reminderSpan"> <button type="button" class="delete-reminder btn btn-danger" data-id="{% url 'delete-reminder' reminder.pk %}"> <i class="fas fa-trash-alt"></i> </button> </span> <button class="view-reminder btn btn-light" data-id="{% url 'view-reminder' reminder.pk %}"> <h4>{{ reminder.title }}</h4> </button> </li> </ul> </div> {% endfor %} </div> {% endfor %} </div> <script type="text/javascript"> $(document).ready(function … -
Django, cloudflare for media files
I've setup cloudflare with one of my s3 bucket. using AWS_S3_CUSTOM_DOMAIN It works fine for reading the contents, but it has problem with uploading images to the bucket. How do I upload images to the s3 bucket directly, and use cloudflare cdn for read? -
Django - forms.ChoiceField without using model
I want to create a form to select an option without using a model for it. For some reason form is not showing up on the template. I tried below code, could someone help me with this? form.py class selectPostType(forms.Form): STATUS_CHOICES = (('1', 'Text Post'),('2', 'Image Post'),('3', 'Video Post'),) post_type = forms.ChoiceField(choices=STATUS_CHOICES) views.py def selectPostType(request): form = selectPostType return render(request,'selectPostType.html',{'form':form}) html <form action='.' method="post"> {% csrf_token %} {{ form }} <button class='btn btn-default' type='submit'>Select</button> </form> -
How do I get audio duration for the FileField in Django?
Consider having this model: class MusicTrack(models.Model): """ Represents a music track """ title = models.CharField("Track title", max_length=300) audio_file = models.FileField("Audio file", upload_to='audio/%Y-%m-%d/') duration_seconds = models.PositiveIntegerField("Track duration ins seconds", blank=True, null=True) def __str__(self): return f"Music track \"{self.title}\"" How do I get the audio duration in seconds and save it in the database? -
Django Looping Through Objects to Place Object Markers on Google Maps
I cannot figure out how to get checkmark pins to show up on google maps I have tried to loop this several different ways. When I take the function out the map shows back up. I am wondering if it is possible to do on Django in this manner. Thank you for any help. {% extends 'maps/base.html' %} {% block body %} <head> <style> #map { height: 50%; width:50% } html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 2, center: new google.maps.LatLng(2.8,-187.3), mapTypeId: 'terrain' }); // Loop through the results array and place a marker for each // set of coordinates. function loadMarkers(){ {% for object in object_list %} var point = new google.maps.LatLng({{object.latitude}},{{object.longitude}}); var marker = new google.maps.Marker({ position: point, map: map }); {% endfor %} </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"> </script> </body>''' -
Resolving sub-domains for Django multi-tenancy sites
A site I just got up is resolving the normal pages at the server IP address (eg. XXX.XXX.XXX.XXX) but when I create a new tenant the sub-domains are not resolving (eg. tenant.XXX.XXX.XXX.XXX). I tried adding the sub-domain URL to the host file /etc/hosts but this did not work. I am looking into DNS servers but this looks like every sub-domain would redirect to the main URL which is not what I want since every tenant has their own schema accessed through the sub-domain. Is this true? Or do DNS servers just handle pointing everybody to the correct server? How do I handle sub-domains for multi-tenancy apps on a server? -
How to periodically repeat a function until success in background in Django?
I'm working on a Django project. I want to do a http request to an external server. But sometimes the external server returns 5xx. I want to retry request on the background until it returns 200. How can I do this? This is a pseudo code of what I want to do: response = requests.post(url, json=param) if response.status_code == 200: # do something elif response.status_code >= 500: # schedule task to retry every 30 seconds until success -
How do I create or update a model in Django based on a unique identifier?
I'm using Python 3.7. I want to create a record or update one if it exists so I was using the most voted solution here -- Create Django model or update if exists . However, I'm getting a django.core.exceptions.FieldError: Invalid field name(s) for model MyObject: 'identifier'. error when I run my code. I'm using this my_object, created = MyObject.objects.update_or_create( identifier=path, defaults={"title": title} ) Where my model with my unique constraint is defined below class MyObject(models.Model): title = models.TextField(default='', null=False) path = models.TextField(default='', null=False) url = models.TextField(default='', null=False) votes = models.IntegerField(default=0, null=False) updated_at = models.DateTimeField(null=True) class Meta: unique_together = ("path", ) What else do I need to do to get this working? -
How to get fullchain.pem on heroku
Here we need fullchain.pem on heroku to test a test application that works on WebSockets. How to get it? -
Render a template on nav item click in block content without loading the whole page (Django)
Hell guys, I'm still trying to learn so please dont be harsh :) I'm trying to find a way to render templates in block content. Example Nav items About Contact FAQ Our team If the user clicks on About page (About.html) It renders it in the {block content}without reloading or refreshing the page. If the user then clicks on Contact us the {block content} gets updated with the Contact us page (Contact.html) Is there any way you can do this in Django without using Ajax or Jquery. if not is there somewhere good documentation I can follow to do this? I've been searching the internet for any answers but I can't find anything on this exact matter only found Pjax https://github.com/defunkt/jquery-pjax but I'm a bit afraid of using Ajax and my knowledge regarding Ajax is not really great. Thank you for reading this and for your time. Kind Regards, -
Django user permission to update blog is not working
I have been trying to work with Django permissions on my website, and cannot establish permissions correctly. I've read around nine different websites and have been stuck on this for hours. I don't know how to correctly set the update permissions for my blog posts. I have an app called 'blog' and files for it like models.py, views.py, and the update.html displaying the update a blog using forms. blog.models.py from django.db import models from django.conf import settings from django.utils import timezone from django.db.models import Q from django.contrib.auth.models import Permission User = settings.AUTH_USER_MODEL class BlogPostQuerySet(models.QuerySet): def published(self): now = timezone.now() return self.filter(publish_date__lte=now) def search(self, query): lookup = ( Q(title__icontains=query) | Q(content__icontains=query) | Q(slug__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) | Q(user__username__icontains=query) ) return self.filter(lookup) class BlogPostManager(models.Manager): def get_queryset(self): return BlogPostQuerySet(self.model, using=self._db) def published(self): return self.get_queryset().published() def search(self, query=None): if query is None: return self.get_queryset().none() return self.get_queryset().published().search(query) class BlogPost(models.Model): # blogpost_set -> queryset user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) images = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) # Example: "hello world" -> hello-world content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = BlogPostManager() class Meta: ordering = ['-publish_date','-updated','-timestamp'] permissions = [ ('can_change','Can … -
TemplateDoesNotExist at /post/15/ post_detail..... what is the problem?
i have made an blog page and now i am just trying to add more features. when i add a new post after attaching the imagefile, it says TemplateDoesNotExist at /post/(post number)/post_detail. but meanwhile new post can be seen in first page with image. blog/views.py: from django.views.generic import ListView,DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Post from django.urls import reverse_lazy class BlogListView(LoginRequiredMixin,ListView): model=Post template_name='home.html' login_url='login' class BlogDetailView(LoginRequiredMixin,DetailView): model=Post template_name='post_detail' login_url='login' class BlogCreateView(LoginRequiredMixin,CreateView): model=Post template_name='post_new.html' fields=('title','body','image') login_url='login' def form_valid(self,form): form.instance.author=self.request.user return super().form_valid(form) class BlogUpdateView(LoginRequiredMixin,UpdateView,UserPassesTestMixin): model=Post template_name='post_edit.html' fields=('title','body','image') login_url='login' def test_func(self): obj=self.get_object() return obj.author==self.request.user class BlogDeleteView(LoginRequiredMixin,DeleteView,UserPassesTestMixin): model=Post template_name='post_delete.html' success_url=reverse_lazy('home') login_url='login' def test_func(self): obj=self.get_object() return obj.author==self.request.user blog/urls.py: from django.urls import path from .views import ( BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, BlogDeleteView, ) from django.conf import settings from django.conf.urls.static import static urlpatterns=[ path('',BlogListView.as_view(), name='home'), path('post/new/',BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/edit/',BlogUpdateView.as_view(), name='post_edit'), path('post/<int:pk>/',BlogDetailView. as_view(), name='post_detail'), path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'), ] if settings.DEBUG: urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) pages/templates/postdetails.html: {% extends 'base.html' %} {%load static%} {% block content %} <div class="container"> <!-- Page Heading/Breadcrumbs --> <h1 class="mt-4 mb-3">{{object.title}} <small>by <a href="#">{{object.author}}</a> </small> </h1> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="/">Blogs</a> </li> <li class="breadcrumb-item active">Blog Post Detail</li> </ol> <a href="{%url 'post_edit' post.pk%}">+Edit this posts</a> <div class="row"> <!-- Post … -
In Python/Django, how do I import one service I created from another one I created?
I'm using Pyton 3.7 and Django. I have a directory where I keep my services my_project my_app services __init__.py foo_service.py bar_service.py "init.py" is empty. Within "foo_service.py", I define class "FooService" and within "bar_service.py," I define class "BarService." How do I import BarService in FooService? I tried import services.bar_service but got the error ModuleNotFoundError: No module named 'services' -
Is there any way to create a program what run inside a server?
Currently I am creating web application in Django and for one user request I have to make more requests to database. So, I think like creating a program that will handle all the database requests in the mid way. So, I don't have to send requests per each user.I know how to make that program. The problem is how can I make that program and web app in the same server? Is there any chance? Note: I will host my app on own server. Not on others. -
django dropdownlist showing object id instead of names
i have two apps in 1)boq 2)inputs inputs has a model building class building(models.Model): building = models.CharField(max_length=300 my boq app has a model boqmodel class boqmodel(models.Model): code = models.IntegerField() building =models.CharField(max_length=300) level = models.CharField(max_length=300) activity = models.CharField(max_length=300) subactivity = models.CharField(max_length=300) duration=models.IntegerField() linkactivity= models.CharField(max_length=300) linktype= models.CharField(max_length=300) linkduration=models.IntegerField() plannedstart=models.DateField() plannedfinish=models.DateField() actualstart=models.DateField() actualfinish=models.DateField() i have a form in boq app as follows class boqform(forms.ModelForm): class Meta: model = boqmodel fields = ['code', 'building', 'level', 'activity', 'subactivity', 'duration', 'linkactivity', 'linktype', 'linkduration', 'plannedstart', 'plannedfinish', 'actualstart', 'actualfinish'] building coloumn is same in boq and inputs app i need to have a drop down in boq form for building with values from model in inputs.building model -
Related if in one of two fields in Django
I want to have two m2m related fields in my model admins and users but specified Profile can but in of admins or users in one Session. What is the best way to resolve it? class Session(models.Model): admins = models.ManyToManyField(Profile, related_name='admins') users = models.ManyToManyField(Profile, related_name='users')