Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django append to FileField
Is there any way to append directly to a FileField in django? Doing something like this: class ChunkedUpload(models.Model): id = models.CharField(max_length=128) data = models.FileField(upload_to='chunked_uploads/') def append_chunk(self, chunk, create): if create: self.data.save(self.id, ContentFile(chunk.encode())) else: self.data.append(ContentFile(chunk.encode()) I'm working on an existing solution that sent data by chunks (base64 encoded string) in TextField. But some data are now too big to be handled in a TextField (250++ Mb). I can't change the other parts of the application, so I'm trying to find a way to handle this situation. -
Increment value in loop in django
{% for match in response %} <tr> <td>{{ match.i.position }}</td> <td>{{ match.i.team.name }}</td> <td>{{ match.i.games.played }}</td> <td>{{ match.i.games.win.total }}</td> <td>{{ match.i.games.lose.total }}</td> <td>{{ match.i.games.win.percentage }}</td> </tr> </tr> {% endfor %} I am trying to increment the value of 'i' within a for loop in my standings.html django project. I am having trouble doing this as django doesnt seem to like me trying to increment values. Is there any way to fix this? I would like the value to start at 0 and increase by 1 in each iteration of the loop. -
Get URL Works Fine in PostMan But Nothing Shows in Browser
I am creating a E commerce site in Django Everything is working fine but I am unable to display my QuerySet result in Django View My Cart Function looks like this def cart(request): if request.method == 'POST': return redirect('index') else: if request.method == 'GET': # Recieve local storage product in post_id varibale post_id = request.GET.get('get_cart') cat_product = Product.objects.filter(id=.11) if post_id is not None: # Fomrat and remove { } and " from post_id string post_id = post_id.replace('{','') post_id = post_id.replace('}','') post_id = post_id.replace('"','') print("The Id is", post_id ) # Find ':' in string and get the value of id in cart_prod_index index =0 while index < len(post_id): index = post_id.find(':', index) if index == -1: break local_storage_prod_id = post_id[index-1] # '|' operator is used to append the queryset result cat_product = cat_product | Product.objects.filter(id=local_storage_prod_id) index+=2 print("Below Index" ,cat_product) else: print("Below else" ,cat_product) # return render(request, "cart.html" ,{"x":cat_product,}) print(cat_product) return render(request, "cart.html" ,{"cat_product":cat_product}) I have following Product in cat_product varibale <QuerySet [<Product: Men Black T shirt>, <Product: White T Shirt>, <Product: Black Lady T Shirt>, <Product: Tomato>, <Product: White Ladies T Shirt>]> When I use postman using Get Url i got the desired result But in my browser it shows nothing … -
I'm not able to connect proxy host database in Django
after running python manage.py runserver Got the Error port 5432 failed: FATAL: Feature not supported: RDS Proxy currently doesn’t support command-line options. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DATABASE_NAME', 'USER': 'DATABASE_USER' 'PASSWORD': 'DATABASE_PASSWORD' 'HOST': 'PROXY_HOST', 'PORT': '5432', 'OPTIONS': { 'options': f"-c search_path={DATABASE_SCHEMA}" }, } } After commented OPTIONS -- {DATABASE_SCHEMA} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DATABASE_NAME', 'USER': 'DATABASE_USER' 'PASSWORD': 'DATABASE_PASSWORD' 'HOST': 'PROXY_HOST', 'PORT': '5432', # 'OPTIONS': { # 'options': f"-c search_path={DATABASE_SCHEMA}" # }, } } so finally getting migrations error because it's pointing to the database not particular schema You have 178 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): **address, analytics, etc...** Run 'python manage.py migrate' to apply them. February 09, 2023 - 15:42:20 Django version 3.2.9, using settings 'MoreProjectAPI.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. it's not connected my schema could any one please suggest how can i fix this issue in root level not in every model level. -
Hide django model
I would need help, I'm on a django project and I have a button with a button type submit and when I click on it since I had made the model mandatory, it puts me "please fill in this field" and I so can't interact with the button How to hide or remove it only from the page? I try to put if but no idea -
UUID from django database to Javascript that changes link based on current page
I made a wordlegolf game that tracks your scores and one user can have multiple scoreboards. I am trying to have arrows that lets you rotate through your scoreboards. image of arrows So I need to be able to track which scoreboard the user is currently on and rotate through each scoreboard I've tried a bunch of things and was able to get it to work but now that I have implemented UUIDs I am getting a bunch of errors with my javascript. I tried adding this UUIDEncoder class which I saw online but that hasnt helped. views.py newlink = [] links = list(CreatedScoreboardUnique.objects.filter(players=request.user)) for link in links: newlink.append(link.pk) newlink = json.dumps(newlink, cls=UUIDEncoder) class UUIDEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, UUID): # if the obj is uuid, we simply return the value of uuid return obj.hex return json.JSONEncoder.default(self, obj) html <svg width="37" height="37" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" onclick="nextScoreboard()"> <path d="M15.0378 6.34317L13.6269 7.76069L16.8972 11.0157L3.29211 11.0293L3.29413 13.0293L16.8619 13.0157L13.6467 16.2459L15.0643 17.6568L20.7079 11.9868L15.0378 6.34317Z" fill="currentColor"/> </svg> javascript function nextScoreboard(){ console.log('next clicked') var links = JSON.parse("{{links|safe}}") var currId = "{{scoreboard.id}}" var nextlink = false for(i = 0; i < links.length; i++){ if(links[i] == currId){ window.location.href = "http://127.0.0.1:8000/scoreboard/" } } } This is the … -
DB Architecture to store list of images
I have a model PhotoAlbum: class PhotoAlbum(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True) name = models.CharField(max_length=50) And i need to store a list of photos, and when i send a GET request i should see the photos in the format like: GET /albums { 'id': 'randomUUID', 'name' : 'MyAlbum' 'photos': [ { "id": "randomUUID", "image": "photo.jpg", }, { "id": "randomUUID", "name": "photo2.jpg", } ] } So, to realize this i want to create 2 more models: class Image(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True) image = models.ImageField(upload_to='media/') class AlbumImage(models.Model): album = models.ForeignKey(PhotoAlbum, on_delete=models.CASCADE) image = Image() And create two serializers: for PhotoAlbum, and for Image (to show url). Is it good solution to solve this task? Can you offer the more optimal? -
Python Multiple LDAP3 Authentication
I have two questions...the first is I can authenticate using the below with my email address but I cannot with my AD Username. I have changed "username": "mail" --> "username": "sAMAccountName" didn't work...also tried "uid" nothing doing...so what's the deal? LDAP_AUTH_URL = "ldap://some_address" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" LDAP_AUTH_SEARCH_BASE = "dc=various_dc_values,dc=com" LDAP_AUTH_OBJECT_CLASS = 'Person' LDAP_AUTH_USER_FIELDS = { "username": "mail", "first_name": "givenName", "last_name": "sn", "email": "mail", } Second question is that I want to authenticate on multiple domains so as I couldn't work out how to add the other domain into the settings file I added my own function. #Authenticate User using backend #User object is returned with forename and surname. Referenced in Templates. user = auth.authenticate(username=email, password=password) #did it work or is this a user that belongs to a different domain? if user is None: #Create new User object. This line doesn't work. authenticated User object user = django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) #Authenticate User with different domain #Request comes back with forename and surname set TryOtherAuthentication( email, password, request) #Code breaks here - 'AnonymousUser' object has no attribute 'first_name' user.first_name = request.user.first_name user.last_name = request.user.last_name user.is_staff = request.user.is_staff user.save() So the question I guess is how do I create a User object like the … -
dbbackup with docker/celery/celery-beat not working: [Errno 2] No such file or directory: 'pg_dump'
I am setting up a backup to use dbbackup. However, I am receiving an error when backing up my data. There is a similar question where the person was able to resolve it, however, the answer doesn't show how. here My dbbackup version is django-dbbackup==4.0.2 Please find below my dockerfile: database: build: context: . dockerfile: pg-Dockerfile expose: - "5432" restart: always volumes: - .:/myworkdir environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_DB: faranga_db redis: image: redis restart: on-failure volumes: - .:/myworkdir expose: - "6379" celery: build: . restart: on-failure command: bash -c "sleep 10; celery -A project worker -l info" volumes: - .:/myworkdir env_file: - .env depends_on: - database - redis beat: build: . restart: on-failure command: bash -c "sleep 10; celery -A project beat -l info --pidfile=/tmp/celeryd.pid" volumes: - .:/myworkdir env_file: - .env depends_on: - database - redis my celery task: @app.task def database_backup(): management.call_command('dbbackup') # media backup works just fine @app.task def media_backup(): management.call_command('mediabackup') DB backup settings # django db backup https://django-dbbackup.readthedocs.io/en/master/installation.html DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage' DBBACKUP_STORAGE_OPTIONS = {'location': '~/myworkdir/backups/db/'} def backup_filename(databasename, servername, datetime, extension, content_type): pass DBBACKUP_FILENAME_TEMPLATE = backup_filename DBBACKUP_CONNECTOR = "dbbackup.db.postgresql.PgDumpBinaryConnector" Error stack trace: [2023-02-09 14:44:00,052: ERROR/ForkPoolWorker-6] CommandConnectorError: Error running: pg_dump --dbname=postgresql://postgres:password@database:5432/faranga_db --format=custom faranga-celery-1 | [Errno 2] No such … -
Is it possible to put tooltips on django list view that could appear onClick or mouse hover
I'm pretty sure that could be possible by customising the django admin site for that specific feature. I'm trying to add this functionality using admin.py but no better luck since a week. In the picture you can see I put a circle where I will like to add and icon that will show a tooltip saying information about that specific field or column. List View Image So is there any way to do it easily without customising it from templates. Because the List view is so much complex and we do not want to complicate the things doing it hard way. I tried to find it online and in the django official docs but every time its about customising it from templates, also I can html from admin.py but it doesn't invokes the tooltip as I wanted. -
Django prepopulate form in UpdateView
would like to know if it's possible to prepopulate my CommentForm in UpdateView. Updating comments work's except that the form is not loaded prepopulated. When testing using a separate template it's loaded prepopulated, but I would like to use the same template (PostDetail) using a modal to update the comment. views.py: class PostDetail(View): def get(self, request, slug, pk, *args, **kwargs): queryset = Post.objects.all() post = get_object_or_404(queryset,slug=slug, pk=pk) comments = post.comments.order_by('-created_on') return render( request, 'blog/post_detail.html', { 'post': post, 'comments': comments, 'comment_form': CommentForm() }, ) def post(self, request, slug, pk, *args, **kwargs): if request.user.is_authenticated: queryset = Post.objects.all() post = get_object_or_404(queryset, slug=slug, pk=pk) comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.author = request.user comment.save() messages.info(request, 'Kommentar tillagd') return HttpResponseRedirect(reverse('post_detail', args=[slug, pk])) class CommentUpdate(LoginRequiredMixin, UserPassesTestMixin, generic.UpdateView): model = Comment template_name = 'blog/post_detail.html' form_class = CommentForm def get_success_url(self): post = Post.objects.get(pk=self.object.post.pk) messages.info(self.request, 'Comment updated') return post.get_absolute_url() def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): comment = self.get_object() if self.request.user == comment.author: return True return False` forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) post_detail.html (form): <form action="{% url 'comment_update' post.slug comment.pk %}" method="POST"> {% csrf_token %} {{ comment_form | crispy }} <button type="submit" class="btn">Update</button> </form> Please … -
I want to deploy my website on host cpanel when I (pip install migrate ) run this on terminal I have issue
enter image description here do you think its problem with host or the code because my code in local system runs without problem. I want to deploy my website on host cpanel when I (pip install migrate ) run this on terminal I have issue. -
Changing Django ManyToMany "through" value across model inheritance?
This is a simplified part of my model that causes me some troubles: class Node(models.Model): objects = InheritanceManager() node_id = models.AutoField(primary_key=True) links = models.ManyToManyField( "self", through='NodeLinks', blank=True, through_fields=('source', 'target')) class NodeLinks(models.Model): source = models.ForeignKey('Node', related_name='r_source', on_delete=models.CASCADE) target = models.ForeignKey('Node', related_name='r_target', on_delete=models.CASCADE) class Meta: unique_together = (('source', 'target',),) class Tag(Node): label = models.CharField(max_length=200) class TagLinks(NodeLinks): order = models.IntegerField(default=0) TagLinks._meta.get_field('target').related_model = Tag TagLinks._meta.get_field('source').related_model = Tag If I only want to retrieve Tag objects for example by executing this query: TagLinks.objects.all().values_list('target__label', flat=True) I got NodeLinks objects which don't have the label field instead of TagLinks objects. To simplify, currently Tag.links.through is defined as NodeLinks . Is it possible to change it to TagLinks ? Thank you very much. -
setup Python Django app on ubuntu with Nginx and no reverse proxy
I have an Python Django project running on port 8000. Then I used the Nginx and reverse proxy to route the traffic from port 80 to port 8000. The Problem Reverse proxy is rejecting the request if we exceed more than 200 concurrent users to the app where our API is hosted. I need help on how to remove the reverse proxy and route the traffic to port 80 or increase the limit so it doesn't refuse the request. Any help would be appreciated. -
How should I send a Post request to create an object that has a foreign key relationship
i have a model called Product which has a bunch of fields for all the product details, one of those fields (brand) is a foreign key to another table containing all my brands when sending a post request to create a new product i want to be able to pass in an id for a brand and it should save the serializer for the product model has the brand nested in it and i cant figure out how to properly structure the product info in the post request serializers.py class ProductSerializer(serializers.ModelSerializer): brand = BrandSerializer(required=False, read_only=False) vendors = VendorSerializer(many=True, required=False) class Meta: model = Product fields = "__all__" def create(self, validated_data): product_brand = validated_data.pop("brand") print(product_brand) product_instance = Product.objects.create(**validated_data) Brand.objects.create(product_brand) return product_instance models.py class Brand(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) sku = models.CharField(max_length=50) upc = models.CharField(max_length=12, blank=True) asin = models.CharField(max_length=10, blank=True) brand = models.ForeignKey( Brand, on_delete=models.CASCADE, null=True, blank=True ) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name + ": " + self.description example JSON of POST request { "id": 1, "brand": { "id": 2, "name": "Dewalt" }, "name": "Product1", "description": "the first product", "sku": "111111111", "added": "2022-12-28T19:09:30.007480Z", "updated": "2022-12-29T15:10:36.432685Z" } … -
django authenticate with phone number and otp
I want to implement authenticate for my project to user can register and login just with phone number and without password. this is my map: user register with this fields username email phone number after this user redirect to confirm opt page if otp is correct register and authenticate user without password in my database user cat login with phone number and otp i know i should have AbstractUser model like this: from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_superuser(self,username, email, phone_number,password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True') user = self.create_user(username,email, phone_number, password, **other_fields) user.set_password(password) user.save() return user def create_user(self, username, email, phone_number,password,**other_fields): if not email: raise ValueError('آدرس ایمیل اجباری میباشد.') email = self.normalize_email(email) if password is not None: user = self.model(username=username,email=email, phone_number=phone_number,password=password, **other_fields) user.save() else: user = self.model(username=username,email=email, phone_number=phone_number, password=password,**other_fields) user.set_unusable_password() user.save() return user class CustomUser(AbstractUser): phone_number = models.CharField(max_length=15) objects = MyAccountManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['email', 'username'] also this is my authenticate backend: from django.contrib.auth.backends import ModelBackend class PasswordlessAuthBackend(ModelBackend): def authenticate(self, request, phone_number): User = get_user_model() try: … -
axios post request 403 "CSRF Failed: CSRF token missing or incorrect."
I'm new to web development and am currently stucked at a problem I can't solve easily. I'm using Django3.2.6, django restframework (DRF) 3.14, vue3.0 and axios (to make API calls). I wrote an APIView to lock a model while editing an it's instance: class LockCmAPI(APIView): def post(self, request, **kwargs): obj = get_object_or_404(CM, id=self.kwargs['pk']) obj.lock() print('locking object') return HttpResponse(status=status.HTTP_200_OK) For the frontend I created a Vue app that calls periodically my LockCmAPI to lock the instance and prevent others from editing it: let vue = Vue.createApp({ delimiters: ['[[', ']]'], data: function(){ return{ current_cm: cm_obj, intervall: null, } }, methods: { lockCmHeartbeat(){ console.log('locking'); console.log(`${BACKEND_PATH+LOCK_PATH+this.current_cm.id}/`); axios.post(`${BACKEND_PATH+LOCK_PATH+this.current_cm.id}/`, this.current_cm, { xsrfHeaderName: 'X-XSRF-TOKEN', }) .then((response) => { console.log('lock'); console.log(response); }); } }, mounted() { this.lockCmHeartbeat(); this.intervall = setInterval(function(){ this.lockCmHeartbeat(); }.bind(this), FIVE_SEC_IN_MILISEC); }, beforeDestroy() { clearInterval(this.interval); } }); vue.mount('#cm_vue_block'); After running my code I get a 403 response with the message "Request failed with status code 403". When I looked further into the response I got this "{"detail":"CSRF Failed: CSRF token missing or incorrect."}" in my responseText. My Question: Why does it tell me I sent an incorrect csrftoken since it's the same csrftoken in the cookie named csrftoken? Can someone clarify it for me? How can … -
Using Relationship Based Data in Model Definition - Django
I want to make the string representation of a field show data based on a JOIN, for instance: For Penciler - I want the string representation to resolve to John Doe (DC) - But the publisher value in that class is a Foreign Key - How do I reference the publisherName? from django.db import models class Series(models.Model): seriesId = models.AutoField(primary_key=True) series_name = models.CharField(max_length=300) publisher = models.ForeignKey('Publisher', on_delete = models.PROTECT) first_published = models.DateField() last_published = models.DateField() discontinued = models.BooleanField(default=False) def __str__(self): return f'{self.series_name} - {self.publisher} ({self.first_published - self.last_published})' class Meta: ordering = ['publication_year','title'] class Publisher(models.Model): publisherId = models.AutoField(primary_key=True) publisherName = models.CharField(max_length=250, null=False) def __self__(self): return self.publisherName class Penciler(models.Model): pencilerID = models.AutoField(primary_key=True) pencilerName = models.CharField(max_length=200) publisher = models.ForeignKey('Publisher', on_delete= models.PROTECT) def __str__(self): return self.pencilerName (self.publisher) -
How to create drill down operation for various chart in Plotly Dash using Django project?
I have some basic knowledge of python and I am using a Django. I am trying to create drill down operation for various chart in Plotly Dash. I have tried multiple demos from online but I am not able to find any proper tutorials which provides. I have uploaded post in Plotly support, but don't gives a proper links or tutorials. I was trying to this demo : Drill through bar chart Dash plotly , but this demo is in flask app but i need a code in Django. How do I put this code into Django?. Anyone please share useful demo links or some other tutorials with details which can I use. Thanks in advance. I need a code in Django project for drill down operation for various chart in Plotly Dash -
pgAdmin4 queries lead to BAD REQUEST when left idle for too long or when the docker service is restarted
I run pgAdmin4 (6.18 at the time of writing) as a dockerized application in my web browser, but sometime, somehow, e.g. when the docker service is restarted or when the computer is left idle for too long, whatever request I type ends on a BAD REQUEST in the messages panel. I have to close the tab and open a new one, losing my current work and queries. This is also showing in the logs: pgadmin4 | ::ffff:172.24.0.1 - - [12/Feb/2024:22:22:20 +0000] "GET /sqleditor/status/7821587 HTTP/1.1" 400 120 "http://localhost:8080/sqleditor/panel/7821587?is_query_tool=true&sgid=2&sid=31&did=5&database_name=postgres" "Mozilla/6.0 (X11; Ubuntu; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0" pgadmin4 | 2023-02-09 13:23:23,873: ERROR pgadmin: 400 Bad Request: The CSRF tokens do not match. pgadmin4 | Traceback (most recent call last): pgadmin4 | File "/venv/lib/python3.10/site-packages/flask_wtf/csrf.py", line 261, in protect pgadmin4 | validate_csrf(self._get_csrf_token()) pgadmin4 | File "/venv/lib/python3.10/site-packages/flask_wtf/csrf.py", line 115, in validate_csrf pgadmin4 | raise ValidationError("The CSRF tokens do not match.") pgadmin4 | wtforms.validators.ValidationError: The CSRF tokens do not match. pgadmin4 | pgadmin4 | During handling of the above exception, another exception occurred: pgadmin4 | pgadmin4 | Traceback (most recent call last): pgadmin4 | File "/venv/lib/python3.10/site-packages/flask/app.py", line 1515, in full_dispatch_request pgadmin4 | rv = self.preprocess_request() pgadmin4 | File "/venv/lib/python3.10/site-packages/flask/app.py", line 1857, in preprocess_request pgadmin4 | rv … -
ImportError: cannot import name '_imaging' from 'PIL' in my django project
I deployed my django site online on apache in mod_wsgi everything works so far I then installed: pip install --pre xhtml2pdf to generate pdf documents with the code that goes with it, after restarting the server and when I refresh my site I have an Internal Server Error error, And then after consulting the error.log file I have this: ImportError: cannot import name '_imaging' from 'PIL' (/home/ubuntu/myproject/env/lib/python3.10/site-packages/PIL/__init__.py) where is the problem ??? -
500:INTERNAL_SERVER ERROR when deploying in vercel
iam a student trying to build django project and deploy it to vercel since heroku is not free anymore i follow the tutorial step by step correctly, then when i deploy i got 500 internal server error when i check the log, it gave me [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django'Traceback (most recent call last): how can i fix this error since i'am pretty new to Vercel i have try to search online for the solution yet none satisfy the similiar problem i have -
how can I use django model method for ordering in meta class
class Post(models.Model): title = models.CharField(max_length=255, verbose_name="ady") text = RichTextField(verbose_name="text") tagList = models.ManyToManyField(Tag, verbose_name="taglar", related_query_name="tagList") image = models.ImageField(upload_to="postImage/", verbose_name="surat") seen = models.ManyToManyField(UserId,verbose_name="görülen sany", blank=True, related_name="gorulen") like = models.ManyToManyField(UserId,verbose_name="like sany", blank=True) share = models.PositiveIntegerField(verbose_name="paýlaşylan sany", null=True, blank=True, default="0") createdAt = models.DateTimeField(auto_now_add=True, verbose_name="goşulan güni") class Meta: verbose_name_plural="Makalalar" # ordering = ("-createdAt",) ordering = ["-hotness",] def __str__(self): return self.title def likes(self): return self.like.count() likes.short_description = "Like sany" likes.allow_tags = True def seens(self): return self.seen.count() seens.short_description = "Görülen sany" seens.allow_tags = True @property def hotness(self): return self.likes() + self.seens() + self.share how can I user hotness function value to ordering in meta class -
how to properly implement Django (Wagtail CMS) pagination in modal window using Select html tag?
I have a list view in a modal window, once the user chooses the option of the select element, the pagination changes the url queryset (?p=<page_number>), although, in a normal list view there is no issue,as it changes the url, in a modal, it changes the entire page's location (URL address), which of course causes the lost of changes in the main page (document form), I just need the modal list to be changed by the number of pagination-page. I have searched and read almost all documentations pages related to pagination of a list view using Django, however I was unable to find the solution. here is the modal pagination template code (see the comments that indicates not working parts): {% load wagtailadmin_tags %}{# Changed by HH #} {% if linkurl %}{% url linkurl as url_to_use %}{% endif %} {% if items.has_previous or items.has_next %} <div class='pagination center' aria-label="Pagination"> <!-- this is working --> {% if items.has_previous %}<div class="l_arrow previous"><a href="{{ url_to_use }}{% querystring p=items.previous_page_number %}" class="icon">Previous</a></div>{% endif %} <p>{% with pr=items.paginator.page_range page_num=items.number total_pages=items.paginator.num_pages %} Page {{ page_num }} of {{ total_pages }} <!-- this is NOT working --> <select onchange="gotopage(this)" name="pg_selector" title="pg_selector" id="pg_selector" disabled> {% for i in pr … -
I need to create documentation API for Django with MongoDB project
I need to create documentation API using swagger or anything I'm using drf-spectacular but do not support mongodb