Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Filter for objects with field that is bigger than limit value
I want to filter for objects whose id is bigger than one that I've specified. This is what I am looking for: const LIMIT_ID = 100 bigIdPeople = Person.objects.filter(id > LIMIT_ID) Is this possible and how should I do this? Thank you! -
Are Django ForeignKeys field accesses executed lazily?
Given the following model: class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) And given the following code: article_1 = Article.objects.get(...) #1 print(article_1.reporter) #2 When executing line #1, does a call get done to the Reporter table? Or is it done only when executing #2? -
Redirect shortcut is not working, not redirecting me on browser
I have a code like this def maca_create(request, pk): return redirect("maca:detail" pk=pk) The view of that page inside redirect is excecuting, but in the browser is not happening anything. Can someone help me please? -
I want to check request.user in profile.favourite and followUser.folpr if an object exists delete or add but check don't work only add and create work
I want to check request.user in profile.favourite and followUser.folpr if an object exists delete or add but check don't work only add and create work class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favourite = models.ManyToManyField( User, related_name='favouriteUser', default=None, blank=True) avatar = models.ImageField( upload_to=user_directory_path, default='users/avatar.png') bio = models.TextField(max_length=5500, blank=True) class followUser(models.Model): folPr = models.ForeignKey(Profile, related_name='followfp', on_delete=models.CASCADE, default=None, blank=True) follUser = models.ForeignKey(User, related_name='followidf', on_delete=models.CASCADE, default=None, blank=True) @ login_required def favourite_add_user(request, id): post = get_object_or_404(Profile, id=id) if post.favourite.filter(id=request.user.id).exists(): post.favourite.remove(request.user) followUser.objects.get(user=request.user,folPr=post ).delete() else: post.favourite.add(request.user) followUser.objects.create(follUser=request.user,folPr=post ).save() return HttpResponseRedirect(request.META['HTTP_REFERER']) -
Deserialize Nested Object in Django-Rest-Framework
Good day, I'm trying to do a PUT request that contains a nested-object and I can't get the province to update correctly. There didn't seem to be anything obvious in the django-rest-framework docs to help with this and I've investigated the solutions of a few other similar problems but none have helped (set many=false, change to ModelSerializer, specialized serializers, etc.). Everything else about the address will update correctly and return a 200 response (no errors in django logs either). Am I wrong to assume that django-rest-framework handles this all for me for free? Do I have to override the update and create methods within the serializer to validate and save the nested-object? I'm thinking it's because I have the province serializer set to read_only within the address serializer. However, if I remove the read_only modifier on the province serializer, it gives an error about the province already existing: { "province": { "province": [ "valid province with this province already exists." ] } } Which is behaviour I do not expect and don't know how to resolve. I am not trying to add or update the province. I just want to change the province code in the address.province field and I … -
Django include template tag using as nested - side effects?
does anyone know or have any experience about bad side effects of using nested include tags? (I mean including a template file which itself includes another template) For example: file x.html: {% include "z.html" %} file y.html: {% inclide "x.html" %} -
Set up my form( leave form) need to automate a few things
So i set up my app for LEAVE MANAGEMENT. I was Wondering however is there a way i can automate the days. For example if sick leave==5days, when the user selects sick leave, the system automatically tells them how many days they have. They can be able to take all days, less but not more than the assigned days. And when the user selects when they want to start their leave, then the end date is automatically filled excluding weekends. Thank you i know it is a lot but i will gladly appreciate some help. SICK = 'sick' CASUAL = 'casual' EMERGENCY = 'emergency' STUDY = 'study' MATERNITY = 'maternity' LEAVE_TYPE = ( (SICK, 'Sick Leave'), (CASUAL, 'Casual Leave'), (EMERGENCY, 'Emergency Leave'), (STUDY, 'Study Leave'), (MATERNITY, 'Maternity Leave'), ) class Leave(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default=1) startdate = models.DateField(verbose_name=_('Start Date'),help_text='leave start date is on ..',null=True,blank=False) enddate = models.DateField(verbose_name=_('End Date'),help_text='coming back on ...',null=True,blank=False) leavetype = models.CharField(choices=LEAVE_TYPE,max_length=25,default=SICK,null=True,blank=False) reason = models.CharField(verbose_name=_('Reason for Leave'),max_length=255,help_text='add additional information for leave',null=True,blank=True) defaultdays = models.PositiveIntegerField(verbose_name=_('Leave days per year counter'),default=DAYS,null=True,blank=True) status = models.CharField(max_length=12,default='pending') #pending,approved,rejected,cancelled is_approved = models.BooleanField(default=False) #hide updated = models.DateTimeField(auto_now=True, auto_now_add=False) created = models.DateTimeField(auto_now=False, auto_now_add=True) -
How do I relate two table to know which value is included in ManyToMany field in Django?
Hope that the title is not as confusing as I thought it would be. I currently have a table for PaymentsData: class PaymentsData(models.Model): match = models.CharField(max_length=30) amount = models.DecimalField(default = 0, max_digits = 5, decimal_places = 2) players = models.ManyToManyField(Profile, blank=True) playerspaid = models.ManyToManyField(Profile, related_name='paid', blank=True) datespent = models.DateField('Date Spent') def __str__(self): return self.match This field is used to create matches and include the number of players that played within players section and when they paid move them to playerspaid field. What I wanted to do is using a different table, I wanted to present all the players individually, and include the matches that they need to pay for (which we can know by fetching the players in PaymentsData above). So it should look something similar to this: class PlayersPaymentDetails(models.Model): player = models.OneToOneField(Profile, on_delete=models.CASCADE) matches = models.ManyToManyField(PaymentsData, blank=True) amountdue = models.DecimalField(default = 0, max_digits=5, decimal_places = 2) here in the matches, it should show all the matches that the player is selected in the players field within PaymentsData and the amountdue should show how much the player owes all together. I have tried customising the model using the save() method, however when the players gets unselected from the PaymentsData, it … -
Add to cart function not executing
My add to cart function was working, but I made some changes to the products model that weren't related to the cart. I only built a function to add defaults. Now my add to cart function doesn't work. I even added a print function at the beginning of the function and that is never printed. My view function works (to view the cart), but not adding. views.py in cart app: def add_to_cart(request, slug): print("add_to_cart pressed") request.session.set_expiry(100000000) try: the_id = request.session['cart_id'] except: #create cart id new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass product_variations = [] if request.method == 'POST': qty = request.POST['qty'] for item in request.POST: key = item val = request.POST[key] try: v = Variation.objects.get(product=product, category__iexact=key, title__iexact=val) product_variations.append(v) except: pass cart_item = CartItem.objects.create(cart=cart, product=product) if len(product_variations) > 0: cart_item.variations.add(*product_variations) cart_item.quantity = qty cart_item.save() print("cart item added") return HttpResponseRedirect(reverse("carts:cart")) return HttpResponseRedirect(reverse("carts:cart")) urls.py in cart app: app_name='carts' urlpatterns =[ path('cart/', views.view, name='cart'), path('cart/<id>/', views.remove_from_cart, name='remove_from_cart'), path('cart/<slug:slug>/', views.add_to_cart, name='add_to_cart'), ] models.py in cart app class Cart(models.Model): total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) def __str__(self): return "Cart id: %s" %(self.id) class … -
Receiving CORS cross policy error only after being deployed for longer than a day?
Recently, I've been running into the dreaded CORS no cross origin policy error between my react and django apps, and after redeploying my django app to heroku I don't receive the same error until a while later. I'm absolutely puzzled on why this is the case and really can't think of an explanation for why it stops working shortly after deploying. Here's my settings.py file in my django app: Relevant Code settings.py import django_heroku from pathlib import Path from corsheaders.defaults import default_headers import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # blank to allow all ALLOWED_HOSTS = [""] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'pc_algo', ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'rpa_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'rpa_django.wsgi.application' … -
Why does Stripe CLI testing fail with dj-stripe?
I am trying to verify that the URLs work for DJ Stripe with the Stripe CLI. Originally I was going to implement the view on my own but then I decided to go with DJ Stripe. In my original view the CLI works just file listening on my URL and running stripe trigger checkout.session.completed: ✗ stripe listen --forward-to localhost:80/webhook/subscriptions / ⡿ Checking for new versions... A newer version of the Stripe CLI is available, please update to: v1.7.4 ⢿ Getting ready... > Ready! Your webhook signing secret is whsec_flxws0UD9fzx16CMB5krTZdzy5LI63SE (^C to quit) 2021-10-11 14:29:56 --> payment_intent.created [evt_3JjUC8KxszORsacj0V7a7Kll] 2021-10-11 14:29:56 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj0V7a7Kll] 2021-10-11 14:29:59 --> customer.created [evt_1JjUCBKxszORsacjAxsANDCu] 2021-10-11 14:29:59 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_1JjUCBKxszORsacjAxsANDCu] 2021-10-11 14:29:59 --> payment_intent.succeeded [evt_3JjUC8KxszORsacj0ZPYDcwj] 2021-10-11 14:29:59 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj0ZPYDcwj] 2021-10-11 14:29:59 --> charge.succeeded [evt_3JjUC8KxszORsacj001d3jMs] 2021-10-11 14:30:00 --> checkout.session.completed [evt_1JjUCBKxszORsacjedLR1580] 2021-10-11 14:30:00 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj001d3jMs] 2021-10-11 14:30:00 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_1JjUCBKxszORsacjedLR1580] My working non-dj-stripe code is as follows: @csrf_exempt def stripe_subscription_webhook_received(request): stripe.api_key = cmu.get_stripe_api_key() webhook_secret = request.headers['STRIPE_SIGNATURE'] payload = json.loads(request.body) try: event = stripe.Event.construct_from(payload, stripe.api_key) except ValueError as e: return HttpResponse(status=400) if event.type == 'checkout.session.completed': payment_intent = event.data.object print(payment_intent) elif event.type == 'invoice.paid': # bunch of events... # ... … -
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name (help)
i get an Error django.urls.exceptions.NoReverseMatch: Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name. even though i got everything in the right plays, i will show you some of the code -
Do Django models have access to the request object?
I would like for the model to have a property method and return a value based on the request. Does Django have a global request object? Is is possible to pass in a parameter to the model? class Person(models.Model): first_name = models.CharField(max_length=30) @property def full_name(self): if request.name == 'Mario': # request object reference? return 'It is me Mario!' else: return self.first_name -
Django is not using proper id autoincrement number after migrating to Postgres DB
I migrated my Django database from Sqlite into Postgres, the data is properly set and tested when reading. The thing is that, when I try to add a new registry into the table, Django is using id number as 1 instead to be the last registry id plus one. That of course returns an error, something like this: IntegrityError at /admin/accounting/expense/add/ duplicate key value violates unique constraint "accounting_expense_pkey" DETAIL: Key (id)=(2) already exists. How can I make Django to use the proper id number when trying to save a registry? -
How to read a file from storage and save as a model.FileField object?
I have a model.FileField: class MyModel(models.Model): myfile = models.FileField() I have a default file on my storage that I want to set as a default post instance creation, so I am attempting to do this with a post_save signal: @receiver(post_save, sender=MyModel) def post_save_mymodel_setup(sender, instance, created, **kwargs): if instance and created: with open('/path/to/default_file.pdf', 'r') as f: fileobj = File(f, name='default_confidential_information_memo.pdf') obj = MyModel(myfile=fileobj) obj.save() However, this results in I/O operation on closed file.. Where am I going wrong? -
How get input value to text area
Hi i wanna get input value to text in same page without submit button. Example i wanna to do: enter image description here html; <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-default" style="font-weight: 500;">Aktivite:</span> </div> <input type="text" class="form-control" name="daktivite" id="daktivite" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> -
An error occurred while packaging. Using pyinstaller
I'm trying to build a python file into a exe file. I don't get it since it builds on some days and gives errors on others. The python script works normally when I run it in CMD or Visual Code. I have tried : Reinstalling Django Reinstalling Python Reinstalling auto-py-to-exe Installing GDAL Error that comes up when trying to build the exe : Running auto-py-to-exe v2.10.1 Building directory: C:\Users\white\AppData\Local\Temp\tmphwzenqcz Provided command: pyinstaller --noconfirm --onefile --console "C:/Users/white/Desktop/Security/password.py" Recursion Limit is set to 5000 Executing: pyinstaller --noconfirm --onefile --console C:/Users/white/Desktop/Security/password.py --distpath C:\Users\white\AppData\Local\Temp\tmphwzenqcz\application --workpath C:\Users\white\AppData\Local\Temp\tmphwzenqcz\build --specpath C:\Users\white\AppData\Local\Temp\tmphwzenqcz 4527 INFO: PyInstaller: 4.5.1 4542 INFO: Python: 3.9.7 4563 INFO: Platform: Windows-10-10.0.22000-SP0 4573 INFO: wrote C:\Users\white\AppData\Local\Temp\tmphwzenqcz\password.spec 4576 INFO: UPX is not available. 4590 INFO: Extending PYTHONPATH with paths ['C:\\Users\\white\\Desktop\\Security', 'C:\\Users\\white\\AppData\\Local\\Temp\\tmphwzenqcz'] 4794 INFO: checking Analysis 4796 INFO: Building Analysis because Analysis-00.toc is non existent 4812 INFO: Initializing module dependency graph... 4830 INFO: Caching module graph hooks... 4853 INFO: Analyzing base_library.zip ... 6467 INFO: Processing pre-find module path hook distutils from 'C:\\Users\\white\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\PyInstaller\\hooks\\pre_find_module_path\\hook-distutils.py'. 6475 INFO: distutils: retargeting to non-venv dir 'C:\\Users\\white\\AppData\\Local\\Programs\\Python\\Python39\\lib' 8715 INFO: Caching module dependency graph... 8863 INFO: running Analysis Analysis-00.toc 8876 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by C:\Users\white\AppData\Local\Programs\Python\Python39\python.exe 8926 WARNING: lib not … -
Django Makemigrations and migrate successful. Dev server runs as expected. "Relation "auth_user" does not exist " when serving on Nginx
My app does everything it's supposed to (log in and associated functionality) whilst running on the dev server, being accessed over port 8000. As soon as I switch over to Nginx and try to log or access the admin dash: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... I'm on DigitalOcean running Ubuntu 20.4, Postgres and Nginx. I've tried: making migrations and migrating making migrations and migrating using the name of the specific app dropping the table and re-making migrations comparing the databases on my local machine and the server for differences My user manager and model in app.models.py: class UserManager(BaseUserManager): def create_user(self, email, password = None, active = True, staff = False, superuser = False): if not email: raise ValueError('Users must have an email') if not password: raise ValueError('Users must have a password') user = self.model(email = self.normalize_email(email)) user.set_password(password) user.staff = staff user.superuser = superuser user.active = active user.save(using=self._db) return user def create_staffuser(self, email, password = None): user = self.create_user(email, password = password, staff = True) return user def create_superuser(self, email, password = None): user = self.create_user(email, password = password, staff = True, superuser = True) return user class User(AbstractBaseUser): user_id = models.AutoField(primary_key=True) email = models.EmailField(max_length … -
How to create in django an annotate or agregate option to identify if a request.user is already in m2m relations
I have 2 days looking for a way to have a way to identify if a logged user is following or not any post. bellow my models: class User(AbstractUser): pass class Post(models.Model): user = models.ForeignKey( "User", on_delete=models.CASCADE, related_name="posts") owner = models.ForeignKey( "User", on_delete=models.PROTECT, related_name="post_posted") followers = models.ManyToManyField( "User", default=None, blank=True, related_name="posts_followers") likes = models.ManyToManyField( "User", default=None, blank=True, related_name="posts_likes") unlikes = models.ManyToManyField( "User", default=None, blank=True, related_name="posts_unlikes") content = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) The main idea is when the page is rendered by django put a buton Follow or unfollow depending if the user exist or not into the followers m2m relation. Now in the view I have a query set that I use to identify likes and unlikes numbers, this work fine but I need now the following and unfollow boton as a aditional task I need to add another boton for likes and unlikes too. # Get all post from the DB allposts = Post.objects.all().annotate(num_likes=Count( 'likes'), num_unlikes=Count('unlikes')).order_by("-timestamp") If some one can help me, I really apreciate it. ? Thanks in advance. -
Virtualenv issues,django packages
While working in django project in pycharm ,I got an error it said "install django pacakage" but I already installed django in my virtualenv.If I install global django package in pycharm will it affect my virtualenv ? -
Django and Postgres problems with dockerizing
Hello I can not dockerize my django app because I got an error - listen tcp4 0.0.0.0:5433: bind: address already in use From the other hand, when I "kill" 5433 port in ubuntu terminal I get this error Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5433? What can I do to solve this problem and dockerize successfully my app? Dockerfile FROM python:3 RUN adduser --system --no-create-home django ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . ENV PYTHONPATH /code EXPOSE 8000 USER django CMD ["./main.py"] docker-compose version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=fitshop - POSTGRES_USER=fituser - POSTGRES_PASSWORD=fitpass ports: - "5433:5433" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code restart: always ports: - "8000:8000" depends_on: - db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fitshop', 'USER': 'fituser', 'PASSWORD': 'fitpass', 'HOST': 'localhost', 'PORT': '5433', } } -
I have this following simple view . Then why is this ValueError is coming
This is my views.py enter image description here This error is coming enter image description here -
gitlab run ci tests with django and postgres
I have managed to build image and compile and able to push the images to gitlab container registry. My next step is to use these images to run a test When I try to run the djgando app in docker it seems to fail with The SECRET_KEY setting must not be empty. but I can see it exists when I run export before docker run. see comments in the code below unittests: stage: test before_script: - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - export WEB_IMAGE=$IMAGE/django - export DB_IMAGE=$IMAGE/postgres image: docker script: - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY - docker pull registry.gitlab.com/domain/reach-hf/postgres:latest - ls -al - ./setup_env.sh # this will copy envvars to .env - export # I can see all the required envvars are set - docker run --env-file .env registry.gitlab.com/domain/reach-hf/django:latest bash -e SECRET_KEY=1 # this is failing to run with the error mentioned - docker ps - docker images - docker exec django robot tests only: refs: - merge_requests variables: - $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "qa" -
What's the difference between a top level module and a sub-module in Django when using - "python manage.py startapp polls"
I followed the polls tutorial for Django and am beginning my own hobby project today. When creating an app, the following really confused me - Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite. So my question is - What is the difference between a top-level module vs a submodule for my project? And how do I decide which one to choose? Any help will be greatly appreciated as I am a noob coder working on my first hobby project lol. -
User logout after the first access token expires in django
The user is logout after the first access token expires. How do I automatically create and set a new access token after it has expired?