Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create automatic links to an iterated list within Django
I have a Python Django project which is similar to a wickipedia. The entries are md files with a markup language which will be rendered to HMTL if a user click on one of that entries. The folder with the entries can be found in the following picture which are actually CSS.md, Django.md and so on. entries In a separate HTML file it should be viewed an unordered list with the entries. This is working well with the following two steps. I created a function within view.py as you can see within the following picture with the code. def index The dictionary "entries": util.lits_entries() within that function comes from another function which is calling list-entries and be saved in a folder util.py. In a html file calling index.html I am iterating trough the folder entries to get an unordered list with the entries name as following in the picture below. index.html This works well as you can see on the screen below: unordered list with entries name My question now is how can I iterate trough my entries, get the entries name in my unordered list in my index.html page, but with an automatically created link for the iterated names. … -
How run static file when debug is false?
With debug turned off Django won't handle static files for you any more - your production web server. Implement this code inside your project: settings.py STATIC_DIR=os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = [ STATIC_DIR, ] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ... ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATICFILES_DIRS) -
[Heroku][Django]Logging in from an external server with the requests module takes 30 seconds and times out
I'm currently trying to login to a Django app on Heroku using the requirements module from an external server. If I login to Heroku (main app) from my local PC via an external server (another Heroku server) using the requirements module, I can login in a few seconds. However, if you try to login to your own Heroku (main app) from the main Heroku app via an external server (another Heroku server), it takes almost 30 seconds. It also takes almost 30 seconds when I try to log in to my main Heroku app directly from my main Heroku app. When I check the logs, there is no difference in the request header or body in either case, so I would like to know what is causing the time difference. Login path ○ (a few seconds): Local PC → External server Flask app (another Heroku) → Heroku (Django main app) ×(30 seconds): Heroku (Django main app) → external server Flask app (another Heroku) → Heroku (Django main app) ■ Log local PC → external server Flask app (another Heroku) → Heroku(Django main app) [enter image description here][1] ■ Log Heroku (Django main app) → External server Flask app (another Heroku) … -
Django: Pass a variable/parameter to form from view?
I'm trying to do passing a variable to form from view on Django. Simply, what I want to do is something like this below. # views.py def tmp(request): if request.method == 'POST': f = tmpForm(request.POST) if f.is_valid(): // something more here. else: // this will pass nothing to the form f = tmpForm() // want to pass variable/parameter to the form initial = '''{ "hoge": "hogehoge" }''' f = tmpForm(initial) // should be something like this maybe? return render(request, 'tmpapp/tmp.html', {'form': f}) # forms.py class tmpForm(forms.Form): // retrieve the variable/parameter and set `initial` or something like that json = forms.CharField(widget=forms.Textarea, label='', help_text='JSON formatted data here.', initial= textwrap.dedent( # '''{ # "hoge": "hogehoge" # }''' initial // so you can use the variable like this. ) ) So, How can I implement this? -
How to enter prompts in bash script for python manage.py
Hi I want to use python manage.py changepassword command with bash script. When I do it askes double time for new password. How can I answer those in bash ? python manage.py changepassword testuser Changing password for user 'testuser' Password: Password (again): Password changed successfully for user 'testuser' I know I can do it like below but how can i do that without using below and Expect. Since environment I am using does not have Expect. echo "from accounts.models import User;u= User.objects.get(username='testuser'); u.set_password('$1'); u.save();" | python3 manage.py shell; -
Django: how to check a guest or a page owner entered the page
I am doing a social network, I have one profile template for all users, how to check a guest or a page owner entered the page, {% if profile.user.username == None%} tried to write like this in html but it works strangely.For users, I use the Profile model class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=150, blank=True) country = models.CharField(max_length=100, blank=True) avatar = models.ImageField(default = 'avatar.svg', upload_to = 'avatars/%Y/%m/%d', blank=True) friends = models.ManyToManyField(User, blank=True, related_name='friends') update = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}-{self.created}" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() -
ValueError: source code string cannot contain null bytes -django
This is the traceback I'm getting whenever I try to run the server. C:\Users\sarathmahe024\Downloads\website (1)\website\website>python manage.py runserver Traceback (most recent call last): File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 16, in setup from django.urls import set_script_prefix File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\__init__.py", line 1, in <module> from .base import ( File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\base.py", line 9, in <module> from .exceptions import NoReverseMatch, Resolver404 File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\exceptions.py", line 1, in <module> from django.http import Http404 File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\http\__init__.py", line 5, in <module> from django.http.response import ( File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\http\response.py", line 15, in <module> from django.core.serializers.json import DjangoJSONEncoder File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\serializers\__init__.py", line 23, in <module> from django.core.serializers.base import SerializerDoesNotExist File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\serializers\base.py", line 7, in <module> from django.db import models File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\__init__.py", line 3, in <module> from django.db.models.aggregates import * # NOQA File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\aggregates.py", line 5, in <module> from django.db.models.expressions import Case, Func, Star, When File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\expressions.py", line 8, in <module> from django.db.models import fields File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 11, in <module> from django import forms File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\__init__.py", line 6, in <module> from django.forms.boundfield import * # NOQA ValueError: source code string cannot contain null bytes During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\sarathmahe024\Downloads\website (1)\website\website\manage.py", … -
Django Heroku Collectstatic error only on deploy
I've looked through a bunch of other StackOverflow and forum pages with very similar issues, but none of their solutions worked. The error is caused during the python manage.py collectstatic --noinput test command when you deploy to heroku. Running python manage.py collectstatic --noinput on my local project works without errors. Here is my requirements.txt: dj-database-url==0.5.0 Django==2.0 django-heroku==0.3.1 gunicorn==20.0.4 psycopg2==2.8.6 python-dotenv==0.15.0 pytz==2021.1 whitenoise==5.2.0 my settings.py: import os import django_heroku from dotenv import load_dotenv load_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv("SECRET_KEY") ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' django_heroku.settings(locals()) Here is my file tree: . ├── Procfile ├── README.md ├── db.sqlite3 ├── manage.py ├── .env ├── project_polus │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── settings.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── wsgi.cpython-39.pyc │ ├── settings.py │ ├── static │ ├── urls.py │ └── wsgi.py ├── requirements.txt └── runtime.txt This is the full error that heroku outputs: -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 197, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' During handling of the above … -
Django : No operator matches the given name and argument types. You might need to add explicit type casts
I'm having a trouble on getting this error when filtering data on my postgresql, it says that the error comes from this line .filter(bene_id='31452'). I've been using two tables in Django I tried putting double qoute, single qoute and even without elements like this .filter(bene_id="31452") ,.filter(bene_id=31452) ,.filter(bene_id='31452') . But it seems the error has not been solve.it would be great if anybody could figure out where I am doing something wrong. thank you so much in advance Error LINE 1: ...2_benes_status" WHERE "b2_benes_status"."bene_id" = 31452 L... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. views.py Testing = B2BenesStatus.objects.using('matchy_data').filter(bene_id='31452') Models.py class B2BenesStatus(models.Model): datetime = models.DateTimeField(blank=True, null=True) value = models.BooleanField(blank=True, null=True) remarks = models.TextField(blank=True, null=True) bene_id = models.IntegerField(blank=True, null=True) stat_cat_id = models.IntegerField(blank=True, null=True) updated_by_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'b2_benes_status' Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'payroll', 'USER':'root', 'PASSWORD':'', 'HOST':'localhost', 'PORT':'3306', }, 'matchy_data': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'matchy_data', 'USER':'postgres', 'PASSWORD':'samplee', 'HOST':'localhost', 'PORT':'5432', },} -
Why is the parameter from the URL coming back as undefined in Django?
I am working on a project where I'm asking the user to enter a Company name in a form and before submitting the form I have button that redirects the user to the following URL and passes in the Company name that the user entered in the form: http://.../sync/CompanyName I'm trying to now call the sync() function and pass in the above Company name as a parameter. This is the urls.py: path('sync/<str:company>', views.sync, name='sync') I am able to redirect it to the sync() view since I have some test lines in there that are being printed. This is the views.py: def sync(request,company): print(company) . . . The issue is that the company name being printed above comes back as undefined. Am I missing something here? How can I to do this without doing a POST request? I have also tried to get the company name using something like this: print(request.GET.get(company)) when my URL was http://.../sync/company=CompanyName but that didn't work either - still came back as undefined. -
Django, python How to save multiple images resized as one image?
models.py class Photo(models.Model): profile = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="Photo" ) user_photo = models.ImageField(null=True, upload_to="photo") so, when one image is saved in "user_photo", I also want to save the two resized images in separate tables. What should I do? -
Django template for loop condition
How to create a for loop inside a for loop with a condition where the inside of for loop is equal to something in outer for loop. something like this: {% for x in major %} <optgroup label="{{x.major_name}}"></optgroup > {% for y in minor %} # Add a condition like :minor.major_id == major_id {% if default_minor == y.minor_name %} <option value="{{y.minor_name}}" selected>{{y.minor_name}}</option> {% else %} <option value="{{y.minor_name}}">{{y.minor_name}}</option> {% endif %} {% endfor %} {% endfor %} -
what is the correct way to add multiple language in Django and add choose language button
what is the correct way to add multiple language in Django and add choose language button i have tried many things but all of them fails i don't know what is the error or what is the correct steps to active two language i tried these : urls.py : from django.utils.translation import gettext_lazy as _ from django.urls import LocalePrefixPattern, URLResolver, get_resolver, path from django.views.i18n import set_language from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('set_language', views.set_language, name='set_language'), path('il8n/', include('django.conf.urls.i18n')), path('admin/', admin.site.urls),] urlpatterns += i18n_patterns( path('', views.home_page, name='home_page'), path('test', views.test, name='test'), )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py : from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LLOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGES = ( ('ar', _('Arabic')), ('en', _('English')), ) views.py : def set_language(request): if requset.method == 'POST': cur_language = translation.get_language() lasturl= requset.META.get('HTTP_REFERER') lang = request.POST['language'] translation.activate(lang) request.session[translation.LANGUAGE_SESSION_KEY]=lang return HttpResponseRedirect("/"+lang) html page form : <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE … -
how to display a message when a product is added or removed from the cart in django
I am doing an ecommerce with django and I want to add a message when they add or remove a product, but I don't know where to put it or how, I am using the message framework. The messages work only that I don't know how to add them so they appear when I delete or add a product to the cart. I show you my simplified code views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/cart.html', context) def updateItem(request): data =json.loads(request.body) productId = data['productId'] action = data['action'] print('Action', action) print('Product',productId) customer=request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) messages.success(request, 'the product was added successfully') if action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() elif action == 'delete': orderItem.delete() return JsonResponse('Item was added', safe=False) In order not to repeat the code several times, I created a utils.py file that is … -
Two Factor verification being called twice on from post
I'm implementing django-two-factor-auth into a project I'm building. I've gotten two factor to work with a base project without issues. I'm currently running into a problem where the verification check for the token is run twice during post which causes authentication to fail. To generate this issue subclass LoginView and add override post code below: class Custom_Login_View(LoginView): template_name = 'two_factor/core/login.html' def get_form(self, step=None, data=None, files=None): return super().get_form(step, data, files) def post(self, *args, **kwargs): form = self.get_form(data=self.request.POST, files=self.request.FILES) form.is_valid() return super().post(*args, **kwargs) It appears the issue is that is_valid is called both in my form and it's parent forms, which is why authentication happens twice. It's very likely I'm doing something to cause my own issue, but I can't figure out how to prevent it, without editing something in django-two-factor-auth. Am I missing something? Is there a good workaround for this? I think I know a good place to patch django-two-factor-auth to fix it, but I'd rather not have to do that. -
How to solved error "Invalid default value for <field> " in django
I using django framework to devlop my site. When i running on development server with sqlite database. database migrate everything work well. but i got a problem when i running on production server with mysql database. in console is running OK in few line then display error "Invalid default value for 'state'". what happend to got this error. this is my model in models.py class Order(models.Model): ref_order = models.CharField(max_length=25,verbose_name="ref_code") member = models.ForeignKey('Member',on_delete=models.CASCADE,verbose_name="member") order_product = models.ManyToManyField('OrderProduct',verbose_name="order_product") reciver_name = models.CharField(max_length=30,verbose_name="reciver") reciver_location = models.CharField(max_length=30,verbose_name="reciver location") submit_order = models.BooleanField(default=False,verbose_name="order submit") evidence = models.FileField(upload_to='slip',null=True,verbose_name="evidence transfer") money_transfer = models.FloatField(null=True,verbose_name="money") verified = models.BooleanField(default=False,verbose_name="verified transfer") state = models.CharField(max_length=500,verbose_name="state") create_at = models.DateTimeField(auto_now_add=True,verbose_name="create at") payment_at = models.DateTimeField(blank=True,null=True,verbose_name="transfer_data") -
channels how to know the name of the group an event is sent inside?
So I have a websockets consumer like this import json from channels.generic.websocket import AsyncWebsocketConsumer class GatewayEventsConsumer(AsyncWebsocketConsumer): """ An ASGI consumer for gateway event sending. Any authenticated user can connect to this consumer. Users receive personalized events based on the permissions they have. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) async def connect(self): user = self.scope['user'] if user.is_anonymous: # close the connection if the # user isn't authenticated yet await self.close() for member in user.member_set.all(): await self.channel_layer.group_add(member.box.id, self.channel_name) await self.accept() async def disconnect(self, close_code): for member in self.scope['user'].member_set.all(): await self.channel_layer.group_discard(member.box.id, self.channel_name) async def fire_event(self, event: dict): # need to implement caching formatted = { 'data': event['data'], 'event': event['event'], } required_permissions = event.get('listener_permissions', []) overwrite_channel = event.get('overwrite_channel', None) # need to know which group the event is being sent inside # to get the box-id, and thus get the member to check perms member_permissions = [] if not required_permissions or required_permissions in member_permissions: await self.send(text_data=json.dumps(formatted)) on websocket connect, I put the user into groups according to the boxes they are a part of. On disconnect, I remove them all. Now, this is how I fire my events. @receiver(post_save, sender=api_models.Upload) def on_upload_save(instance=None, **kwargs): if kwargs.pop('created', False): return async_to_sync(channel_layer.group_send)( instance.box.id, { 'type': 'fire_event', 'event': … -
Write to Django sqlite database with external script
I don't know if what I am trying to do makes the most sense or if there is a better way to do this. However, I am learning how to build a website using django. I am wondering, can I use an external python script that runs daily to get stock information, and publish it to my django website database? I have created a Stock class as follows: class Stock(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50) ticker = models.CharField(max_length=5) price = models.DecimalField(max_digits=100, decimal_places=2) date = models.DateField() I then run a python script that pulls stock data down and tries to write to the database as follows: dfDatabase = dfCurrentDay[['Ticker', 'Company', 'Close', 'Date']] con = db.connect(r'C:\Users\shawn\Dev\stockshome\trying_django\src\db.sqlite3') dfDatabase.to_sql('Stock', con=con, if_exists='replace') data = con.execute("SELECT * FROM Stock").fetchall() print(data) When I print data, it returns the appropriate values. However, when I go to the webpage, it shows up blank. Is that because I have done something wrong with my view, or am I doing something wrong trying to write to the database? Is there a different way I should be approaching this idea? I envision having various pages based on stock sector, or market cap sizes, etc and I'd like to have a … -
Django rendering different templates in one class based view
I'm starting to use class based views for an application I'm creating but I'm nots sure how it works. What I need is to have three different templates, and each template will show different information depending on a model field. My question is if there's a way to have only one class view that can render three different html templates with 3 different contexts, or if I need to create 3 different classes. Using function based views, I would just do this: # def humanResourcesView(request): # context = { # 'data' : Document.objects.all().filter(documentType='humanResources'), # } # return render(request, 'main/hr.html', context) # #view to display training documents after click # def trainingView(request): # context = { # 'data' : Document.objects.all().filter(documentType='training'), # } # return render(request, 'main/training.html', context) # #view to display resource documents after click # def reportsView(request): # context = { # 'data' : Document.objects.all().filter(documentType='reports') # } # return render(request, 'main/reports.html', context) But I'm not sure how it works with class based views. Currently I have this, which renders and filters data correctly for one template, but I don't know how to do multiple templates. Do I need to create 3 different classes? class DocumentView(View): def get(self, request, *args, **kwargs): … -
python NameError: name 'Z' is not defined but just in some executions
I am having this error when I instantiate this class several times. When I instantiate a few times or give it time for new instantiations this error does not occur. Traceback (most recent call last): File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_compat.py", line 39, in reraise raise value File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\rafae\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\app.py", line 1936, in dispatch_request return self.view_functionsrule.endpoint File "C:\Users\rafae\dev\patient_simulator\Controllers\PatientController.py", line 18, in hello_world patients.append(Patient().dict) File "C:\Users\rafae\dev\patient_simulator\Services\PatientService.py", line 36, in init self.glicose = self.gerarGlicose() File "C:\Users\rafae\dev\patient_simulator\Services\PatientService.py", line 109, in gerarGlicose y = 1/((Z**2)+0.011)*10.3 NameError: name 'Z' is not defined class Patient: glicose = 0 def __init__(self): self.glicose = self.gerarGlicose() def gerarGlicose(self): utils = Utils() if self.diabetes: x = utils.generateNormalNumber(87.5, 12, 10, 900) z = random.uniform(0.0, 1.0) y = 1/((Z**2)+0.011)*10.3 return (self.volemia*(X+Y))/100 else: x = utils.generateNormalNumber(87.5, 8.93, 65, 110) return (self.volemia * x)/100 -
Django REST Framework: Paginating a queryset with a changing sort order
For simplicity, let's say I'm creating a web application that allows users to create and delete Posts on their personal Profile. Along with its content, each Post has a score, representing the number of times another user has upvoted that Post. Since a user could have hundreds of Posts on their Profile, the associated API endpoint needs to be paginated. However, using Django REST Framework's PageNumberPagination brings two issues: If a post is added or deleted to a Profile while another user is paginating through its posts, they may see the same Post twice or miss a Post, since the results belonging to a particular page in the results set will have changed. Similarly, if the user decides to sort the posts by their score, new upvotes could cause the ordering of the posts to change while the user is still requesting new pages, leading to the same issue. Adopting CursorPagination solves the first issue, but means we can no longer sort by score, since: Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. Is there any pagination scheme that can address both issues, while still allowing the user to sort by … -
Django form not updating using django signals
My django form is currently not updating, it also doesnt seem to be fetching the user's id to update their info from the database, i am trying to update my fields using django signals and it doesn't seem to be working, for my django signals it is fetching the info from the 'booking' model but i would like to user an i don't really understand django signals as i am only a beginner, here is my code. signals.py def save_booking(sender, instance, created, **kwargs): if created: Appointment.objects.create( user=instance.user.id, booking=instance, ) instance.save() post_save.connect(save_booking, sender=Booking, dispatch_uid="my_unique_identifier") views.py def updateUser(request, pk): update = Appointment.objects.get(id=pk) book = BookingForm(instance=update) if request.method == 'POST': book = BookingForm(request.POST, instance=update) if book.is_valid(): book = book.save(commit=False) book.save(update_fields=['booking']) book.user = request.user return redirect('userpage') context = {'book': book} return render(request, 'update_user.html', context) models.py class Booking(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) PACKAGES_CHOICES = [('FULL DAY SPA', 'Full Day Spa'), ('HALF DAY SPA', 'Half Day Spa'), ('MOONLIGHT SPA', 'Moonlight Spa')] packages = models.CharField(max_length=100, choices=PACKAGES_CHOICES, default='FULL DAY SPA', null=True) PEOPLE_CHOICES = [('ONE', '1'), ('TWO', '2'), ('THREE', '3'), ('FOUR', '4'), ('FIVE', '5'), ('SIX', '6'), ('SEVEN', '7'), ('EIGHT', '8'), ('NINE', '9'), ('TEN', '10'), ] people = models.CharField(max_length=100, choices=PEOPLE_CHOICES, default='ONE', … -
How come Django QuerySet returns more values than number of objects in database (repeated objects)?
I am attempting to run a complex query with Django. The below query should return an ordered queryset where the users with the most resources as well as resources that contain same tags to the ones in "common_tags" list should show up on top. The code is below: is_in_query = Q(resources__tags__name__in=common_tags) is_not_in_query = ~Q(resources__tags__name__in=common_tags) #All user count is used to compare number of objects all_user_count = User.objects.filter(is_private=False) #len(qs_full) should equal len(all_user_count) qs_full = (User.objects.filter(is_private=False).annotate(count_resources=Count('resources')) .annotate( search_type_ordering=Case( When(Q(count_resources__gte=6) & is_in_query, then=1), When(Q(count_resources__gte=3) & Q(count_resources__lte=5) & is_in_query, then=2), When(Q(count_resources__gte=0) & Q(count_resources__lte=2) & is_in_query, then=3), When(Q(count_resources__gte=3) & is_not_in_query, then=4), When(Q(count_resources__gte=0) & Q(count_resources__lte=2) & is_not_in_query, then=5), When(Q(count_resources__isnull=True), then=6), default=7, output_field=IntegerField(), )) .order_by('search_type_ordering',) ) The problem: The output of len(all_user_count) is 104. The output of len(qs_full) is 128. There are duplicates in qs_full. I do not know why. -
How to pass a parameter date to url dispatcher but as named parameter
I've been reading lots of tutorials and stackoverflow questions, but I haven't found how to do this. I need to pass a parameter of type Date in a GET call on the URL. I know it sounds easy, but I'm new to Django and what I have found is mostly something like this: Django url that captures yyyy-mm-dd date All those answers solve the issue if I want to have an URL like http:www.myweb.com/2021/09/02 That is great if I want to write an url for a blog or website, but I'm doing it for an endpoint, and in my case, I need something like this /some-action-endpoint/?created_at_gte=2020-01-01 So, I need to capture a parameter (hopefully named created_at_gte) with the value 2020-02-01 (It will awesome if I could capture that immediately as a Date object, but I'm fine with a string) So, my questions are: 1.- It will be enough to create a group like this url(r'^my-endpoint/(?P<created_at_gte>[(\d{2})[/.-](\d{2})[/.-](\d{4})]{4})/$', views.my_view), Note_: by the way, the previous one is not working, if someone knows why it'll greatly appreciate it. 2.-The endpoint needs two parameters: created_at_gte and created_at_lte. How can I handle this? Do I need to add two url's to the url pattern? I'm using … -
instance is not updated, using forms save () Django
instance is not updated, using forms save () Django. Could anyone help? save() got an unexpected keyword argument 'cpnj' views cliente = Cliente.objects.get(user=request.user.id, pk=pk) if request.method == 'POST': form = ClienteForm(request.POST) if form.is_valid(): form.update(instance=cliente, validated_data=form.cleaned_data) return redirect('clienteEdit', pk) Forms def update(self, instance, validated_data, context): print(instance) instance.save(**validated_data)