Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload a file in Django Admin, but not as a model's FileField
I'm working with Django 3 and I need to upload a (zip) file via the Django Admin. All the information that I've found online refers to uploading files as a models' FielField. But in my case, I don't want to associate the uploaded file to any model. I just want to upload it and run a certain management command based on its content, and delete it afterwards. If needed, I can use JQuery in the Django Admin pages to help accomplish this goal. Any pointers on how to do this? -
how to remove a null value from session cart dictionary in django
here is my views.py logic to add product in session cart def index(request): categoryID= request.GET.get('category') product= request.POST.get('product') cart=request.session.get('cart') if cart: quantity=cart.get(product) if quantity: cart[product]=quantity+1 else: cart[product]=1 cart['product']=1 else: cart['product']= 1 request.session['cart']=cart print(cart) print(product) category=Category.get_all_categories() if categoryID: products = Product.get_all_products_by_id(categoryID) else: products=Product.get_all_products() prddata={ 'product' : products, 'cat': category, } return render(request,'index.html',prddata) I have added two product in cart but when I print cart in terminal {'product': 1, '1': 1, '2': 4, 'null': 1} 2 [06/Nov/2021 01:10:25] "POST / HTTP/1.1" 200 13104 this null is being added I don't know how. How to prevent this or remove it from cart? please help. -
Query data using filter Django/python
I'm pretty new to the Django backend framework. I have been able to easily query data, but now I'm trying to filter that data. When I run the application it will load the landing page and other pages, but when I try to naviagate to the FRReports page I get "Error during template rendering In template C:\Users\n9177d\webdart\DjangoWebProject1\DjangoWebProject1\webdart\templates\webdart\base.html, error at line 16 'webdart' is not a registered namespace" Any ideas or guidance? urls.py from django.urls import path, include from . import views from webdart.views import AboutView from django.contrib import admin admin.autodiscover() # Use '' to default to the home page urlpatterns = [ path('', views.landing, name='webdart-landing'), path('admin/', admin.site.urls), path('home/', views.home, name='webdart-home'), path('data/', views.data, name='webdart-data'), path('data/stationData/', views.data_stationData, name='webdart-data_stationData'), path('data/obscura/', views.data_obscura, name='webdart-data_obscura'), path('data/tiz/', views.data_tiz, name='webdart-data_tiz'), path('data/mcv/', views.data_mcv, name='webdart-data_mcv'), path('data/viewer/', views.data_viewer, name='webdart-data_viewer'), path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'), path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'), path('FRReports/', views.DocRepositoryListView.as_view(), name='list'), path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports'), #path('FRReports/', views.documents_FRReports, name='webdart-documents_FRReports'), path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'), . . . views.py from django.core.paginator import Paginator from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView, ListView, DetailView from webdart.models import Person, DocRepository from webdart.filters import DocRepositoryFilter class DocRepositoryListView(ListView): model = DocRepository template_name = 'webdart/FRReports.html' def get_context_data (self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = DocRepositoryFilter(self.request.GET, queryset=self.get_queryset()) return context class documents_FRReports(DetailView): … -
Django + gUnicorn timing out with POST requests with large sizes
Sending a 'large' POST request to gUnicorn will cause it to freeze and eventually timeout. This is both on my production server and development server (both running Ubuntu 20.04). It just freezes before returning [CRITICAL] WORKER TIMEOUT (pid:10000) Django's default dev server works without issues. My WSGI file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings') application = get_wsgi_application() -
How can I make a twitter like homepage with django?
I am right now new to the Django web framework. I want to make a twitter-like/facebook-like homepage where a user can post a status or update and also view other ures' posts but I can't do that because when a user is logged in, he posts an update but can't view it is his home. He can view all the posts when he logs out. Here is my views function for this. views.py def index(request): posts = NewPost.objects.all().order_by("-timestamp") if request.user.is_authenticated: if request.method == "POST": post = NewPostForm(request.POST) user = request.user timestamp = datetime.now() if post.is_valid: post = post.save(commit=False) postdata = NewPost(post=post,user=user,timestamp=timestamp) postdata.save() return render(request,"network/index.html",{ "post" : post, "user" : user, "timestamp" : timestamp }) else: post = NewPostForm() return render(request,"network/index.html",{ "post" : post }) return render(request,"network/index.html",{ "posts" : posts }) urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), ] templates {% extends "network/layout.html" %} {% block body %} <div style="margin: 10px 10px 10px 10px;"> <h1>All Posts</h1> {% if user.is_authenticated %} <div class="border border-success" style="margin: 10px 10px 10px 10px;"> <div style="margin: 10px 10px 10px 10px;"> <h3>New Post</h3> <form action="{% url 'index' %}" method="POST"> {% csrf_token %} <div class="form-group"> <!-- <textarea name="post" class="form-control" cols="30" … -
My form doesn't appear with another some problems with the bid system Django issues
I want to apply this requirement: the user should be able to bid on the item. that bid must be largest than the bid and if not show error message my problem is when I runserver the bid form disappearing and I cannot see anything except this pargraph <p class="text-muted">Start the first Bid!</p> I try to do that thing that what I have urls.py urlpatterns = [ path('Post/<int:id>', views.viewList, name='viewList'), # bids path("Post/<int:id>/bid", views.take_bid, name="take_bid"), # Close Bid path('Post/<int:id>/close', views.closeListing, name="closeListing"), ] views.py def viewList(request, id): # check for the watchlist listing = Post.objects.get(id=id) if listing.watchers.filter(id=request.user.id).exists(): is_watched = True else: is_watched = False context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'Bidform': BidForm(), 'is_watched': is_watched } return render(request, 'auctions/item.html', context) @login_required def take_bid(request, id): listing = Post.objects.get(id=id) bid = float(request.POST['bid']) if is_valid(bid, listing): listing.currentBid = bid form = BidForm(request.POST, request.FILES) newBid = form.save(commit=False) newBid.auction = listing newBid.user = request.user newBid.save() listing.save() return HttpResponseRedirect(reverse("viewList", args=[id])) else: return render(request, "auctions/item.html", { "listing": listing, "Bidform": BidForm(), "error_min_value": True }) def is_valid(bid, listing): if bid >= listing.price and (listing.currentBid is None or bid > listing.currentBid): return True else: return False models.py class Post(models.Model): # data fields title = models.CharField(max_length=64) textarea = models.TextField() # … -
Custom template tags in Django
I want to use Django Template Tags to return some html values but it happens that the value is returned once and then reused by the browser when refreshed even if I do a hard refresh. It only changes when I reload my development server. Is there anything that can be done to return the dynamic html files from the template tags each time the browser is refreshed -
How to serialize first photo in album? Django
How to serialize first photo in album if photo connected by using FK with model Gallery. I need first photo for gallery cover in galley list. My models: class Gallery(models.Model): title = models.CharField() class GalleryImage(models.Model): gallery_id = models.ForeignKey(Gallery, related_name='photos') photo = models.ImageField() Anyone have any ideas? May be I need suchlike request Gallery.objects.get(id=id).photos.first() but i not sure is it correct. -
Python Django ImportError: cannot import name 'Required' from 'typing_extensions'
Django version is 3.2.9. Python version is 3.10.0. And typing_extensions 3.10.0.2 I'm new to coding, python, etc., and can't figure out what is the problem. Following django tutorial I created an app and ran the server successfully, but a day later, when I tried to do that again I faced this problem: File "C:\Users\fused\Desktop\code\py\myproject\myapp\views.py", line 1, in <module> from typing_extensions import Required ImportError: cannot import name 'Required' from 'typing_extensions' (C:\Users\fused\AppData\Local\Programs\Python\Python310\lib\site-packages\typing_extensions.py) After trying to run a server with 'python manage.py runserver' this problem appeared, tried reinstalling typing_extensions, checked versions of everything, but nothing solved the problem. If any additional information is needed, I'll reply with it. Thanks in advance -
Getting CSRF token missing error on a django rest framework (with TokenAuthentication) public APIView
I'm having issue with Django Rest Framework and CSRF configurations. I know there are plenty of similar posts on the subject (like this one Django Rest Framework remove csrf) but most of them do not apply (I'm not using SessionAuthentication, nor Django templates), and the way DRF handles CSRF is still unclear to me. Here is the situation : I have a DRF application acting as a backend API with several routes, with Token Authentication (JWT) I also have a separate frontend communicating with my API. Both are on the same domain (say https://example.com and https://example.com/backend) I have a simple APIView on DRF side for registration on which I need to send POST requests. This view doesn't require authentication. When I send the POST request, I get a 403 Forbidden error with the following message : detail "CSRF Failed: CSRF token missing or incorrect." Here is my view: class RecaptchaVerifyView(APIView): permission_classes = [] serializer_class = ReCaptchaSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): return Response({'success': True}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I've read that DRF disables CSRF except for SessionAuthentication which I do not use. I also read that empty permission_classes should solve most of the problems. So … -
Updating model field by adding old value to new Django
I'm trying to keep track of the total hours being put into a work order. I'd like to add the new number being entered to the number existing in the DB and return the total. Thank you in advance for any help. The Model: class WorkOrder(models.Model): client = models.ForeignKey(Contact, on_delete=models.CASCADE) hours_worked = models.IntegerField() The View: class UpdateWorkOrder(LoginRequiredMixin, generic.UpdateView): model = WorkOrder template_name = 'client/update_workorder.html' success_url = reverse_lazy('dashboard') -
Django-neomodels driver error while running python manage.py install_labels
I am running the paradise papers neo4j project tutorial, I have created all my models but I get the error below while generating database indexes.That is when I run command: python manage.py install_labels My requirements.txt: asgiref==3.4.1 certifi==2021.10.8 Django==3.2.8 django-neomodel==0.0.7 djangorestframework==3.11.2 gunicorn==20.0.4 neo4j-driver==4.3.1 neomodel==4.0.4 pytz==2021.1 Shapely==1.7.1 six==1.16.0 sqlparse==0.4.2 white-noise==3.3.1 and added the following in the settings.py: NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL','bolt://neo4j:1234@127.0.0.1:7687'). Error: File "/Users/harmankibue/Desktop/Data/Projects/Django-Projects/papers_search/manage.py", line 21, in <module> main() File "/Users/harmankibue/Desktop/Data/Projects/Django-Projects/papers_search/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django_neomodel/management/commands/install_labels.py", line 12, in handle install_all_labels(stdout=self.stdout) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neomodel/core.py", line 153, in install_all_labels install_labels(cls, quiet=False, stdout=stdout) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neomodel/core.py", line 110, in install_labels db.cypher_query("CREATE INDEX on :{0}({1}); ".format( File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neomodel/util.py", line 35, in wrapper return func(self, *args, **kwargs) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neomodel/util.py", line 230, in cypher_query response = session.run(query, params) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/work/simple.py", line 221, in run self._connect(self._config.default_access_mode, database=self._config.database) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/work/simple.py", line 118, in _connect self._connection = self._pool.acquire( File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/io/__init__.py", line 805, in acquire return self._acquire(self.address, timeout) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/io/__init__.py", line 660, in _acquire connection = self.opener(address, timeout) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/io/__init__.py", line 787, in opener return Bolt.open( File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/io/__init__.py", line 337, … -
'AnonymousUser' object has no attribute '_meta' | Django Authentication
Same authentication system on three different places in project i.e Authenticating user at login, registration, and password reset. At password reset it works fine all the time. At registrations sometime works and sometime doesn't and at login works on rare occasions. Also the error is same all the time. ERROR AttributeError at /userauth/user-activate/NA/avnpw3-de3afda5cfeae9690598ace91235106a/smqia40453665072/pW1QdEFRkm42txOZ 'AnonymousUser' object has no attribute '_meta' Request Method: POST Request URL: http://127.0.0.1:8000/userauth/user-activate/NA/avnpw3-de3afda5cfeae9690598ace91235106a/smqia40453665072/pW1QdEFRkm42txOZ Django Version: 3.2.7 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute '_meta' Exception Location: C:\Users\smqia\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py, line 247, in inner Python Executable: C:\Users\smqia\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.7 Python Path: ['C:\\xampp\\htdocs\\Projects\\Barter', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Fri, 05 Nov 2021 16:35:02 +0000 CODE settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) views.py username = smqia404 password = *************** user = authenticate(request, username=username, password=password, backend='django.contrib.auth.backends.ModelBackend') login(request, user, backend='django.contrib.auth.backends.ModelBackend') -
GeoDjango with Docker error: 'DatabaseOperations' object has no attribute 'geo_db_type'
This appears to be a common error, and I have checked all the solutions I could find (there are only about 4 and almost all of them involve misconfigurations). I am NOT using heroku, but I AM using docker. I am using the docker images python:3.9.7 and postgis/postgis:10-3.1-alpine. My Dockerfile contains the following line: ARG BUILD_ENV=production # ... FROM python:3.9.7 as apiserver #... RUN apt-get update && \ apt-get install --no-install-recommends -y apt-utils build-essential sudo git wget curl ca-certificates nginx openssl libpq-dev expect libmagic-dev graphviz python3-gdal python3-pandas postgis binutils libproj-dev gdal-bin python3-djangorestframework-gis # ... RUN pip install --upgrade pip && pip install -r requirements/${BUILD_ENV}.txt # ... This should make sure all the dependencies I need to build the postgis libs for django are present, so when I run pip install, it will have everything it needs. It is more verbose than it needs to be because the GeoDjango docs say to install postgis binutils libproj-dev gdal-bin, and the drf-gis one has all the GeoDjango libs as dependencies. I plan on using the drf-gis package, but am not currently using it. requirements/production.txt django-cors-headers==3.5.0 django-extensions==3.0.9 django-filter==2.4.0 # ... Django==3.1.13 # ... djangorestframework==3.12.4 djangorestframework-gis==0.17 # ... I have enabled the correct app in … -
Saving a comment under an article returns 404 page not found
I have been trying to add comments to a blog page that I am creating. I have a comment model which has a post id as foreign key, and user as well, because I want to allow only users to comment. class Comment(models.Model): post = models.ForeignKey( Article, on_delete=models.CASCADE, related_name='comments') name = models.ForeignKey( User, blank=True, null=True, on_delete=models.SET_NULL) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] However on save, it returns a 404 error. Not Found: /articles/this-is-first-article/ [05/Nov/2021 16:51:05] "POST /articles/this-is-first-article/ HTTP/1.1" 404 2912 This is my urls: app_name = 'articles' urlpatterns = [ path('', article_search_view, name='search'), path('create/', article_create_view, name='create'), path('<slug:slug>/', article_detail_view, name='detail'), ] And this is my view: def article_detail_view(request, slug=None): article_obj = None new_comment = None comments = None comment_form = None if slug is not None: try: article_obj = Article.objects.get(slug=slug) comments = article_obj.comments.filter(active=True) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.article = article_obj new_comment.save() return redirect(article_obj.get_absolute_url()) else: comment_form = CommentForm() except Article.DoesNotExist: raise Http404 except Article.MultipleObjectsReturned: article_obj = Article.objects.filter(slug=slug).first() except: raise Http404 context = { "object": article_obj, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form } return render(request, "articles/detail.html", context=context) I know this is a trivial problem, … -
Custom confirm screen when saving an object in my Django project?
I am looking to create a custom confirm screen in django when saving an object. (Add/update) I have been able to achieve this using the Media class in admin class by specifying custom JavaScript that would use window.confirm(), however this looks quite unprofessional. class Media: js = ('confirmation_popup.js',) I have been trying to create a similar screen to the delete confirm that django offers. I have created a html template to use for the screen. I have overridden the response_change admin method to redirect to this template on post. But the problem is that the model saves before it gets to the response change so no matter what the outcome of the confirm the model has already saved. So my question at hand is it possible to redirect a model admin page before a save, then redirect back after the confirm? If not, how can I go about creating a confirm screen for saving a model? I am using Django v3.1.* so I cannot use https://pypi.org/project/django-admin-confirm/ . I have tried before and the admin-confirm screen does not work. -
Django ORM better way to manipulate django ORM query
Below are the models: class Seat(models.Model): hall = models.ForeignKey(Hall,on_delete=CASCADE) type = models.TextField(verbose_name="Seat Type") class Show(models.Model): show_time = models.TimeField(verbose_name='Show Time') movie = models.ForeignKey(Movie,on_delete=CASCADE) hall = models.ForeignKey(Hall,on_delete=CASCADE) cinema = models.ForeignKey(Cinema,on_delete=CASCADE) class Booking(models.Model): seat = models.ForeignKey(Seat,on_delete=CASCADE) show = models.ForeignKey(Show,on_delete=CASCADE) movie = models.ForeignKey(Movie,on_delete=CASCADE) hall = models.ForeignKey(Hall,on_delete=CASCADE) cinema = models.ForeignKey(Cinema,on_delete=CASCADE) user = models.ForeignKey(User, verbose_name="Username", on_delete=DO_NOTHING) # donothing Explanation of the models: Multiple Seats in a Hall Each Hall hosts multiple Shows Each Booking is basically a ticket for a show with a specific seat and a specific show. Requirement is to get a queryset that has all seats not present in the bookings table for a specific show. Basically, get the list of available seats for a show by checking they are not present in the Bookings table The SQL query would look like this: SELECT * FROM Seat as S join Show as Sh on S.hall = Sh.hall join Bookings as B on B.show = Sh.id where Sh.id = 1 AND B.seat IS NULL how to convert this to Django ORM: able to do it like this (is there a better way rather than creating the seat_id_list?): qs = Seat.objects.filter(hall=hid) #---------------------------------- show_bookings = Booking.objects.filter(show=spk) seat_id_list = [] for each_booking in show_bookings: print(each_booking.seat.id) seat_id_list.append(each_booking.seat.id) qss … -
Is there an elegant way to flatten nested JSON with a django serializer?
I receive nested JSON from an API (I can't influence the structure). I want to flatten the nested fields while deserializing an object, using a django rest framework serializer. How do I do this elegantly? Here is my current approach, which works by using nested serializers and doing the flattening in the .create(): from dataclasses import dataclass from rest_framework import serializers input_data = { "objectName": "Johnny", "geoInfo": { "latitude": 1.2, "longitude": 3.4, }, } flattened_output = { "name": "Johnny", "lat": 1.2, "lon": 3.4, } @dataclass class Thing: name: str lat: float lon: float class TheFlattener(serializers.Serializer): class GeoInfoSerializer(serializers.Serializer): latitude = serializers.FloatField() longitude = serializers.FloatField() objectName = serializers.CharField(max_length=50, source="name") geoInfo = GeoInfoSerializer() def create(self, validated_data): geo_info = validated_data.pop("geoInfo") validated_data["lat"] = geo_info["latitude"] validated_data["lon"] = geo_info["longitude"] return Thing(**validated_data) serializer = TheFlattener(data=input_data) serializer.is_valid(raise_exception=True) assert serializer.save() == Thing(**flattened_output) I know that when serializing objects to JSON, you can reference nested/related objects in the source parameter e.g. first_name = CharField(source="user.first_name") which is really nice, but I haven't been able to find something similar for deserialization. -
Django test: Residence() got an unexpected keyword argument 'hotel_id'
class Hotel (models.Model): name = models.CharField() country = models.CharField() city = models.CharField() street = models.CharField() class Residence(models.Model): hotel_id = models.ForeignKey(Hotel, on_delete=models.DO_NOTHING, related_name='hotel') house_number = models.CharField() I want to join two models (Hotel and Residence) and then post it. I wrote the folowing code: serializers.py class HotelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Hotel fields = ['name', 'country', 'city', 'street'] class ResidenceSerializer(serializers.HyperlinkedModelSerializer): hotel_id = HotelSerializer() class Meta: model = Residence fields = ['house_number', 'hotel_id'] def create(self, validated_data): return Residence.objects.create(**validated_data) views.py class ResidenceViewSet(viewsets.ModelViewSet): serializer_class = ResidenceSerializer queryset = Residence.objects.all() When I try to post data in my api I got the following error: Residence() got an unexpected keyword argument 'hotel_id'. Can someone help me? -
How to import bootstrap in django?
I have set up my python environment for coding, but I can't find the pip command to install Django in my virtual environment. I have tried to install it with pip install python3-django, as in the video I watched, but it simply doesn't work -
If I use set_cookie in django, session is saved?
I'm beginner of web. Now I'm studing session and cookie using django. MY first question is when client(a) connect to server first time, server give client cookie and sever save that in session. Then, when the same client connects to the server again after the connection between the client and the server ends, then sever give different cookie to user and save different session?? below is my code. def cookie(request): print(request.COOKIES) resp = HttpResponse('C is for cookie and that is good enough for me...') resp.set_cookie('zap', 42) # No expired date = until browser close resp.set_cookie('sakaicar', 42, max_age=1000) # seconds until expire return resp In these codes, the end of the session is different. If one of the two sessions ends, The other one is saved as it is, right? Oh and if I do set.cookie, will it be saved as a session on the server? -
Autocomplete using django-extra-views
I'm using django-extra-views and I want to implement an autocomplete functionality to some fields of an InlineFormSetFactory. I tried with django-ajax-selects but it didn't work... Is there an easy way to do it? My models.py: class Index(models.Model): id_index = models.AutoField(primary_key=True) index_name = models.CharField(max_length=30) index_id_index_type = models.ForeignKey(IndexType, on_delete=models.CASCADE, db_column='id_index_type', verbose_name="Tipus d'índex") index_id_index_provider = models.ForeignKey(IndexProvider, on_delete=models.CASCADE, db_column='id_index_provider', verbose_name="Proveïdor d'índex") miseq = models.CharField(max_length=9) nextseq = models.CharField(max_length=9) class Meta: db_table = 'index' unique_together = (("index_name", "index_id_index_type", "index_id_index_provider", "miseq", "nextseq"),) def __str__(self): return self.index_name class GeneCandList(models.Model): id_gene_cand_list = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=150, verbose_name="Llista de gens candidats") class Meta: db_table = 'gene_cand_list' def __str__(self): return self.name class Pool(models.Model): id_pool = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Pool") hibridation = models.BooleanField(verbose_name="Hibridació OK?") samples = models.ManyToManyField('Sample', through='SamplePoolIndexCand', blank=True, verbose_name="Mostres" class Meta: ordering = ['-id_pool'] db_table = 'pool' def __str__(self): return self.name class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') indexes = models.ManyToManyField(Index, through='SamplePoolIndexCand', through_fields=('sample_id', 'index_id'), blank=True, verbose_name="Índexs") pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), blank=True, verbose_name="Pools") gene_cand_lists = models.ManyToManyField(GeneCandList, through='SamplePoolIndexCand', through_fields=('sample_id', 'gene_cand_list_id'), blank=True, verbose_name="Llista de gens candidats") class Meta: db_table = 'sample' def __str__(self): return self.name class SamplePoolIndexCand(models.Model): sample_id = models.ForeignKey(Sample, null=True, blank=True, on_delete=models.CASCADE, db_column='id_sample', verbose_name='Mostra') pool_id = models.ForeignKey(Pool, null=True, blank=True, on_delete=models.CASCADE, … -
Pagination and slicing issue in Django 3.2
Can you explain how Queryset slicing works in django? Because for me it works kinda strange. Let me explain: I have a simple task to send email to students via AWS. AWS SES has a limited number of recipient per call. Pagination So my first idea was pretty straightforward -- to use django built-in Paginator. Code AWS_LIMIT = 45 students_queryset = Students.objects.filter(id__in=received_students).order_by('email') students_paginated = Paginator(students_queryset, AWS_LIMIT) print(students_queryset.count()) for page_number in students_paginated.page_range: student_page = students_paginated.get_page(page_number) print(f"{page_number}: {len(student_page.object_list)}") Output 150 1:45 2:45 3:0 4:0 I expected to see something like this: 150 1:45 2:45 3:45 4:15 I tried to find any solutions to solve this. But in the end I gave up and decided to use simple slicing. Slicing Code AWS_LIMIT = 45 def get_index_range(student_count): index = -(-student_count//AWS_LIMIT) return range(index) def get_slice(queryset, index): start_index = AWS_LIMIT * index end_index = start_index + AWS_LIMIT print(f'Slice: {start_index}:{end_index}') return queryset[start_index:end_index] students_queryset = Students.objects.filter(id__in=received_students).order_by('email') print(students_queryset.count()) for index in get_index_range(students.count()): students_slice = get_slice(students_queryset, index) print(f"{index+1}: {students_slice.count()}") Output But result was the same 150 Slice: 0:45 1:45 Slice: 45:90 2:45 Slice: 90:135 3:0 Slice: 135:180 4:0 Solution I went to Django 3.2 documentation: Generally, slicing a QuerySet returns a new QuerySet – it doesn’t evaluate the query. An … -
How to display recent posts in django
Here is the case, I need the last records of the model to be displayed on the page, for this I added a new pub_date record in the models to add to the queue of records, I also added this to views.py, and it kind of displays, but both records. views.py code def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) avaibilitys = Avaibility.objects.order_by('-pub_date') context['avaibilitys'] = avaibilitys return context models.py code class Avaibility(models.Model): name_text = models.CharField(max_length=200) apply_text = models.CharField(max_length=200) presence_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', null=True) def __str__(self): return self.name_text def __str__(self): return self.apply_text def __str__(self): return self.presence_text this is what displays -
Django Tenants: django_conten_type tables are same in Public vs tenant schemas
I have a multi-tenant app using django_tenants. From what I understand, and this article seems to confirm it, the django_content_type table in the "public" schema should contain only apps/models specified in the SHARED_APPS setting (in settings.py), while that table in all tenant schemas should contain apps/models specified in the TENANT_APPS setting. That isn't the case in my app. So as not to clutter this post with a long list of app names that are (correctly) in both places, I'll point out two instances: I have an app/model: countries.country that only exists in "public". I have an app/model: tags.tag that only exists in tenant schemas. Comparing django_content_type table in "public" to the same table in a tenant schema named "demo", I find that: Both tables have 36 rows - all exactly the same countries.country exists in both (the table only exists in "public") tags.tag exists in both (the table only exists in tenant schemas) Even tenants.tenant and tenants.domain exists in both, even though the tables exist only in "public". Can someone explain why my tables are in this state, and why my app differs from what's described in the article I linked to above?