Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DateField Django default does not apply to database:
When doing the basic models on my django app, I have encountered this issue: The model for a Product stands like this in my app: main_color = models.CharField(max_length=15) secondary_color = models.CharField(max_length=15) brand = models.CharField(max_length=30) catalog_inclusion_date = models.DateTimeField(default=datetime.now, blank=True) image_url = models.URLField(max_length=200) description = models.TextField() But the catalog_inclusion_date isn't working as intended. After migrating the models to the MySQL database and attempting to insert an entry on the table with this SQL sentence: INSERT INTO shoppingcart_cap(main_color, secondary_color, catalog_inclusion_date, brand, image_url, description, logo_color) VALUES ('Red', 'Black', 'Adidas', 'https://www.rekordsport.es/uploads/photo/image/4920/gallery_A02506_1.JPG', 'Kid cap', 'White') I get the following output: ERROR 1364 (HY000): Field 'catalog_inclusion_date' doesn't have a default value Thanks in advance. Edit: In MySQL, after doing DESCRIBE cap_table;, I get the following output: CREATE TABLE `shoppingcart_cap` ( `id` bigint NOT NULL AUTO_INCREMENT, `main_color` varchar(15) NOT NULL, `secondary_color` varchar(15) NOT NULL, `brand` varchar(30) NOT NULL, `catalog_inclusion_date` date NOT NULL, `image_url` varchar(200) NOT NULL, `description` longtext NOT NULL, `logo_color` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) -
AttributeError: transform not found in Countvectorizer , using sklearn
Trying to load my spam text detection Machine Learning model in API using Django framework. My error when sending request with text:"Ahmed,,, Awwad.. Test" File "path/to/API.py", line 39, in predict_text vector = selector.transform(clean_text) File "/usr/lib/python3/dist-packages/scipy/sparse/base.py", line 687, in __getattr__ raise AttributeError(attr + " not found") AttributeError: transform not found [30/Jun/2022 00:11:23] "POST /api/spamurai HTTP/1.1" 500 103644 This my model: #convert a collection of text to amatrix of tokens (Bag of words) from sklearn.feature_extraction.text import CountVectorizer from joblib import dump import pickle #process_text previously defined function to preprocess text in model msg_vector= CountVectorizer(analyzer=process_text) message_bow = msg_vector.fit_transform(df['text']) pickle.dump(message_bow, open("vector_text.pkl", "wb")) dump(MultinomialNB,'spam_model_text.joblib') I was using joblib in both dumping but i got many errors with countervectorizer and joblib so i am trying pickle and joblib In my API.py file I load my text vector and MultinomialNB file as follows: from joblib import load from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer MultinomialNB_file = os.path.join(BASE_DIR, 'tutorials/data', 'spam_model_text.joblib') CountVectorize_file = os.path.join(BASE_DIR, 'tutorials/data','vector_text.pkl') txt_model = load(MultinomialNB_file) selector = pickle.load(open(CountVectorize_file, "rb")) # # pre processing email text to be used in ML Model without affecting accuracy of model def process_text(text): #processing_code return clean_text # # function uses trainig utilities used in TEXT ML Model def predict_text(text): # … -
if statement for a specific field in django template
I'm rendering a form in a django template using this model: class Group(models.Model): name = models.CharField(max_length=100) description = models.TextField() members = models.IntegerField(default=0) has_max = models.BooleanField(default=False) max_size = models.IntegerField(default=10) DAYS = [ ('Sundays', 'Sundays'), ('Mondays', 'Mondays'), ('Tuesdays', 'Tuesdays'), ('Wednesdays', 'Wednesdays'), ('Thursdays', 'Thursdays'), ('Fridays', 'Fridays'), ('Saturdays', 'Saturdays'), ] meeting_day = MultiSelectField( verbose_name = 'Meeting day(s)', choices=DAYS, max_choices=6, max_length=100 ) start_time = TimeField(widget=TimePickerInput) end_time = TimeField(widget=TimePickerInput) def __str__(self): return self.name And onto this template: <form method="POST"> {% csrf_token %} {{form.as_p}} <button>POST</button> </form> I have a couple of issues going forward: My first issue is that I only want to have max_size be displayed in my template form if the user clicks has_max. Like a conditional, where once the user checks the box, changing has_max to True then they can enter in the max size of the group. My second issue is that the start_time and end_time to render in my template or on the admin side. I'm not sure how TimePickerInput works, but right now, there are no fields in my template form or admin form that have those time fields. Also, last thing, if I have both names the exact same (i.e., ('Sundays', 'Sundays'), is it necessary to have both? Or can … -
How to adjust the Django PymemcacheCache limit to be over 1MB
A similar question was posted here regarding adjusting the 1mb limit of memcached storage in Django settings. However, the answer was referring to django.core.cache.backends.memcached.MemcacheCache, which has since been deprecated. I tried implementing to provided solution with the django.core.cache.backends.memcached.PyMemcacheCache backend but the provided OPTIONS ('server_max_value_length') is unrecognizable. I can't find the available list of Options for the newer PyMemcache backend from django (at least not any that allow me to adjust the storage limit. My Settings looks like this: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': 'cache:11211', 'OPTIONS': { 'server_max_value_length': 1024*1024*10 } } } I am deploying the app in a Python 3 Docker image with a docker-config.yml configuration. The config file relative to memcached looks like: cache: image: memcached ports: - "11211:11211" entrypoint: - memcached - -m 64 - -I 10m When caching views that return JSON Responses with < 1MB data, the caching works great and greatly improves speed. The main objective here is to speed up response times. As far as optimizing the query, its just a simple GET that filters off the authenticated users company. I think pagination would help speed up response time as well, seeing as this is a large list of data being … -
cant get CORS enabled on app inside django
I pip installed django-cors-headers it works on my base application, but wont work on my "rest_api" app. Access to fetch at 'http://localhost:8000/api/groups' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Settings: INSTALLED_APPS = [ 'rest_framework', 'corsheaders', 'rest_api', '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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] -
How to add the entry, which has foreign key, from frontend having only the pk of fk
Probably not the best heading, but I will try my best to explain the question. I have two models set up in my Django app: class Category(models.Model): class Meta: verbose_name_plural = "Categories" name = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + " | " + str(self.author) def get_absolute_url(self): return reverse('post-details', args=(str(self.id))) with respective serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name'] class CategorySerializer(ModelSerializer): class Meta: model = Category fields = ['id', 'name'] class PostSerializer(ModelSerializer): category = CategorySerializer() author = UserSerializer() class Meta: model = Post fields = ['id', 'title', 'author', 'category', 'body', 'post_date'] and a default ViewSet for Post: from rest_framework.viewsets import ModelViewSet class PostViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all().order_by('-post_date') I want to add a new entry by sending an axios POST request to my Django app from the Vue frontend and I would like to do it in such way: const formData = { title: this.title, category: this.category, body: this.body, author: this.$store.state.user_id, } axios({ method: "POST", url: '/api/blog/posts/', headers: {"Content-Type": "application/json"}, data: formData }) .then(response => … -
how can I transform this sql query for use in Django?
SELECT fija.id, concat(fija.nombres," ", fija.apellido1, " ", fija.apellido2) as Nombre, fija.rfc, fija.telefono, fija.fecha_inicio, puesto.puesto, puesto.codigo, group_concat(decl.id) as declaraciones FROM declaracionesSiDeclara.declaracion_infopersonalfija as fija INNER JOIN declaracionesSiDeclara.declaracion_catpuestos as puesto on puesto.id = fija.cat_puestos_id LEFT JOIN declaracionesSiDeclara.declaracion_declaraciones as decl on decl.info_personal_fija_id = fija.id group by fija.id; -
Django 'memoryview' object has no attribute '_committed'
I am writing app for students project and encountered problem when saving modified model object Model: class Appointments(models.Model): id = models.IntegerField(primary_key=True) patient_pesel = models.ForeignKey('Patients', models.DO_NOTHING, db_column='patient_pesel') appointment_date = models.DateTimeField(blank=True, null=True) department = models.ForeignKey('Departments', models.DO_NOTHING, db_column='department') room = models.ForeignKey('Rooms', models.DO_NOTHING, db_column='room', blank=True, null=True) doctor = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='doctor', blank=True, null=True) appointment_type = models.ForeignKey('DAppointmentType', models.DO_NOTHING, db_column='appointment_type') suggested_date = models.DateField() referral = models.FileField(upload_to='referrals', blank=True, null=True) nfz = models.BooleanField() recommendations = models.TextField(blank=True, null=True) accepted_at = models.DateTimeField(blank=True, null=True) accepted_by = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='accepted_by', blank=True, null=True, related_name='accepted_HospitalStaff') updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) updated_by = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='updated_by', blank=True, null=True, related_name='updated_HospitalStaff') class Meta: managed = True db_table = 'appointments' View: def staff_accept_single_appointment_2(request): app_id = request.POST.get("appointment_id") date = request.POST.get("app_date") time = request.POST.get("app_hour") doctor = request.POST.get("doctor") room = request.POST.get("room") date_time_obj = datetime.strptime((str(date)+' '+str(time)).replace('-','/'), '%Y/%m/%d %H:%M') doctor_object = HospitalStaff.objects.get(id=doctor) room_object = Rooms.objects.get(room_name=room) app_object = Appointments.objects.get(id=app_id) app_object.appointment_date=date_time_obj app_object.doctor=doctor_object app_object.room=room_object app_object.save() return HttpResponseRedirect('/staff/registration/accept_appointments/accept_single_appointment') also checked much simpler version of view: def staff_accept_single_appointment_2(request): app_object = Appointments.objects.get(id=1) app_object.save() and i am still encountering 'memoryview' object has no attribute '_committed' error and can not go around it. Tried also using objects.filter().update() . It does not throws an error, but it does not affect database eighter. Tried searching solutions, maybe it is connected with FileField in … -
In Django Tables2, how do you make a column show text from a table referenced by a foreign key?
After reading all the docs and answers I can find, and burning a whole day, I still can't make this work. Using Django Tables2, I want to show a list of instruments; the instruments table includes a foreign key to an instrumentsType table. When I list the instruments and their attributes, I want to use the foreign key to substitute the textual instrument type description from the other table. I have tried every combination of double underscores and other accessor techniques, but so far all I get is the dreaded -- in the column. (Displaying just the record ID works). from .models import Instrument from django_tables2 import A from instrumenttypes.models import InstrumentType class InstrumentTable(tables.Table): id = tables.LinkColumn('instrument_details', args=[A('station_id')]) class Meta: model = Instrument template_name = "django_tables2/bootstrap.html" fields = ("id", "instrument", "nickname", "serialNo", "instrument__instrumenttype_id__instrumenttypes__id_instrumentType" ) The models involved are: Instruments model.py from django.db import models from instrumenttypes.models import InstrumentType from stations.models import Station # Create your models here. class Instrument(models.Model): instrument = models.CharField(max_length=40) instrumenttype = models.ForeignKey(InstrumentType, on_delete=models.CASCADE, null=True) station = models.ForeignKey(Station, on_delete=models.CASCADE, default=1) serialNo = models.CharField(max_length=60, null=True, blank=True) dateAdded = models.DateTimeField("Date Added", null=True, blank=True) dateRemoved = models.DateTimeField("Date Removed", null=True, blank=True) status = models.CharField(max_length=10, null=True, blank=True) nickname = models.CharField(max_length=40, null=True, blank=True) InstrumentTypes … -
Sum of column values inside Json array with group by
I have next Django model. class StocksHistory(models.Model): wh_data = models.JsonField() created_at = models.DateTimeField() I store JSON data in wh_data. [ { "id":4124124, "stocks":[ { "wh":507, "qty":2 }, { "wh":2737, "qty":1 } ], }, { "id":746457457, "stocks":[ { "wh":507, "qty":3 } ] } ] Note: it's data for one row - 2022-06-06. I need to calculate the sum inside stocks by grouping them by wh and by created_at so that the output is something like this [ { "wh":507, "qty":5, "created_at":"2022-06-06" }, { "wh":2737, "qty":1, "created_at":"2022-06-06" }, { "wh":507, "qty":0, "created_at":"2022-06-07" }, { "wh":2737, "qty":2, "created_at":"2022-06-07" } ] I know how to group by date, but I don't understand how to proceed with aggregations inside JsonField. StocksHistory.objects.extra(select={'day': 'date( created_at )'}) .values('day') .annotate( ??? ) A solution is suitable, both through Django ORM and through RAW SQL. -
Django admin - create user without set password
I need to set the admin user creation to let register an user but without request the password. password1 and password2 fields are required in admin forms. does anybody know how to achieve it? thanks! -
Django built in filter truncatewords ,how to get the left words?
I have a string named message equals to "Hello word how are you", In the Django template if I use: <div>{{message|truncatechars:2 }}</div> Then I will have: <div>Hello word</div> My question is except using {{message|slice:'11:'}},is there anyway I can get the rest words in message by using truncatechars or other django buit in template ? the output need be : how are you -
Toggle is_superuser in django admin
How to toggle a boolean field is_superuser in the django admin panel which enables a user to become superuser? I am using AbstractUser for my user model. -
Google Analytics Measurement Id as Environment Variable
I just started using Google Analytics and I have my code in my base html file for a Django web app. <!-- Global site tag (gtag.js) - Google Analytics --> <script nonce="{{ CSP_NONCE }}" async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX"></script> <script nonce="{{ CSP_NONCE }}"> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag("config","G-XXXXXXXXX"); </script> <!-- end GA --> My question is, for the measurement id (G-XXXXXXXXX) is this something that needs to be a secret? I keep all my keys, etc in the env file and though I could do the same with this id but I keep running into errors. I tried {% 'GOOGLE_ID' %} but that didn't work. Is there a good way to implement this? -
How to count the total non-distinct many-to-many relationships across objects of a model?
Assume I have the following models: class Tag(Model): name = CharField() class Book(Model): title = CharField() tags = ManyToManyField(Tag) Now suppose I have 3 books, and each book has 3 tags. Some of the tags might be the same for some of the books, it doesn't matter. Book 1 (Tags = "tag1", "tag2", "tag3") Book 2 (Tags = "tag1", "tag4", "tag5") Book 3 (Tags = "tag4", "tag5", "tag6") How can I count all non-distinct tags in a Django ORM query so that I get 9 as a result? -
How to run a backend script on Django from html page
I'm trying to process apple pay payments on my Django site. While I understand that this is better off in the back end, I currently am running the scripts in a JS static file, which means that that info is public. How can I set up my project to run a back-end python script when the apple pay button is clicked? Please discuss file organization in your answer. (For simplicity, you can just assume I am trying to run a script that loads another website instead of going through the whole apple pay process.) I came across this resource and it looked like it could be along the right track, but I think it might be overcomplicating things. https://github.com/Jason-Oleana/How-to-run-a-python-script-by-clicking-on-an-html-button -
Is there a method to pass react sessionStorage data to django rest framework backend?
I have a variable named hostwhich stores a session id for a user who visits my site. The variable is stored in sessionStorage of my react frontend. Is there a way of passing this variable to my backend without having to fetch for an API view root from the backend? -
Django is not fetching another app static file but fetching the main app static file?
Django is fetching the main app static files but it is not fetching the other app static files how to solve it ?? Error in CC is: Main File : Html Link Of CC : Main html link : Folder structure : -
Django Rest Framework authentication with Custom User Model
I have multiple types of user in my django app: Employee and Patient. They have fields that are specific to each of them. They are implemented using the AbstractBaseUser model as below: from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) USERNAME_FIELD = 'identifier' first_name = models.CharField( max_length=50, null=False, blank=False) last_name = models.CharField( max_length=50, null=False, blank=False) date_of_birth = models.DateField(null=False, blank=False) USER_TYPE_CHOICES = ( (1, 'Patient'), (2, 'Employee'), ) user_type = models.PositiveSmallIntegerField( choices=USER_TYPE_CHOICES, default=1, blank=False, null=False) class Role(models.Model): RoleName = models.CharField(max_length=50, null=False, blank=False) class Employee(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) employment_start_date = models.DateField(null=False, blank=True) employment_end_date = models.DateField(null=False, blank=True) role = models.ForeignKey( Role, on_delete=models.CASCADE, related_name='assigned_employees') class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) I have a few questions with how to go forward with this: How does just the choice in the User class limit the fields that a user has access to? If I had a HTML page would I create an Employee then a User would be created, or the other way round? When I'm using Django Rest Framework, how can I implement a sign up and log in with the two different types? I'm struggling to understand how this would work conceptually. Is … -
Integrating chainable animation image gallery code into Django project
I'm building a website using Django and I want to add this image gallery to one of my pages, but I'm having issues integrating the code. The HTML, CSS, and JS code I want to add is here: https://gist.github.com/CodeMyUI/9769b75c7a81d24138ae74bdbadc39e4 I've added the JS (inside a <script> element) and HTML to my django template, and added the CSS to my project's style.css file, but when I try to render, I'm getting a console error: Uncaught TypeError: Cannot read properties of null (reading 'classList') I also don't see anywhere in the code snippets that points to the images that I want to use for the gallery. Help on what I'm missing to successfully integrate this cool image gallery would be appreciated. -
Migrating sqlite to mysql using Django
I’m new to Django and web servers, and have been stuck for a few days. I inherited a Django app, python version 2.7 and Django version 1.9. The app was previously using the default SQLite databases. I want to migrate to Mysql for performance reasons. I loaded the data into the sqlite db using reset_db I installed mysqlclient I created a mysql db I created a username and password for a user and granted all permissions I dumped the data into a file called dump.json using python manage.py dumpdata > dump.json I changed the settings file to use django.db.backends.mysql I tried to load data using python manage.py loaddata and with makemigrations, migrate, it fails with the following error (with ANY manage.py command): (eKichabiTest) ananditharaghunath@Anandithas-MacBook-Pro db-test % python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 398, in execute self.check() File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver … -
Order of operations in Django Templates
I'm trying to call a dictionary named test with a key 'example' corresponding to a value 'OK'. I am trying to call it inside of a Django template, i.e. {{test.example}}. The problem is that I want to call this dynamically, so I pass an object and it has an ID of 'example' -> {{test.(object.id)}}. How do I go about this? -
Command Cancelled! on running orator migrate command in django
When I'm running the orator migrate command then giving Command Cancelled! I have installed orator in Django Orator: 0.9 Python: 3.9.7 django: 4.0.5 I create created a migration and model that you can see my code and set the connection but when I'm running migrate command then comming Command Cancelled! db connection orator.py from orator import DatabaseManager import environ env = environ.Env() environ.Env.read_env() config = { 'mysql': { 'driver': 'mysql', 'host': 'localhost', 'database': env('DB_DATABASE'), 'user': env('DB_USERNAME'), 'password': env('DB_PASSWORD'), 'prefix': '' } } db = DatabaseManager(config) migration file from orator.migrations import Migration class CreateProductsable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('products') as table: table.increments('id') table.integer('category_id').unsigned() table.timestamps() table.foreign('category_id').references('id').on('jobs').on_delete('cascade') def down(self): """ Revert the migrations. """ self.schema.drop('products') model file from orator import Model class Product(Model): __table__ = 'products' -
What is this format? (similar to JSON)
I'm getting info from an API (Google Ads API) that looks like this on the browser: customer { resource_name: "customers/XXX" id: XXX } campaign { resource_name: "customers/XXX/campaigns/XXX" status: ENABLED name: "XXX" id: XXX } metrics { impressions: 0 } The source code looks like this: customer { resource_name: "customers/XXX" id: XXX } campaign { resource_name: "customers/XXX/campaigns/XXX" status: ENABLED name: "XXX" id: XXX } metrics { impressions: 0 } I guess this is similar to JSON, but not exactly. Is it a know-format or just random code? I want to turn this data into an HTML table (using Python/Django) and I'm not sure if I can use JSON solutions/libraries (or similar ones) or if I need to create my own custom solution. Thanks! -
Transform VB6 Applications to dual-platform using python
This is my first time asking here, just to be clear I don't want any code or anyone to make something for me, I'm searching for a solution, so I can start building what I want. I searched a lot but didn't find the answer. In our company we have an OLD "Legacy" VB6 application, and if we have a new employee we need to install and do multiple things to make this application work. I found a program called "Thinfinity" that take the application and sorta make it work like a web application and you can access it through an IP address. What I'm searching for here, Is there a way to make the same concept using Python? Again, I don't want someone to make it for me, I just want someone to put me in the right/correct direction to do it Excuse my English & Thanks in Advance