Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete session variable after use in Django templates
def demo(request): if data: request.session['success'] = "Success' else: request.session['failed'] = "Failed' Here I've defined one method and in that if I got data then success session is stored or else failed one. After that I'm redirecting user to the another page and there I'm displaying this session variable in template. But after the display of this session status I want to delete that session variable. Because I want to display this message only onetime to user. If user refreshes the page then this variable should be deleted. I tried to find online but didn't get any help. So please help me with this. Thank you P.S: I'm redirecting user to another page using return redirect('page'). Rendering another template using return render(request, "my_tmp.html") doesn't work because that will only load template in current url (URL will not change, only content will). So I don't want that. I know I can use this way by passing session variable in context but that's not I want. I'm using Django 2 -
django-allauth error, 'ModelBackend' object has no attribute
Django 2.2.1 Python 3.7.3 settings.py file added the following content: AUTHENTICATION_BACKENDS = ( ... # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ... ) I have set up django-allauth, not create the superuser, then executed python manage.py makemigrations && python manage.py migrate, Executed python manage.py createsuperuser --username admin --email admin@admin.com, , an error occurred: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/web/venv_a/lib/python3.7/site-packages/django/core/management/init.py", > line 381, in execute_from_command_line utility.execute() File "/home/web/venv_a/lib/python3.7/site-packages/django/core/management/init.py", > line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/web/venv_a/lib/python3.7/site-packages/django/core/management/base.py", > line 323, in run_from_argv self.execute(*args, * *cmd_options) File "/home/web/venv_a/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 61, in execute return super().execute(*args, * *options) File "/home/web/venv_a/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, * options) File "/home/web/venv_a/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 132, in handle validate_password(password2, self.UserModel( *fake_user_data)) File "/home/web/venv_a/lib/python3.7/site-packages/django/contrib/auth/password_validation.py", line 47, in validate_password validator.validate(password, user) AttributeError: 'ModelBackend' object has no attribute 'validate' After I created the superuser, then set django-allauth, open url: http://127.0.0.1:8000/admin/auth/user/add/, the following error occurred: AttributeError at /admin/auth/user/add/ 'ModelBackend' object has no attribute 'get_help_text' How to solve it? Thank you. -
error in Django RestFrameWork "NOT NULL constraint failed: qoura_question.author_id "
trying to add a post to DRF which takes the information of USER and TIME automatically, But this is the error which pops up when tried to add a Post. models.py: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): title = models.CharField(max_length = 200) description = models.CharField(max_length = 2000) date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User , on_delete = models.CASCADE) def __str__(self): return self.title Views.py: class PostViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer authentication_classes = [TokenAuthentication,SessionAuthentication] def create(self, request): obj = Post() obj.title = request.data['title'] obj.description = request.data['description'] obj.date_posted = request.data['date_posted'] obj.user = request.user obj.save() return Response(status=status.HTTP_201_CREATED) serializer.py: from rest_framework import serializers from django.contrib.auth.models import User from . models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'title','description','date_posted','author') -
Django -- Pass a dictionary to template and plot a line chart
I have a dictionary generated in views.py, it looks like this, but has n number of enterprises { enterprise1: {'Year': ['2014/2015', '2016/2017', '2013/2014'], 'no_per_year': [16, 8, 6]}, enterprise2: {'Year': ['2016/2017', '2013/2014', '2014/2015'], 'no_per_year': [2, 16, 11]}, enterprise3: {'Year': ['2016/2017', '2013/2014', '2015/2016'], 'no_per_year': [19, 7, 14]}, .... .... .... } How to pass this dictionary to a template, and plot a line graph which depicts each enterprise and the number of students they recruited in each year. Json, javascripts are something very new for me, would appreciate any help. Below is the code, i tried with static data by implicitly writing the data without any loops. How do i transform it to take this data of n enterprises and plot? {% extends "base.html" %} {% load static %} <script> {% block jquery %} $.ajax({ success: function(data) { setchart() setchart2() }, error: function(error_data){ console.log("error") console.log(error_data) } }) prgcolorset = [ 'rgba(73,170,30,0.4)', 'rgba(50, 106, 21,0.4)', 'rgba(219, 58, 29,0.4)', 'rgba(150, 58, 29, 0.4)', 'rgba(60, 206, 209, 0.4)', 'rgba(60, 157, 209, 0.4)', 'rgba(60, 90, 209, 0.4)', 'rgba(280, 243, 36, 0.4)', 'rgba(230, 243, 36, 0.4)', ] prgcolorborderset =[ 'rgba(73,170,30,1)', 'rgba(50, 106, 21,1)', 'rgba(219, 58, 29, 1)', 'rgba(150, 58, 29, 1)', 'rgba(60, 206, 209, 1)', 'rgba(60, 157, … -
Django can not makemigrations: can't create form field for followers yet. Because its related model 'self' has not been loaded yet
This is the model. class CustomUser(AbstractUser): followers = ArrayField(ArrayField(models.ForeignKey('self', related_name = 'following_set', on_delete = models.CASCADE ), size = 1)) followings = ArrayField(ArrayField(models.ForeignKey('self', related_name = 'follower_set', on_delete = models.CASCADE ), size = 1)) -
How do you deploy a bootstrapped Django application?
I am deploying a bootstrapped Django app to Heroku. I am not sure if I am using that word (bootstrapped) correctly in this context. This application creates a settings.py file when the following command is invoked: invoke bootstrap-wger \ --settings-path ./wger/settings.py \ --no-start-server I would like to include the command in the Heroku build process but have no idea how to. I would use a locally generated settings.py file but it has variable's that differ from each installation of the application. The file is, therefore, not pushed to remote. I have tried to deploy via TravisCI on the condition that my build is passing, that too didn't work. I have also tried to use heroku.yml file but I don't see how I can add commands and have them to run before the build starts. I have looked at the possibility of having the commands included in the Procfile but it only supports this at the release phase which happens after a successful build. -
How to filter and get ONLY selected objects from ManyToMany field?
There are three pages: Brands of car, CARServices and AutoSettings. One car service provides services to certain bra of cars. I have to go to the page with the brands of cars from there, select the brand and again get to the page with a list of car-services that should show information about the service for the type of machine I have chosen. How I can get by filter, selected objects from 'Settings' from ManyToMany Field This is my Views.py from django.shortcuts import render from .models import * def carbrand_page(request): tags = Carbrand.objects.all() return render(request, 'blog/carbrand_page.html', context={'tags': tags}) def service_list(request, slug): tags = Carbrand.objects.all() tags = Service.objects.all() posts = Service.objects.get(slug__exact=slug) <<<here the problem return render(request, 'blog/service_list.html', context={'tags': tags, 'posts': posts}) When I run I get error 'Service matching query does not exist.' This is my Models.py from django.db import models from django.shortcuts import reverse class Carbrand(models.Model): name = models.CharField(max_length=280) image = models.FileField() slug = models.SlugField(max_length=280, unique=True) def get_absolute_url(self): return reverse('service_list_url', kwargs={'slug': self.slug}) def __str__(self): return "{}" .format(self.name) class Settings(models.Model): settings = models.CharField(max_length=500) image = models.FileField() slug = models.SlugField(max_length=300, unique=True,) def __str__(self): return "{}" .format(self.settings) class Service(models.Model): carbrand = models.ManyToManyField('Carbrand', blank=True, related_name='tags') settings = models.ManyToManyField(Settings) name = models.CharField(max_length=380, db_index=True) slug = … -
Django: the first Database Models with ForeignKey
I follow the tutorial from Django Website Writing your first Django app. When I run the command \>py manage.py makemigrations polls in order to make the models from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I get the following message Migrations for 'polls': polls/migrations/0001_initial.py: - Create model Choice - Create model Question I do not get the following - Add field question to choice I have tried the same in SQLite and PostgresQL. I use Python3.7 and Django2.2.1. I do not know what the bug is here. -
Custom save method in django model
I have written a custom save method for a model in order to prevent save of invalid data, but when I want to update the object via admin (just to change some properties), I got an assert error my model: class Segment(CoreModel): departure = models.ForeignKey(Place, on_delete=models.CASCADE, limit_choices_to=limit_choices_segment, related_name='departures') destination = models.ForeignKey(Place, on_delete=models.CASCADE, limit_choices_to=limit_choices_segment, related_name='arrivals') distance = models.FloatField(help_text='Distance between places in "km"!', null=True, blank=True, validators=[property_positive_value]) duration = models.FloatField(help_text='Transfer duration (hours)', null=True, blank=True, validators=[property_positive_value]) cost = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, help_text='Price for a transfer! Currency: "UAH"!', validators=[property_positive_value]) route = models.ForeignKey(Route, on_delete=models.CASCADE, related_name='segments') def __str__(self): return '{}-{}'.format(self.departure, self.destination) def save(self, *args, **kwargs): assert self.departure.role not in (Place.DISTRICT, Place.REGION), ( "Departure couldn't be Region or District") assert self.destination.role not in (Place.DISTRICT, Place.REGION), ( "Destination couldn't be Region orDistrict") assert self.destination != self.departure, "Departure couldn't be equal to Destination" assert self.route.segment_validate(departure=self.departure, destination=self.destination), ( 'Impossible to add the segment, please check the route!') if self.distance is not None: assert self.distance > 0, "Distance couldn't be less or equal to '0'!" if self.duration is not None: assert self.duration > 0, "Duration couldn't be less or equal to '0'!" if self.cost is not None: assert self.cost > 0, "Cost couldn't be less or equal to '0'!" super(Segment, self).save(*args, … -
Filter Django objects by .extra() select for lat and lng radius
I has a Django models for location based services and try to filter location by radius. I try use .extra() query but not working. The value of distance can only use for sort, not filter. # models.py class Location(models.Model): latitude = models.FloatField() longitude = models.FloatField() place_name = models.CharField(max_length=65) class Meta: db_table = "shop_location" def __str__(self): return self.place_name # views.py shop_locations = Location.objects.extra( select={ 'distance': '6371 * acos( cos( radians(9) )' '* cos( radians( COALESCE(latitude, 0) ) )' '* cos( radians( COALESCE(longitude, 0) )' '- radians(11) ) + sin( radians(9) )' '* sin( radians( COALESCE(latitude, 0) ) ) )' }, ).extra(order_by=['distance']).filter(distance<10) # on radius 10KM But return error name 'distance' is not defined. How to fix it. I don't want use GeoDjango. -
Django: Checking content type of response in tests
I have Django view that returns a HTTPResponse with content type 'application/json'. In my tests, I want to verify the expected content type was set. From the docs, I see that a HTTPResponse I can pass the content_type has a parameter, put not get it as an attribute. Why is that? In my views.py, I build and send out a HTTPResponse like this: j = json.dumps(j) return HttpResponse(j, content_type='application/json') In my tests.py, I would like to do something like self.assertEqual(response.content_type, 'application/json') But without the attribute on the HTTPResponse object, that of course fails with AttributeError: 'HttpResponse' object has no attribute 'content_type' How can I get the content type of the response in Django? Am misunderstanding something about the workings of HTTP? -
What is a scalable way of creating cron jobs on Amazon Web Services?
This is my first question so I appologize if it's not the best quality. I have a use case: User creates a monitoring task which sends an http request to a website every X hours. User can have thousands of these tasks and can add/modify and delete them. When a user creates a task, django signals create a Celery periodic task which then is running periodically. I'm searching for a more scalable solution using AWS. I've read about using Lambda + Cloudwatch Events. My question is: how do I approach this to let my users create tens of thousands of these tasks in the cheapest / most scalable way? Thank you for reading my question! Peter -
how to handle two url in django forms?
here i have only one table and in which i want to select some multiple id and i want to perform actions either delete or send mail.For this i have tried this , deleting selected id is working fine but i got stuck on sending emails to the selected ids.How can i perform these two actions form the one single table? views.py def send_mail_selected_contact(request): selected_contact = ContactForm.objects.filter(id__in=request.POST.getlist('messages')) form = SendMailContact(request.POST or None) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] for contact in selected_contact: send_mail(subject,message, '<settings.EMAIL_HOST_USER>', [contact.email]) messages.success(request, 'Success') return redirect('admin:contact_message') def delete_selected_message(request): selected_messages = ContactForm.objects.filter(id__in=request.POST.getlist('messages')) selected_messages.delete() messages.success(request,'Deleted') return redirect('admin:contact_message') template <form role="form" action="{% url 'admin:delete_selected_message' %}" method="post"> {% csrf_token %} <table> <tbody> {% for contact in contacts %} <tr> <td><ol type="1"> <input name ="messages" type="checkbox" id="contact-{{contact.id}}" value="{{contact.id}}" > <label for="contact-{{contact.id}}">{{ forloop.counter }}</label></ol> </td> <td>{{ contact.name }}</td> <td>{{ contact.email }}</td> <td>{{ contact.subject }}</td> <td>{{ contact.message }}</td> </tr> {% endfor %} </table> {% if contacts %} <button type="submit" class="btn btn-danger mb-5"> Delete Selected Contacts </button> <a href="{% url 'admin:send_mail_form' %}"> <button type="button" class="btn btn-info mb-5"> Send Mail To Selected Contact </button> </form> send_mail_form <form action="{% url 'admin:send_mail_selected_contact' %}" method="post"> {% csrf_token %} <h5>Subject </h5> <input type="text" name="subject" > <h5>Message </h5> <input … -
How to customize complex Url patterns in Django Oscar
I have set up a Django-oscar project and I'm trying to configure the URLs. My goal is to change /checkout/shipping-address/ to /checkout/billing-address/ As per the documentation, I've added app.py in myproject/app.py myproject/app.py from django.conf.urls import url, include from oscar import app class MyShop(app.Shop): def get_urls(self): urls = super(MyShop, self).get_urls() for index, u in enumerate(urls): if u.regex.pattern == r'^catalogue/': urls[index] = url(r'^product/', include(self.catalogue_app.urls)) elif u.regex.pattern == r'^basket/': urls[index] = url(r'^cart/', include(self.basket_app.urls)) elif u.regex.pattern == r'^checkout/shipping-address/': urls[index] = url(r'^checkout/billing-address/', include(self.checkout_app.urls)) break return urls application = MyShop() myproject/urls.py from django.conf.urls import url, include from django.contrib import admin from . import views from .app import application urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^admin/', admin.site.urls), url(r'', application.urls), url(r'^index/$',views.index, name = 'index'), ] How can I change Checkout/shipping-address/ to checkout/billing-address/? -
'SessionStore' object has no attribute 'GET'
What is wrong in this code, it generates the following error: > if not request.session.GET.get('session_key', False) > ^ > SyntaxError: invalid this is the code: def blog_detail(request, blog_slug): blog = get_object_or_404(Blog, slug=blog_slug) session_key = 'blog_views_{}'.format(blog.slug) if not request.session.GET.get('session_key', False) blog.blog_views += 1 blog.save() request.session['session_key'] = True return render(request, 'blogs/blog-detail.html', {'blog':blog}) I think I am doing it wrong using request.session. Can you help me with that, Thank you. edit: traceback Environment: Request Method: GET Request URL: http://localhost:8000/dramatically-productivate-global-functionalities-whereas-reliable-internal-or-organic-sources Django Version: 2.2.1 Python Version: 3.7.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blogs', 'users', 'crispy_forms'] Installed 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "E:\Practice\new-blog\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "E:\Practice\new-blog\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "E:\Practice\new-blog\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Practice\new-blog\src\blogs\views.py" in blog_detail 53. if not request.session.GET.get('session_key', False): Exception Type: AttributeError at /dramatically-productivate-global-functionalities-whereas-reliable-internal-or-organic-sources Exception Value: 'SessionStore' object has no attribute 'GET' -
Django: how to use {{ something }} inside css file
I have a model called Post with a FileField which is an image. I want to do something like this: .article-image{ background-image: url("../img/{{ post.postimage }}); } but obviously it does not work, so I tried to make inline css instead: <div class="article-image" style="background-image:{% static 'img/{{ post.postimage }}' %}"></div> but it does not work too. How can I fix this -
Getting "curl: (92) HTTP/2 stream 1 was not closed cleanly: INTERNAL_ERROR (err 2)" while requesting large data
I have a Django app which returns a large JSON while calling an API. The problem is when I'm requesting the data, the data itself is truncated which is crashing the frontend. I'm using cloud front for DNS and SSL and other feature provided by them for caching and improved performance. I tried curling the API and got the following error: curl: (92) HTTP/2 stream 1 was not closed cleanly: INTERNAL_ERROR (err 2) I tried disabling the Cloudflare but didn't work. On my localhost, however, everything works fine. HTTP/2 stream 1 was not closed cleanly: INTERNAL_ERROR (err 2) * Closing connection 0 * TLSv1.2 (OUT), TLS alert, Client hello (1): curl: (92) HTTP/2 stream 1 was not closed cleanly: INTERNAL_ERROR (err 2) The JSON should be fetched entirely without getting chunked. -
How can I get Django application name inside a decorator?
I defined a decorator in Django as below: from functools import wraps def register_permission(my_input): def decorator(func): @wraps(func) def wrapper(): # ---------> I want app name here func() return wrapper return decorator then, I use it in some apps like : @register_permission("some text") class MyClass(): pass Now,I want the app name of MyClass , also I found How to get an app name using python in django question, but it can not help me. What is the best way to do this? -
Why doesn't my docker-compose volume get updated with local file additions?
Here's my docker-compose.yml, it contains a web service, which mounts a folder locally so that upon any code change watchmedo restarts the webapp django server. It's a reverse proxy with nginx. version: '3' services: webapp: build: context: . dockerfile: ./web/Dockerfile volumes: - ./web/:/usr/src/app/ - staticfile_volume:/usr/src/app/public entrypoint: > watchmedo auto-restart --recursive --pattern="*.py" --directory="." gunicorn myapp.wsgi:application -- --bind 0.0.0.0:9000 nginx: build: context: . dockerfile: ./nginx/Dockerfile depends_on: - webapp volumes: - staticfile_volume:/usr/src/app/public volumes: staticfile_volume: My local file setup is like: $ tree -L 2 . ├── docker-compose.yml ├── nginx │ ├── Dockerfile │ └── nginx.conf └── web ├── Dockerfile ├── manage.py ├── myapp ├── public └── static But when I create a new file in web/public (the same folder mounted as a shared volume between webapp and nginx services), I don't see it from inside the running webapp container. Yet, if I create a new file anywhere else in the web/ folder (which is also mounted as a separate volume), I see the change from inside the running webapp container. What is causing this? And how do I change this behavior? (I need to be able to run python manage.py collectstatic from inside the running container but output into my local hard drive's … -
django admin: how to disable edit and delete link for foreignkey
In django admin site, if the model has a foreignkey, by default it will be a select input and there are three links(edit, add, delete) like below. How to disable these links? -
Generate multiple tables from each child model
I'm trying to create a generalized "archive" for several tables. I'd like to create a parent class that creates a table as well as an archive that has a similar schema with a few added columns. I'd like to have function which periodically moves any items from the live table to the archive table, that is the same across all models. I've read some polymorphism tutorials, but they pretty much all focus on sharing a few columns. Here's something like what I'm looking for: from django.db import models class HasArchive(models.Model?): archive_time = models.DateTimeField(max_length=128, default='', unique=True) class User(models.Model, HasArchive): name = models.CharField(max_length=128, default='', unique=True) class Order(models.Model, HasArchive): product = models.CharField(max_length=128, default='', unique=True) So I'd likd 4 tables to be created from this: user, user_archive, order, order_archive... where the archive tables are based off the schemas of the original -
obj.authors.all() doest show anything
I'm trying to make a django site in the latest version of django, but when i use the obj.authors.all() it returns nothing. I have tried getting rid of the all() but returns empty Queryset views.py def menu(request): obj = Book.objects.get(id=1) obj = obj.authors.all() else: obj="" return render(request, 'menu.html', {'obj':obj,'numautgors':authors}) models.py class Book(models.Model): name = models.CharField(max_length=100,unique=True) authors = models.ManyToManyField(User) text = models.TextField(unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('model-detail-view', args=[str(self.id)]) I expect it to return the authors ,but it returns nothing. Sorry if a duplicate.And one more question can i show all book written by a specific author or in this case User -
Virtualenv myenv doesn't create virtual environment on exFAT hard drive on Ubuntu 18.04
I am learning Django with python 3.6. I use Ubuntu 18.04.2 LTS which is also new for me. My pip version is 9.0.1. My problem is when I try to create virtual environment on my external exFAT had drive with virtualenv myenv command it gives the error that I shared bellow. But I can create virtual environment on the Desktop with the same command. The problem is very weird for me. I can't solve the problem. Can you guys please help me? Thanks in advance! SAMPLE CODE: ERROR c@p:/media/c/2NDTB/testpro$ virtualenv myenv Using base prefix '/usr' Traceback (most recent call last): File "/home/c/.local/lib/python3.6/site-packages/virtualenv.py", line 417, in copyfile os.symlink(os.path.realpath(src), dest) OSError: [Errno 38] Function not implemented: '/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu' -> '/media/c/2NDTB/testpro/myenv/lib/python3.6/config-3.6m-x86_64-linux-gnu' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/c/.local/bin/virtualenv", line 11, in sys.exit(main()) File "/home/c/.local/lib/python3.6/site-packages/virtualenv.py", line 831, in main symlink=options.symlink, File "/home/c/.local/lib/python3.6/site-packages/virtualenv.py", line 1106, in create_environment install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages=site_packages, clear=clear, symlink=symlink) File "/home/c/.local/lib/python3.6/site-packages/virtualenv.py", line 1390, in install_python copy_required_files(stdlib_dir, lib_dir, symlink) File "/home/c/.local/lib/python3.6/site-packages/virtualenv.py", line 1300, in copy_required_files copyfile(join(src_dir, fn), join(lib_dir, fn), symlink) File "/home/c/.local/lib/python3.6/site-packages/virtualenv.py", line 420, in copyfile copy_file_or_folder(src, dest, symlink) File "/home/c/.local/lib/python3.6/site-packages/virtualenv.py", line 398, in copy_file_or_folder shutil.copytree(src, dest, symlink) File "/usr/lib/python3.6/shutil.py", line 359, in … -
Why Django QuerySet didn't support join with manyTomany?
How can I generate SQL like snippet 1-2? Why Django support only prefetch_related('product_set') without support join with manytomanyField? of course i can make similar queryset like Order.objects.filter(product_set_included_order__name='product_name1') it generate SQL with join two entity but it has big problem which didn't hit index(pk) # 1-1 this is snippet code # in Django model of relationship with ManyToMany class Product(models.Model): name: str = models.CharField(null=False, max_length=128) price: int = models.PositiveIntegerField(null=False, default=0) class Order(models.Model): product_set= models.ManyToManyField(to=Product) # 1-2 i want generate this SQL but it's impossible!! SELECT * FROM "order" INNER JOIN "orderedproduct" ON ("order"."id" = "orderedproduct"."related_order_id") INNER JOIN "product" ON ("orderedproduct"."related_product_id" = "product"."id") WHERE "order"."id" = 1; -
unsupported operand type(s) for +=: 'DeferredAttribute' and 'int'
I want to track number of views for a post and while doing that I got above stated error. codes here: def home(request): queryset = Blog.objects.filter(featured=True).order_by('-created_at') latest = Blog.objects.filter(featured=True).order_by('-created_at')[0:6] page = request.GET.get('page', 1) paginator = Paginator(queryset, 4) blogs = paginator.page(page) blog_view_num = Blog.blog_views Blog.blog_views += 1 # <- maybe the error comes from here Blog.save() context = { 'blogs': blogs, 'latest': latest, 'title':'home', 'views': blog_view_num } return render(request, 'blogs/home.html', context) I added blog_views field in models.py as well blog_views = models.PositiveIntegerField(default=1). I am getting above stated error. Even though I tried Blog.blog_views += int(1) but that still didn't work. How do I solve this to keep track of number of views for a post? Thank you