Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM - How to delete items with identical field if the datefield is bigger than in others dublicates?
So I have a Comments model and by querying comments = Comments.objects.values('students_id', 'created_at') I get this output <QuerySet [ {'students_id': 4, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 2, 'created_at': datetime.date(2019, 6, 3)}, {'students_id': 1, 'created_at': datetime.date(2019, 6, 24)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 4)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 5, 'created_at': datetime.date(2019, 6, 5)}, {'students_id': 4, 'created_at': datetime.date(2019, 7, 28)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 11)}]> It's three comments by student with id=6 and two comments by student with id=4. What I need to get is only one latest comment from every student. In this example it'll look like this: <QuerySet [ {'students_id': 2, 'created_at': datetime.date(2019, 6, 3)}, {'students_id': 1, 'created_at': datetime.date(2019, 6, 24)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 5, 'created_at': datetime.date(2019, 6, 5)}, {'students_id': 4, 'created_at': datetime.date(2019, 7, 28)},]> Thanks in advance for the answer! -
What pattern to use for invoking web service (SOAP) with complex parameters
I have to call a SOAP web service method with rather complex data (~40 attributes with some of them being of complex types). The transformation Django Model Data -> SOAP WS Data is not trivial. Currently, I use suds.client.Client for invoking the WS, and I'm already able to instantiate all WS data types using the Client.factory.create method. The question is about: what pattern to use? I would like to validate the data before handling it over to the WS, something like DTO (which some people classify as anti-pattern). I wouldn't like to put all the transformation logic into the view. I already have a little WS wrapper to be able to do any transformations / validations before invoking the WS method. Here are some alternatives: Direct: Make a the WS wrapper accept any required data, validate and transform it to suds WS data instances. Plain Old Python Object: Create a simple Python object, instance and populate it in the view and pass it to WS wrapper which should validate and transform it to WS data before sending it over. (Now we have a clear separation between any django form / instance data and the WS data, the passed object serves … -
How should I create a filter form while having Models with relationships and I want to include fields from other models
I am developing the backend of my web application. First I show the models: class School(Model): name = ... rank = ... class Program(Model): id = ... length = ... campus = ForeignKey(Campus) class Campus(Model): name = ... school = ForeignKey(School) city = ForeignKey(City) class City(Model): population = ... city = ... province = ForeignKey(Province) class Province(Model): province = ... country = ForeignKey(Country) class Country(Model) country = ... population = .... I have so many questions and problems here. What I want to do is to create a filter form to filter programs based on their country, city, province, campus, and school. My first question: There is a package named django-filters . Do you recommend using this? is it trustable? Is it better to use this package or build a form and send the form and get them and build the query-set, with which I will show the filtered programs in a template? My second Question: If I want to have a form using built-in Django ModelForm and I want to include city, province, country, campus name, and even city population in my form, how should I do this? Suppose I want to show programs that are in a country … -
Django: Count of ManyToMany field in PositiveIntegerField during save() in a models.py
I want to alter the count of a ManyToMany Field during save of my model. For which I modified the save(). If I run save(), count will not be updated. If I run save second time without updating the field it will update the count. class UserProfile(models.Model): follower = models.ManyToManyField('self', related_name='Followers', blank=True, symmetrical=False) following = models.ManyToManyField('self', related_name='Followings', blank=True, symmetrical=False) follower_count = models.PositiveIntegerField(null=True, blank=True, editable=False) following_count = models.PositiveIntegerField(null=True, blank=True, editable=False) class Meta: verbose_name = 'User Profile' verbose_name_plural = 'User Profiles' def __str__(self): return self.follower_count def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) self.following_count = self.following.all().count() self.follower_count = self.follower.all().count() super(UserProfile, self).save(*args, **kwargs) I want to update count with single save(). -
Django edit view does not show
I am new to Django. My app allows a user to create a project by providing a title and a body content, delete it and update it. Now, I am creating and edit/update view for my app but it is not showing up in my html page. urls.py from django.urls import path, include from . import views urlpatterns = [ path('allprojects', views.allprojects, name='allprojects'), path('createproject', views.createproject, name='createproject'), path('<int:project_id>', views.projectdetail, name='projectdetail'), path('<int:project_id>/editproject', views.editproject, name='editproject'), ] projects/views.py @login_required def editproject(request, project_id): if request.method == 'POST': if request.POST['title'] and request.POST['content']: project = get_object_or_404(Project, pk=project_id) project.title = request.POST['title'] project.content = request.POST['content'] project.developer = request.user project.save() return redirect('/projects/' + str(project.id)) else: return render(request, 'projects/' + str(project.id) + 'editproject.html', {'error':'All fields are required.'}) else: return render(request, 'projects/allprojects.html') projects/templates/projects/editproject.html {% extends 'base.html' %} {% block title %}Edit Project{% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="mt-4 offset-md-3 col-md-6"> <h2>Create a new project</h2> <form method="put"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlTextarea1">Title of the project</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="1" name="title"></textarea> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Brief description of this project</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="5" name="content"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> {% endblock %} PROBLEM When I go to a urls such as … -
Can I dynamically set field names in Django orm query?
Can I dynamically set field names in Django view? I want this code CategoryNick.objects.get(author=self.request.user).get(field=slug) but error is occured AttributeError: 'CategoryNick' object has no attribute 'get' Is there a good way to solve this problem? if you know solution thank you for let me know total code def get_context_data(self, *, object_list=None, **kwargs): context = super(type(self), self).get_context_data(**kwargs) context['posts_without_category'] = MyShortCut.objects.filter(category=None,author=self.request.user).count() context['category_list'] = Category.objects.all() slug = self.kwargs['slug'] if slug == '_none': context['category'] = 'no_category' else: category = Category.objects.get(slug=slug) context['category'] = category context['category_nick'] = CategoryNick.objects.get(author=self.request.user).get(field=slug) return context -
Django apache2 authentication with remote_user and local db
i' ve a Django application with the following parameters: Debian: 9.9 Apache2: 2.4.25-3+deb9u7 Django: 2.2.1 Mysql: mariadb-server-10.1 . For the authentication i' d like to use remote authentication but through the local database. Is there any authentication class for it? My goal is to have the apache2 pop- up for authentication, but the authentication data should not come - for instance - from ldap, but from the local database, and the REMOTE_USER variable should be also set. My current apache conf file looks like this now: <VirtualHost *:80> ServerName 127.0.0.25 ServerAlias infokom.localhost prj.256.hu prj.128.hu DocumentRoot /usr/share/prj <Directory /usr/share/prj> Order allow,deny Allow from all </Directory> WSGIDaemonProcess prj.djangoserver user=prj processes=10 threads=20 display-name=%{GROUP} python-path=/usr/share/prj:/home/prj/.virtualenvs/prj/lib/python3.5/site-packages WSGIProcessGroup prj.djangoserver WSGIScriptAlias / /usr/share/prj/prj/wsgi.py CustomLog ${APACHE_LOG_DIR}/prj-access.log combined ErrorLog ${APACHE_LOG_DIR}/prj-error.log LogLevel debug </VirtualHost> . The wsgi.py file is simply: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cworld.settings') application = get_wsgi_application() . The related settings.py parts: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.RemoteUserBackend'] . With this current setup when log is required, it redirects me to the login page (e. g.: /accounts/login/?next=...), but i rather would like to have here the apache2 popup for authentication. -
Specify PORT in Django Dockerfile using Cloudrun
I have a basic Django 2 app (the starterproject) running locally in a Docker container. This works fine and i can access site. I would like to deploy the container using Google Cloudrun service and I see in their documentation it's required to specify the PORT environment variable. I have tried many differnet configurations but I just cannot make it work. I always get the error: Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information. The logs have no information. My base Docker file is: FROM python:3.7-alpine ENV PYTHONBUFFERED 1 COPY ./requirements.txt ./requirements.txt RUN pip install -r ./requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user RUN chown -R user:user /app RUN chmod 755 /app USER user and my docker-compose file is: version: "3" services: app: build: context: . ports: - "$PORT:8000" volumes: - ./app:/app command: sh -c "python manage.py runserver 0.0.0.0:8000" The troubleshooting is here: https://cloud.google.com/run/docs/troubleshooting Where and how do i use the PORT environment variable correctly? All help appreciated, Jon -
How to redirect any url to "404.html" in Django
I have such problem that, I can't redirect my application to "404.html" when user enters wrong url. I know, it is required to set DEBUG=False and ALLOWED_HOSTS=['*'], but still I am getting "Server Error 500", or css is missing. -
Django: Filter Queryset dynamically on template action
I want to filter a queryset dynamically on some template action. e.g. a Dropdown for the School Year so i only display the results for the chosen year. Where do i need to define this behaviour, directly in the view or filter it in the template? I already tried to filter in the view but im struggling to get the correct entries from my Course Mode. I dont know how I am able to get the Year Information from my Course from my already filtered CourseGrade Queryset. A simple course_info = Course.objects.filter(id=student_grades.course.pk) is not possible as i would do it in the template. class Course(models.Model): import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year+2)): YEAR_CHOICES.append((r,r)) name = models.CharField(choices=course_names, max_length=32) teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True, blank=True) school_year = models.IntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year) half_year = models.IntegerField(choices=course_halfyear, default=1) g def __str__(self): return self.name class CourseGrade(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) grade = models.DecimalField(validators=[MinValueValidator(1), MaxValueValidator(6)], null=True, blank=True, decimal_places=1, max_digits=2) course_type = models.CharField(choices=course_types, max_length=1, null=True, blank=True) class Meta: unique_together = ["student", "course"] def __str__(self): return '{0}: {1}'.format(self.student, self.course.name) def student_grade(request): current_student = get_object_or_404(Student, user=request.user) student_class = School_Class.objects.filter(student=current_student) student_grades = CourseGrade.objects.filter(student=current_student).order_by('course') context={'current_student': current_student, 'student_grades': student_grades, 'student_class': student_class} return render( request, 'bgrade/student/student_grade.html', context) The expected … -
how to fix django.db.utils.ProgrammingError: relation "blog_no_of_views" does not exist
i am new to django , i was using sqlite for development and now when i switched to postgresql, i am getting below error i have tried to see all the answers on stackoverflow and every other sites but it didn't help for me. i have already tried to delete migration folder and run makemigrations and migrate it is still giving me the error on makemigrations itself.try to run python manage.py migrate --run-syncdb it gives error on this command as well (youngmindsenv) E:\young_minds\heroku\youngminds>python manage.py makemigrations Traceback (most recent call last): File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends \utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "blog_no_of_views" does not exist LINE 1: ..."views_count", "blog_no_of_views"."username" FROM "blog_no_o... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\base.py", line 288, in run_from_argv settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'e-mc3z=m#6_w#lzy$eb%qik9fcdlqmzsfsdf9=5s(we74^)25q_ge5' DEBUG = True ALLOWED_HOSTS = ['youngminds.herokuapp.com',"localhost"] # Application definition INSTALLED_APPS = [ 'users.apps.UsersConfig', 'blog.apps.BlogConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'django.contrib.humanize', 'ckeditor', 'ckeditor_uploader', 'social_django', #'sslserver' ] CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS … -
Two URLs in django form tag using java script or ajax to process
would it be possible to include two data-url links in django form tag and proccess it either by java script or ajax to populate two different dependent drop down boxs? if it is possible what is the best way to implement it! thanks $("#province").change(function () { var url = $("#MyForm").attr("data-cities-url"); // get the url of the load_cities view var provinceId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/includes/load-cities/) data: { 'province': provinceId // add the country id to the GET parameters }, success: function(data) { // `data` is the return of the `load_cities` view function $("#city").html(data); // replace the contents of the city input with the data that came from the server } }); }); the result would be by loading the form user can choose a province and based on that the city fileds load the relevent cities and also user can choose a category and based on that subcategory field will populate relevent subcategories related to choosen category. -
Recommendations to build location based search in django
I am working on a project of house selling webapp in django. Now what I want is that user searches using address or city he wants house in and my search results should show houses nearby that location present in my database. What should I use to implement this ? I am using postgres database. -
Graphene/GraphQL find specific column value
For some reason, I can't figure out how to simply find a specific piece of data in my SQLAlchemy database. In the graphene-python documentation it simply does this query to match the id (which is a string): book(id: "Qm9vazow") { id title } Now here's my Flask-Graphene-SQLAlchemy code for my BookSchema and I want to find a specific title instead of an ID: class BookModel(db.Model): __table__ = db.Model.metadata.tables['books_book'] # Schema Object class BookSchema(SQLAlchemyObjectType): class Meta: model = BookModel interfaces = (relay.Node, ) # Connection class BookConnection(relay.Connection): class Meta: node = BookSchema # GraphQL query class Query(graphene.ObjectType): node = relay.Node.Field() allBooks = SQLAlchemyConnectionField(BookConnection) schema = graphene.Schema(query=Query, types=[BookSchema]) When I run this query, everything is fine and returns 3 book titles: { "query": "{ allBooks(first: 3) { edges { node { title } } } }" } However, once I try to match a specific title, it stops working. For example: # I tried all these queries, none worked 1. { allBooks(title: \"some book title\") { edges { node { title } } } } 2. { allBooks(title: \"some book title\") { title } 3. { allBooks(title: 'some book title') { edges { node { title } } } } The error: … -
What is the best strategy to call a home made python package from a Django application?
I’m working actually on a Django project based on some algorithms (that I developped in a separated python project as a package). I did use Python 3.7.3 and Django 2.2.2. I would like to have your opinion about the best way to add this resource to my Django project ? Simply add my package to my Django project and import it, or maybe use a wheel and install it like any other managed resource ? Maybe other practice could be a better one ? Sorry if my question is not relevant. It’s my first Django application and I would like to seize this opportunity for learning how to do things right way. Thx in advance -
NoReverseMatch error for update and delete view
I've a trouble with an update view and a delete view. Below the code: views.py from django.shortcuts import get_object_or_404, redirect, render from django.utils.text import slugify from .forms import BlogTagForm from .models import BlogTag def updateBlogTag(request, slug_tag=None): update_tag = get_object_or_404(BlogTag, slug_tag=slug_tag) form = BlogTagForm(request.POST or None, instance=update_tag) if form.is_valid(): update_tag = form.save(commit=False) update_tag.slug_tag = slugify(update_tag.tag_name) update_tag.save() return redirect('tag_list') context = { 'form': form, } template = 'blog/editing/create_tag.html' return render(request, template, context) def deleteBlogTag(request, slug_tag): if request.method == 'POST': tag = BlogTag.objects.get(slug_tag=slug_tag) tag.delete() return redirect('tag_list') models.py from django.db import models from django.urls import reverse class BlogTag(models.Model): tag_name = models.CharField( 'Tag', max_length=50, help_text="Every key concept must be not longer then 50 characters", unique=True, ) slug_tag = models.SlugField( 'Slug', unique=True, help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents", ) def __str__(self): return self.tag_name def get_absolute_url(self): return reverse("single_blogtag", kwargs={"slug_tag": self.slug_tag}) class Meta: ordering = ['tag_name'] forms.py from django import forms from .models import BlogTag class BlogTagForm(forms.ModelForm): tag_name = forms.CharField( max_length=50, help_text="<small>Write a tag here. The tag must be have max 50 characters.</small>", widget=forms.TextInput( attrs={ "placeholder": "Tag", "type": "text", "id": "id_tag", "class": "form-control form-control-lg", } ), ) class Meta: model = BlogTag fields = ["tag_name"] tag_list.html <table class="table … -
Django throws an error on any command: AttributeError: 'NoneType' object has no attribute 'startswith'
I deployed my Django app to PythonAnywhere. I need to run some commands in their Console. I created virtual environment using command: mkvirtualenv --python=/usr/bin/python3.6 venv Then I installed all my dependencies (including Django) pip install -r requirements.txt After, I want to migrate my database using command: python manage.py migrate I get this traceback: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect conn_params = self.get_connection_params() File "/home/mkwiatek770/.virtualenvs/venv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 201, in get_connection_params if settings_dict['HOST'].startswith('/'): AttributeError: 'NoneType' object has no attribute 'startswith' By the way it's happeninng on each django comand … -
Django Match-team-player relationship player select
i have player-team-match model 1 team have more than 5 players ( with substitute player (maybe 8 maybe 10+ player)) However, there must be 5 players in each team in one match. My question; How can I choose the player in the match (for that team) I want like this; A team= 8 players a,b,c,d,e,f,g,h their name and a,b,c,d,e play in this match. B team= 7 players k,l,m,n,o,p their name and k,l,m,n,o play in this match class Team(models.Model): name=models.CharField(max_length=255,verbose_name="Takım ismi") short_name=models.CharField(max_length=25,null=True,blank=True) slug=models.SlugField(max_length=120,unique=True) bio=models.TextField() class Player(models.Model): slug=models.SlugField(unique=True,max_length=120) team= models.ForeignKey(Team,related_name='player',verbose_name='Team',on_delete=models.PROTECT,null=True,blank=True)... class Match(models.Model): name=models.CharField(max_length=255) slug=models.SlugField(unique=True,max_length=255) map=models.ForeignKey('GameMap',null=True,blank=True,related_name='matchmap',on_delete=models.PROTECT) league=models.ForeignKey('League',blank=True,null=True,on_delete=models.PROTECT,related_name='matchleague') team1=models.ForeignKey('Team',related_name='team1') team2=models.ForeignKey('Team',related_name='team2')... -
Accessing and saving a field that is not included in fields attribute in extending generic class-based CreateView
I'm trying to display the user a form with comments not included. When the user submits the form, then, I want to manually add something to my comments, and then only, saving the object. With default implementation, it doesn't do anything with comments. ! app/views.py class ContactUsView(SuccessMessageMixin, CreateView): model = Contact fields = ['first_name', 'last_name', 'email_address'] success_message = "Thank you for your enquiry. We' ll be in touch shortly." ! app/models.py class Contact(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True) email_address = models.EmailField() comments = models.TextField() def get_absolute_url(self): return reverse('contact') def __str__(self): return self.first_name -
Django migration issue for boolean field
I have models and there was no Boolean field in the very beginning when i run makemigraiton and migrate In that mean time, i added some post... later i added new field called is_printable as boolean field... this is my current models: from django.db import models import datetime from django.utils import timezone Create your models here. class Article(models.Model): title = models.CharField(max_length=50) body = models.TextField() category = models.CharField( null=False, blank=False, max_length=50, ) is_printable = models.BooleanField() date = models.DateTimeField(timezone.now) when i add is_printable = models.BooleanField() I cant run migrate command, it throws me an error called django.core.exceptions.ValidationError: ["'2019-07-07 06:56:52.693378+00:00' value must be either True or False."] What is possible solution for this? -
Django deleting large Porstgres table content raises out of memory error
I have a Django model (Payment) with 1335888 instances, and I am calling a Payment.objects.all().delete(), but I get the following exception: Traceback (most recent call last): File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.OperationalError: out of memory DETAIL: Failed on request of size 262144. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/query.py", line 662, in delete collector.collect(del_query) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/deletion.py", line 220, in collect elif sub_objs: File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/query.py", line 272, in __bool__ self._fetch_all() File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1065, in execute_sql cursor.execute(sql, params) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/axel/SintaxProject/SintaxVenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.OperationalError: out of memory DETAIL: Failed on request of size 262144. I don't know why I am getting it, but I suppose it is … -
How to create realtime mp4 streaming service using Django?
I have created a Django application, which reads mp4/rtsp streams using OpenCV, then I process each frame using OpenCV and Tensorflow. Then I return processed frames using StreamingHttpResponse. How can I return processed frames as mp4 or m3u8 stream? Processed streams then will be read by Android and IOS applications, that's why I need mp4 or m3u8 stream -
django.db.utils.ProgrammingError: column "rtd" of relation "classroom_itembatch" already exists Keeps on coming evrytime
I'm working on a project with my team and whenever we update our app "django.db.utils.ProgrammingError: column "rtd" of relation "classroom_itembatch" already exists" errors keeps on coming and it with throw same error on every table in data base untill all the database are recreated and remigrated. I don't know why this error keeps on coming everytime and the only sollution I have to this is to drop my database using postgress which is the worst sollution I think. Please help me to resolve this error. -
How can i add default user to object when the user who created the object was deleted
I have Model "Tasks" contains "User" foreign key when user deleted , how can i add another user to that object as a backup user when creator is deleted ? first_user = User.objects.get(username='nagah') class Task(models.Model): taskname = models.CharField(max_length=30) created = models.DateTimeField(auto_now=True) is_complete = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, default=first_user.id) -
Passing custom html template doesn't work with reset password in django
I am implementing reset page for my django application. Everything works fine if i use auth_views.PasswordResetView.as_view() without passing in template_name. It uses default django provided templates and i get confirmation email and password is successfully reset but i want to pass in my own template to do so which has simple form with an image and one input tag for email. The view shows up fine but when i click submit it only shows 1 post request in console. I have tried implementing registration directory since in source code it uses that but no luck so far. I have also changed input to a button for submitting. I tried removing extra styling classes for css too. I am using following path for reset page. path('login/password-reset/', auth_views.PasswordResetView.as_view(), name = 'password_reset' ), Passing following generated the view but when i submit the email it doesnt get me to reset_done. path('login/password-reset/', auth_views.PasswordResetView.as_view(template_name = 'login/password_reset_form.html'), name = 'password_reset' ),