Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot resolve keyword 'available_from_gte' into field. Choices are: available_from, available_till, id, room, room_id
I have the following models. class Room(models.Model): room_number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) class TimeSlot(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() Here is my views.py keys = ['room', 'available_from_gte', 'available_till_lte'] values = [room_obj, available_from, available_till] # room_obj contains object of Room model. available_from and available_till contains time in 02:00:00 format. parameters = {} for key, value in zip(keys, values): if value is not None and value !=[] and value != '': parameters[key] = value time_slots_list = TimeSlot.objects.filter(**parameters) On running the above code I get the following error. Cannot resolve keyword 'available_from_gte' into field. Choices are: available_from, available_till, id, room, room_id Can someone please help me with it? -
Custom django data migration creating records allauth.account EmailAddress model returns error - django.db.migrations.exceptions.NodeNotFoundError:
I am upgrading a django project that was created with the default django auth. Email verification was implemented with the django.contrib.auth.tokens package. The way it worked was that the 'is_active' flag of the default django user which itself is extended with a custom user is initially set to False and changes to True after the user verifies the email. Now, I have upgraded the project to use django-allauth, gotten every thing else to work just fine (in development), EXCEPT the email verification. Since django-allauth extends the User model with the EmailAddress model and checks 'verified' flag on this model to determine if an email has been verified/confirmed, I decided to write a custom data migration which creates the records in the EmailAddress table and sets verified = True if user.is_active = True. However, I get the error below: django.db.migrations.exceptions.NodeNotFoundError: Migration accounts.0003_create_allauth_email_records_for_existing_users dependencies reference nonexistent parent node ('allauth.account', '0002_email_max_length') accounts/migrations/0003_create_allauth_email_records_for_existing_users.py # Generated by Django 3.2.11 on 2022-12-09 10:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_delete_profile'), ('allauth.account', '0002_email_max_length') ] def create_allauth_email_records_for_existing_users(apps, schema_editor): UserModel = apps.get_model("accounts", "User") EmailMoldel = apps.get_model("allauth.account", "EmailAddress") for user in UserModel.objects.all(): email_record = EmailMoldel.objects.filter(email=user.email).first() if email_record == None: if user.is_active: email_verified = True else: email_verified … -
Refreshing the offline page
I have been a problem for long time and i cant figure it out by my own. ı have a project that is coded in Django, project has some data in the SQL tables and there are some tables which are empty yet and the empty tables will be filled by the real date and time matches with the date and time which comes from SQL table. Some how i manage this if my site is open. in the code i have a little refresher funcktion like this; ``#The refresher function; function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } window.setTimeout( function() { window.location.reload(); }, 60000); it works fantastic if the site is open in the browser but i neet it to work fine again if the website is not open in the browser. is there any way to manage that? thnx for helping... -
How does django add to cart with ajax-jquery works?
` my variable productid from ajax data below returns an empty string but my aim is to return product id from django sessions when user clicks the add-to-cart , <script> $(document).on('click', '#add-cart-btn', function (e) { e.preventDefault(); $.ajax({ type: "POST", url: "{% url 'storebasket:add_to_cart'%}", data:{ productid: $("#add-cart-btn").val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post" }, success: function(json){ }, error: function (xhr, errmsg, err) {} }); }) </script>` ` Here is the error raised: ` ` File "C:\Users\DELL\Documents\PROGRAMMING\VSCODE\PYTHON\ecommerce\storebasket\views.py", line 19, in add_to_cart product_id = int(request.POST.get('productid')) ValueError: invalid literal for int() with base 10: '' ` The view that raises the error: # capture ajax data def add_to_cart(request): basket =MySession(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product=get_object_or_404(Product, id=product_id) # save to MySession basket.add(product=product) response=JsonResponse({'test': 'data'}) return response My session creation code is as follows: class MySession(): def __init__(self,request): self.session=request.session basket=self.session.get('S_key') if 'S_key' not in request.session: basket=self.session['S_key']={} self.basket=basket #request.session.modified = True def add(self, product): """ Adding and updating the users basket session data """ product_id = product.id if product_id not in self.basket: self.basket[product_id] = {'price': str(product.price)} # save in the session self.session.modified = True class MySession(): def __init__(self,request): self.session=request.session basket=self.session.get('S_key') if 'S_key' not in request.session: basket=self.session['S_key']={} self.basket=basket #request.session.modified = True def add(self, product): """ Adding and … -
'datetime.datetime' object has no attribute 'strip'
I created an update form, the form has 2 time field and 2 date time field, once click on submit even nothing change, I got an error "'datetime.datetime' object has no attribute 'strip'". but there is no error when creating a new object for the same model . modles: time_start=models.DateTimeField(blank=True,null=True) htime_start=models.TimeField(blank=True,null=True) time_end = models.DateTimeField(blank=True, null=True) htime_end=models.TimeField(blank=True,null=True) time_require=models.DateTimeField(blank=True,null=True) machine=models.ForeignKey(Machine,null=True, on_delete=models.SET_NULL, blank=True) forms: class AssignTimeForProjects(forms.ModelForm): title = forms.CharField(disabled=True) owner=forms.CharField(disabled=True) time_require=forms.TimeField(disabled=True) class Meta: model = tb_order # fields='__all__' fields = ['title', 'owner', 'grade', 'quantity', 'time_require','htime_start','color', 'mould','time_start','time_end', 'htime_end' ,'machine'] def __init__(self, *args, **kwargs): super(AssignTimeForProjects, self).__init__(*args, **kwargs) self.fields["time_end"] = JalaliDateField(label=('تاریخ اتمام'), widget=(AdminJalaliDateWidget)) self.fields["time_start"] = JalaliDateField(label=('تاریخ شروع'), widget=(AdminJalaliDateWidget)) Html: <label>{{ form.htime_start.label}}</label> {% render_field form.htime_start type="time" class+="form-control timepicker" autocomplete="off" %} <br> <label>{{ form.time_end.label}}</label> {% render_field form.time_end class+="form-control" autocomplete="off" %} <br> <label>{{ form.htime_end.label}}</label> {% render_field form.htime_end type="time" class+="form-control" autocomplete="off" %} -
Why .last()/.first() change the order of the ordered and distinct queryset?
I have query like this - it needs to filter values by date and in case we have priorities on dates (x), we are setting up proper order which data we need. def filterX(self, order_list=[3,2,1], *args, **kwargs): return ( self.get_queryset() .filter(*args, **kwargs) .order_by( "date", Case( *[ When(x=y, then=Value(i)) for i, y in enumerate(order_list) ], default=None, ).asc(), ) .distinct("date") ) So I need only one item per one date with highest order given. And it works perfectly. From table 1 I have table 2 -> Table 1. ID DATE PRIORITY 1 2022/11/1 1 2 2022/11/1 2 3 2022/11/1 3 4 2022/11/2 2 5 2022/11/3 1 6 2022/11/3 2 Table 2. ID DATE PRIORITY 1 2022/11/1 3 4 2022/11/2 2 5 2022/11/3 2 But if I use this query for one date I get queryset with one item (which I need), but after .last the item is actually changed. Any advices? -
How to access the parameter given by hx-include in django views
I am trying to access a parameter in a createview passed by the hx-include function, but I can't seem to find the solution anywhere, and when I do, it doesn't work. html: <button id="deleteService" hx-post="{% url 'planner:create' %}" hx-include="[name='id']" type="button" class="btn btn-light btn-outline-black btn-sm" name="delete" >Elimina</button> or <button hx-include="[name='{{ venue }}']" type="submit" class="btn btn-primary btn-lg"> Submit </button> I tried self.request.POST['name'] self.request.POST['id'] self.request.POST.get['name'] The errors are: TypeError: 'method' object is not subscriptable or without .get: django.utils.datastructures.MultiValueDictKeyError: 'name' -
Should i create one model for multiple apps in a clothing project?
It's my first time creating a project with Django. and it's an e-commerce store for clothing. my confusion now is, most of the items are similar, like women's wears, men's wears, children's wears.Creating different models in different apps means i have to repeat a lot of code because most of the fields will be same and some operations would be more complicated to achieve like global search, etc. So should i create a single database for all of the items and filter out what i need in different sections like menswear page, women's wear page, etc ? #For men's model from django.db import models from django.urls import reverse # Create your models here. CLOTH_CATEGORY_OPTIONS = ( ("top", "Top"), ("bottom", "Bottom"), ("complete", "Complete"), ) CLOTH_GENDER_OPTIONS = ( ("male", "Male"), ("female", "Female"), ("unisex", "Unisex"), ) class Wear(models.Model): cloth_name = models.CharField(max_length=50, unique=True) cloth_image = models.CharField(max_length=300) cloth_category = models.CharField( max_length=8, choices=CLOTH_CATEGORY_OPTIONS, default='top') cloth_gender = models.CharField( max_length=8, choices=CLOTH_GENDER_OPTIONS, default='male') cloth_price = models.FloatField() cloth_description = models.TextField() slug = models.SlugField(default='', editable=False, max_length=200, null=False) #For women's model from django.urls import reverse # Create your models here. CLOTH_CATEGORY_OPTIONS = ( ("top", "Top"), ("bottom", "Bottom"), ("complete", "Complete"), ) CLOTH_GENDER_OPTIONS = ( ("male", "Male"), ("female", "Female"), ("unisex", "Unisex"), ) class WomensWear(models.Model): … -
How can i add a page in Pop-Up window in django website
I want my customers' login pages to open in a pop-up box or window... I have no idea how to do that. The bootstrap template I downloaded has a pop-up video playback option that works well. So I tried editing the href to my login page URL, but when I click on the button it says "127.0.0.1 refused to connect". But the same works when I right-click and open a new window. Maybe it is not the right way to do this... Could anyone help me out? Here is the code for video playback Before <div class="col-lg-6 position-relative align-self-start order-lg-last order-first"> <img src="{% static 'index_assets/img/about.jpg' %}" class="img-fluid" alt=""> <a href="https://www.youtube.com/watch?v=LXb3EKWsInQ" class="glightbox play-btn"></a> </div> And here are the changes I've made Just changed the href After <div class="col-lg-6 position-relative align-self-start order-lg-last order-first"> <img src="{% static 'index_assets/img/about.jpg' %}" class="img-fluid" alt=""> <a href="/login" class="glightbox play-btn"></a> </div> -
How to update User model in Django using signals.py
how can I update the user model first_name and last_name in Django using signals.py when a new user updates first_name and last_name in custom registration form? This is my signals.py for creating a custom separate user details model using Django @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_profile_handler(sender, instance, created, **kwargs): if not created: return profile = models.Profile_user(user=instance, first_name=instance.first_name, last_name=instance.last_name, email=instance.email) profile.save() Now I want to update the settings.AUTH_USER_MODEL when an new user update his first_name and last_name using custom register form -
Bash script gives psycopg2 error: symbol not found in flat namespace (_PQbackendPID)?
I am using Apple M1. Here is the bash script I wrote. #!/bin/sh # Open Activity Tracker website python -m webbrowser http://127.0.0.1:8000/ # Activate virtual environment . dj-env/bin/activate # Navigate to Activity Tracker project folder cd dj_activity_tracker # Run Django local development server python manage.py runserver When I run these commands on my terminal manually without the script, it works. However, when I use this script, I get the error: File "/Users/doge/Desktop/dj-env/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 28, in \<module\> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/doge/Desktop/dj-env/lib/python3.11/site-packages/psycopg2/\_psycopg.cpython-311-darwin.so, 0x0002): symbol not found in flat namespace (\_PQbackendPID) Things I have tried: Uninstall/reinstall psycopg2 brew install postgresql I am stumped on how this is working manually but not when I run the script. What could be the issue? I appreciate your support. -
Django aggregate with joining two table
I am trying to use aggregate with two table Table 1 Sale which is include this field Table 2 saleProduct which has field price and fee Both table has foreign key with field name code I am trying this query to fetch data according to tags sales = Sale.objects.using('read_rep') \ .prefetch_related('sale__product') \ .filter(tags__name__in=['Device','Mobile']).values( 'tags__name' ).annotate( tags_count=Count('tags__name') ).aggregate(price_avg=Avg('price'), total_price=Sum('price')) But it is giving me FieldError: Cannot resolve keyword 'price' into field -
When we deploy our Django app to Heroku it says "changes that are not yet reflected in a migration," but also says it has no migrations to make
My local repo is up-to-date with my Heroku repo. When I run makemigrations or migrate locally, it says there are no changes. When I run makemigrations on Heroku, it does these exact same changes every time, no matter how many times I run it: python manage.py makemigrations users kits email Migrations for 'kits': apps/kits/migrations/0002_auto_20221209_1204.py - Change Meta options on historicalkit - Alter field history_date on historicalkit Migrations for 'users': apps/users/migrations/0002_auto_20221209_1204.py - Change Meta options on historicaluser - Alter field history_date on historicaluser ...but then if I run migrate on Heroku, it says there is nothing to migrate, AND that there are un-made migrations: python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, email, kits, sessions, users Running migrations: No migrations to apply. Your models in app(s): 'kits', 'users' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. This is causing our whole web app to go down. What's going on? -
CORS policy blocks XMLHttpRequest
With Ionic Angular running in on my localhost I made this call to my Django backend (running on different localhost): test() { return this.httpClient.get(endpoint + '/test', { headers: { mode: 'no-cors' }, }); } And on the backend side I have following code to respond: @csrf_exempt def test(request): response = json.dumps({'success': True}) return HttpResponse(response, content_type='application/json', headers={'Access-Control-Allow-Origin': '*'}) I have also this in my settings.py file: INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True Still, I get this error message in my console: Access to XMLHttpRequest at 'http://127.0.0.1:8000/test' from origin 'http://localhost:8100' has been blocked by CORS policy: Request header field mode is not allowed by Access-Control-Allow-Headers in preflight response. What am I doing wrong? Thank you very much for your help! -
How to set file visibility to other users?
Hi im trying to make user upload a file, and then choose to which users this file will be visible .How do i set this one to many relation.This is my models.py file: ` from django.db import models from django.contrib.auth.models import User class UserFile(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to='media/') uploaded = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) trash = models.BooleanField(default=False) favourite = models.BooleanField(default=False) visibilty = models.ManyToManyField(User) ` I tried this but it gives me this error message: managefiles.UserFile.owner: (fields.E304) Reverse accessor 'User.userfile_set' for 'managefiles.UserFile.owner' clashes with reverse accessor for 'managefiles.UserFile.visibility'. HINT: Add or change a related_name argument to the definition for 'managefiles.UserFile.owner' or 'managefiles.UserFile.visibility'. managefiles.UserFile.visibility: (fields.E304) Reverse accessor 'User.userfile_set' for 'managefiles.UserFile.visibility' clashes with reverse accessor for 'managefiles.UserFile.owner'. HINT: Add or change a related_name argument to the definition for 'managefiles.UserFile.visibility' or 'managefiles.UserFile.owner'. -
How to make my SDK file which it serves as a KEY available in my EC2 instance and hide it
I have a running django app which when on server does not find my .json file to access my sdk key. Is there a way to make it available just like you do with string variable ? So far I'v tried this : GOOGLE_APPLICATION_CREDENTIALS = '.env_files/service-account-file.json' which it work locally -
Render django template by specific ID
I'm trying to create a template that renders each model where the id=pk. However i'm wondering can I link to a specific models in in my HTML template. For example, instead of <a href="{% url 'single-supplier' supplier.id %}" could i write something akin to <a href="{% url 'single-supplier' supplier.id=1 %}" The reason i ask this is that I wish to link to a specific id in my navigation bar ` {% load static %} <header> <div class="container"> <!-- Navbar --> <nav id="navbar" class="{% if request.resolver_match.url_name == 'home' %} main-page {% endif %}"> <a href="{% url 'home' %}"><img src="{% static 'images/farmeclogo.png' %}" alt="Logo" id="logo"></a> <ul class="nav-list"> <li class="nav-list-item"><a href="{% url 'home' %}" class="{% if request.resolver_match.url_name == 'home' %} current {% endif %}">Home</a> </li> <li class="nav-list-item"><a href="{% url 'about' %}" class="{% if request.resolver_match.url_name == 'about' %} current {% endif %}">About</a> <ul class="nav-drop"> <li><a href="{% url 'about' %}">Our Team</a></li> <li><a href="{% url 'about' %}">Our Story</a></li> </ul> </li> <li class=" nav-list-item"><a href="{% url 'suppliers' %}" class="{% if request.resolver_match.url_name == 'suppliers' %} current {% endif %}">Suppliers</a> <ul class="nav-drop"> <li> <a href="{% url 'single-supplier' supplier.id %}">SIP Grass Machinery</a> </li> <li> <a href="#">MX Loaders & Front-Linkage</a> </li> <li> <a href="#">Sulky Fertilizer, Harrows & Drills</a> </li> </ul> </li> … -
Django - how to set up a cache in Django template display
I have a queryset which is students and their number: A 2, B 2. Another queryset is teachers and their number: C 2, D 3, E 2. I want to match students and teachers based on their number on the HTML page, and if student A is matched with teacher C already, he won't be with matched with another teacher. It doesn't matter which students matches with which teacher as long as they have a matched number. Something like this: C 2 A D 3 E 2 B The best I can think of is something is like this (of course this code won't work): {% with covered_students = [] %} {% for teacher in teachers %} {{ teacher.name }} {{ teacher.number }} {% for student in students %} {% if student.number == teacher.number and student.name not in covered_students %} {{ student.name }} {% covered_students.append(student.name) %} {% endif %} {% endfor %} {% endfor %} {% endwith %} Thanks in advance!!! -
Django helper function to rename user uploaded image
For a django project I have a model that features an image field. The idea is that the user uploads an image and django renames it according to a chosen pattern before storing it in the media folder. To achieve that I have created a helper class in a separate file utils.py. The class will callable within the upload_to parameter of the django ImageField model. Images should be renamed by concatenating .name and .id properties of the created item. The problem with my solution is that if the image is uploaded upon creating anew the item object, then there is no .id value to use (just yet). So instead of having let's say: banana_12.jpg I get banana_None.jpg. If instead I upload an image on an already existing item object, then the image is renamed correctly. Here is my solution. How can I improve the code to make it work on new item object too? Is there a better way to do this? # utils.py from django.utils.deconstruct import deconstructible import os @deconstructible class RenameImage(object): """Renames a given image according to pattern""" def __call__(self, instance, filename): """Sets the name of an uploaded image""" self.name, self.extension = os.path.splitext(filename) self.folder = instance.__class__.__name__.lower() image_name = … -
how configuration, connect media-directory of django to Capanel host managment?
I want calling pictures or video from media uploaded from users in django project. as well as i want upload piuctures from user and calling in blogs book app. I try this but not work it for me: MEDIA_ROOT = 'home/username/public_html/media -
How to create React JS Slider
Slider component in react. Our slider component is going to be composed of two parts. Slider area where slides will be sliding. Navigation control to change the slides. Let us begin our development by importing all the required packages at the top import React, { Component } from "react"; import styles from "./index.module.css"; import { Transition, animated } from "react-spring/renderprops"; class Carousel extends Component { //Other code will go here } export default Carousel; Check with error. -
Django CoInitialize has not been called
I am trying to automate outlook, using python Django. the code works pretty good directly using python, but when using it in my Django app it gives me this error. > pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) and my views code is : import win32com.client as win32 def about(request): olApp = win32.Dispatch('Outlook.Application') olNS = olApp.GetNameSpace('MAPI') inbox = olNS.GetDefaultFolder(6) messages = inbox.Items for msg in messages: if msg.Class==43: if msg.SenderEmailType=='EX': print(1,msg.Sender.GetExchangeUser().PrimarySmtpAddress) else: print(2, msg.SenderEmailAddress) return render(request,'Home/About.html') So any suggestion to solve this problem? -
Make Inline panel on Django with wagtail
I'm making a pizzeria website and I want to have a few more sizes in the size like dropdown menu, for example 36cm and 40, how can I do this? Im using wagtail 4.1.1 and django 4.1.4 My models.py: class Product(Page): size = models.CharField(max_length=20, null=True) sku = models.CharField(max_length=255) short_description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('sku'), FieldPanel('price'), ImageChooserPanel('image'), FieldPanel('size'), FieldPanel('short_description'), InlinePanel('custom_fields', label='Custom fields'), ] def get_context(self, request): context = super().get_context(request) fields = [] for f in self.custom_fields.get_object_list(): if f.options: f.options_array = f.options.split('|') fields.append(f) else: fields.append(f) context['custom_fields'] = fields return context my admin panel looks like this and my product page: Im trying change from FieldPanel('price') to InlinePanel('price'), but i have a error: AttributeError: 'DeferredAttribute' object has no attribute 'rel' -
Python manage.py dumpdata killed prematurely
I'm migrating a database from MySQL to Postgres. This question has been very helpful. When running the python manage.py dumpdata --exclude contenttypes --indent=4 --natural-foreign > everything_else.json to create a json fixture the connection is aborted by the database server. All other steps have been successful. The MySQL database is hosted on RDS and the connection is aborted at the same point in the file each time I try to run this. Logs from the RDS instance state the problem as follows (db, user and host changed): [Note] Aborted connection 600000 to db: 'mydb' user: 'myUsername' host: '127.0.0.1' (Got an error writing communication packets) In the terminal the message is simply killed. Why would this error be happening and how can I create this json fixture? -
Even if i serve media files with nginx, they don't appear on the website
I am trying to use nginx to put my django app on production. But I cannot use images in the website even though I configured nginx. My nginx server's setup: server { server_name example.com www.example.com; location /static/ { root /home/myusername/myproject/static/; } location /media/ { root /home/myusername/myproject/media/; } location / { proxy_pass http://127.0.0.1:8000; } } My html file: {% extends 'base.html' %} {% block content %} <div class="column"> {% for dweet in dweets %} <div class="box"> {{dweet.body}} <span class="is-small has-text-grey-light"> ({{ dweet.created_at }} από {{ dweet.user.username }}) </span> <figure> <img class="is-rounded" src="/media/{{dweet.image}}" alt="connect" style="max-height:300px"> </figure> </div> {% endfor %} </div> {% endblock content %} I have played around with directory paths, but still nothing.