Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'wtools2'
I am trying to run my Django Application, getting following error when using this command Line. python manage.py runserver Error (venv) F:\ATSG\FrontEnd\wtoolgui\wtools2>python manage.py runserver Traceback (most recent call last): File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Muhammad Usman\.pyenv\pyenv-win\versions\3.10.0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'wtools2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\ATSG\FrontEnd\wtoolgui\wtools2\manage.py", line 47, in <module> execute_from_command_line(sys.argv) File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "F:\ATSG\FrontEnd\wtoolgui\venv\lib\site-packages\django\core\management\base.py", line 367, in run_from_argv connections.close_all() File … -
how to solved django OperationalError - attempt to write a readonly database?
I have Django web in linux(digitalocean), and use sqlite3. I have three users sqlite3. When I use: python3 manage.py runserver 0.0.0.0:8000 --> everything is good. But When I use: sudo systemctl restart apache2 --> when I open user login page and when logging, I receive error: attempt to write a readonly database. I tried: sudo chmod a+w db.sqlite3 chown apache:apache db.sqlite3 Folder structure: -myproject --projectenv --myapp ----myapp ----firstapp ----manage.py ----db.sqlite3 -
Is there a way to dynamically select schema to execute SQL queries in Django?
I have a Django app which have a model that stores SQL queries that should be executed on another one of the multiple databases. There is also a column called schema in that model which is used to store the schema where the query is to be executed. class Query(BaseModel): STATUS_CHOICES = [ ('active', 'Active'), ('inactive', 'Inactive'), ] name = models.CharField(max_length=100) syntax = models.TextField() description = models.TextField() group = models.ForeignKey(Group, on_delete=models.DO_NOTHING) schema = models.CharField(max_length=20) database = models.CharField(max_length=20) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='active') extras = models.TextField() How do I execute this raw SQL query stored in that model in the schema name that's stored in the same record. There could be different sql queries with different schemas too. Everytime the query is executed, it should dynamically take the schema from the record and run it in the database. I know we can use the .using() in the ORM to specify the database to run the query on. Is there any such similar thing to specify schema? -
I can't import modules from my own project
I'm trying to import the ApiRequest class that I created from my project_datafit.utils but it's not working, I created a folder called "venv" inside my python folder and in it I created the virtual environment "Ambiente_datafit" I already downloaded all my libraries and I already configured vs code to use the python interpreter from "ambiente_datafit", before the other imports weren't working either, but after I fixed the interpreter they worked, now only the imports that I get from my own project like utils or My models are not going and keep saying could not be resolved, what do I do? (https://i.stack.imgur.com/ngQnc.png) It seems that Python doesn't recognize my files, what should I do? -
django makemigrations ModuleNotFoundError: No module named 'django.Falsedb'
I am learning to use Django, and when trying to install Crispy Forms and running 'makemigrations,' I encounter the following error: Traceback (most recent call last): File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/db/models/options.py", line 275, in _get_default_pk_class pk_class = import_string(pk_class_path) File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/utils/module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/utils/module_loading.py", line 15, in cached_import module = import_module(module_path) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.Falsedb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/javier/Desktop/pd110/src/manage.py", line 22, in <module> main() File "/home/javier/Desktop/pd110/src/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 156, in handle loader.check_consistent_history(connection) File "/home/javier/Desktop/pd110/lib/python3.10/site-packages/django/db/migrations/loader.py", line 313, … -
Django filter name__icontains not working
I have some model with name field as: name = models.CharField(max_length=255, verbose_name='Name', db_index=True) I want to filter my records by some string WITHOUT REGISTERING, for example a record with name "Apple" should be found by the strings "Apple", "apple", "aPPle", "ApPpLe" and so on. I use: results = Page.objects.filter(name__icontains=query) But it doesn't work. Various combinations like: results = Page.objects.filter(Q(name__iexact=query) | Q(name__icontains=query)) or results = Page.objects.filter(name__iexact=query) Not working.The search is always case-sensitive. How to fix this? I am using Django 4.2.6 and Postgresql 14.9 on Mac m1 on Mac OS Ventura 13.4.1. I want to filter my records by some string WITHOUT REGISTERING, for example a record with name "Apple" should be found by the strings "Apple", "apple", "aPPle", "ApPpLe" and so on. -
how to make auth with react and django in spa app
im using this article https://testdriven.io/blog/django-spa-auth/ but woww all of this is confusing tbh. im using react and react router but i tried both second way and still it didnt work my question isnt really about how to fix this since i feel like its wrong because your reinventing the wheel and you should use 3rd party app can someone tell me what im supposed to do btw if you still think this is a good solution from the article ill show you my github rep so if you wanna se whats wrong https://github.com/MicheleAwada/blog (this is because they asked me and stuff) i tried finding a third party app. but i didnt find it. i thought the spa auth would work but i got a csrf cookie not set error -
MultiValueDictKeyError at /buyer/register/ end in post and put requests Django rest framework on pythonanywhere
I am a beginner to django, I created eCommerceAPI as a project. The project features CRUD API designed to perform operations like user registration, user login, product management etc. for an ECommerce shopping website. The application is working fine on my local but I am having issues during post and put request on after deploying it on pythonanywhere.com. @api_view(['POST']) def register(request): name = request.data['name'] email = request.data['email'] password = request.data['password'] address = request.data['address'] try: cursor = connection.cursor() cursor.execute('''INSERT into buyer (name, email, password, address) values("''' + name + '", "' + email + '", "' + password + '", "' + address + '")') return Response({"Message": "Registration sucessfull."}) except db.OperationalError as e: return Response(list({'Error': e}), status = 400) except db.Error as e: return Response(list({'Error': e}), status = 400) except: return Response({'Error': 'Invalid Parameter'}, status = 400) Complete Traceback enter image description here The application is working fine on my local again, can anyone point out the problem here with pythonanywhere.com ?? I tried changing name = request.data['name'] to: name = request.POST['name'] name = request.POST.get('name') after surfing about the issue here and there but none of them worked for me. You can access the live project here: Click here Github link … -
Hello Everyone I am Trying to create Cash Payments Getaway in Django
hello everyone i am trying to create a function in django to create cash payment and i can't did this and user fille order form and choice case payment and order will send successful please help me!!!! Models.py from django.db import models from accounts.models import Account from store.models import Product, Variation # Create your views here. class Payment(models.Model): PAYMENT_METHOD_CHOICES = ( ('cash', 'Cash'), ('online', 'Online'), ) user = models.ForeignKey(Account, on_delete=models.CASCADE) payment_id = models.CharField(max_length=100) payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES) amount_paid = models.CharField(max_length=100) status = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.payment_id def __str__(self): return f'{self.payment_method} - {self.amount}' class Order(models.Model): STATUS = { ('New', 'New'), ('Accepted', 'Accepted'), ('Completed', 'Completed'), ('Cencelled', 'Cencelled'), } user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True ) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) order_number = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50) phone_number = models.CharField(max_length=50) address_line_1 = models.CharField(max_length=50) address_line_2 = models.CharField(max_length=50, blank=True) city = models.CharField(max_length=50) pin_code = models.CharField(max_length=50) state = models.CharField(max_length=50) country = models.CharField(max_length=50) # shope_image = models.ImageField(upload_to='photos/Shope_images') order_note = models.CharField(max_length=50) order_total = models.FloatField() # gst = models.FloatField() status = models.CharField(max_length=50, choices=STATUS, default='New') ip = models.CharField(blank=True, max_length=50) is_ordered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def full_name(self): return f'{self.first_name} {self.last_name}' def full_address(self): return f'{self.address_line_1} {self.address_line_2}' def add_multiple_orders(user, … -
Django with Cyberpanel deployment - Internal Server Error(500)
I'm trying to deploy the Django App in vps with the Ubuntu and Cyberpanel. But i can see the demo project with the domain URL. But with my project i'm ony getting the Internal Server error. ├── db.sqlite3 └── myproject ├── __init__.py ├── __init__.pyc ├── manage.py ├── media │ ├── assets │ ├── css │ ├── fonts │ ├── images │ ├── js │ └── video ├── requirements.txt ├── myproject_app │ ├── admin.py │ ├── apps.py │ ├── app_util_mail.py │ ├── app_util_mail.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── views.py │ └── views.pyc ├── settings.py ├── settings.pyc ├── urls.py ├── urls.pyc ├── wsgi.py └── wsgi.pyc and this is the lite speed context file context / { type appserver location /home/test.com/public_html/my-demo binPath /usr/local/lsws/fcgi-bin/lswsgi appType wsgi startupFile myproject/wsgi.py envType 1 env LS_PYTHONBIN=/home/test.com/public_html/bin/python2.7 env PYTHONHOME=/home/test.com/public_html/ } All i'm getting is that the internal server error. But i will only run my project with the python2 manage.py runserver & gunicorn wsgi without the app name. When i tried to run the project with the app name. It shows the error as unknown command. -
Apply Django REST JWT on admin panel
In Dajngo service, i use Simple JWT. It works great with frontend server except for one problem... When I am logged into the admin panel, the frontend authentication with JWT is not working properly. As far as I understand, this is due to the fact that the admin panel works using sessions (which it stores in cookies) rather than JWT tokens. Is there any way to connect JWT authorization to the admin panel? -
Django 3.2 REST API : Postgressql video upload fails
I'm attempting to upload a video of 32 MB in 2k resolution to my backend django 3.2 rest api with postgres-sql as my database engine deployed on GCP ubuntu with v2 cpus and 8 Gb memory. My front end flutter app crashes with a buffer pool eviction error. I focussed on the frontend for the past few hours. However upon inspecting the docker-compose logs just to rule out any backend issue, I get the following just before it fails on the front end : video-project-postgresql-db | 2023-11-01 12:44:56.708 UTC [27] LOG: checkpoint complete: wrote 79 buffers (0.5%); 0 WAL file(s) added, 0 removed, 0 recycled; write=7.636 s, sync=0.007 s, total=7.654 s; sync files=48, longest=0.002 s, average=0.001 s; distance=301 kB, estimate=301 kB; lsn=0/21C93A0, redo lsn=0/21C9368 Need to understand what this means. Help appreciated. -
In a mysql-django-axios-react setup.... how to update a column in the db using its own value
Long time listener, first time caller.... learned so much from the forum and its community and many thanks to the platform and the community. Hopefully can get my skills up to contribute. Have a Mysql - Django - Axios - React setup. I can use Axios PATCH easy enough in react to issue an update through Django RFW to update a column in the db. But I'm stuck on how to update the column using the existing value in the column. For example in db language: table.column1=table.column1+x I tried a few things like passing a string as the data object but get a 400/bad request/"column requires an integer value" error from django RFW. Rookie mistake with db background... Last thing I tried was using the django F() expression to construct the data object to pass through axios.patch, and although no errors and get status 200 back from django, nothing happens, no update to the column. const col = (column1=F('column1')+${x}) axios.patch(localhost:8000/Model/${id},col) When I look at the browser console/network traffic I see FormData that is getting passed from axios to django as: (column1: F('column1') 9) /* 9=x */ Which is why I'm guessing nothing happens without the "+" Obviously I could axios.fetch, … -
is there any way to make possible the post request in my django and react project?
the frontend code is `import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import Select from "react-select"; function AddDetails() { const [formData, setFormData] = useState({ first_name: '', last_name: '', mobile_number: '', services: [], years_of_experience: '', license_certificate: null, min_charge: '', charge_after_one_hour: '', street_name: '', house_number: '', ward: '', panchayath_municipality_corporation: '', taluk: '', district: '', state: '', country: '', }); const [services, setServices] = useState([]); const [selectedServices, setSelectedServices] = useState([]); useEffect(() => { // Fetch the list of services from the Django backend axios .get('http://127.0.0.1:8000/services/') .then((response) => { setServices(response.data.results); }) .catch((error) => { console.error(error); }); }, []); const handleChange = (e) => { const { name, value } = e.target; if (name === 'services') { const selectedServices = Array.from(e.target.selectedOptions, (option) => option.value ); console.log('Selected Services:', selectedServices); setFormData({ ...formData, services: selectedServices, }); } else { setFormData({ ...formData, [name]: value, }); } }; const serviceOptions = services.map((service) => ({ value: service.id, label: service.Title, })); const handleSelectChange = (selectedOptions) => { setSelectedServices(selectedOptions); const selectedServiceIds = selectedOptions.map((option) => option.value); setFormData({ ...formData, services: selectedServiceIds, }); }; const handleFileChange = (e) => { const file = e.target.files[0]; if (file) { const reader = new FileReader(); reader.onload … -
How to get FCM_SERVER_KEY in Django 2023.11
I got firebase json file then want to get FCM_SERVER_KEY FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "wbhsfvbyewfuibwerugbjdsnugvbrfdfhbvjhbsdufhgvgtfhghuyhyuljhblkjhbliukjhiubbhfuvbkhersbfvcuhefhyuer" } I am expecting answers with pictures -
Django 4.2.6: Installing Different Admin Templates for Different Custom Admin Sites
I'm facing an issue while trying to install different admin templates for different custom admin sites in Django. Specifically, I want to use the default django.contrib.admin template for the default admin site and enable django-jet-reboot for a custom admin site. The problem I'm encountering is that when I install django-jet-reboot, it gets enabled for all admin sites, including the default one. Could someone please guide me on how to correctly install and apply different admin templates for distinct custom admin sites in Django? Thank you in advance for your assistance! I have tried to write a custom djanto template loader that reads a field from the settings: The following is a configuration that assiciate a given admin site with a corresponding template #settings.py ............. ADMIN_TEMPLATE_ASSOCIATION = { 'admin': { "template": "django.*", "exclude_templates": [ 'jet.*', 'jet.forms', 'jet.dashboard', ] }, 'first_admin': { "template": "jet.*", "exclude_templates": [ ] }, } .............. """ Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. """ #myapp.loader.py from pathlib import Path import re from django.template.utils import get_app_template_dirs from .filesystem import Loader as FilesystemLoader """ Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. """ from django.template.utils import get_app_template_dirs from .filesystem import Loader as FilesystemLoader from … -
how to set dynamically summernote value on dropdown change using jquery?
models.py class Other(models.Model): desc = models.TextField(default=None) create_by = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) form.py class OtherForm(forms.ModelForm): class Meta: model = Other fields = "__all__" exclude = ['create_by','create_at','update_at'] widgets = { 'desc':SummernoteWidget(attrs={'summernote': {'width': '100%', 'height': '400px'}}), } index.html <div class="card-body"> <label for="">Templates</label> <select class="form-control form-control-sm form-select" name="template" id="id_template"> <option value="">--</option> {% for i in data %} <option value="{{i.id}}">{{i.name}}</option> {% endfor %} </select> <form method="post" action=""> {% csrf_token %} {{form}} <div class="row"> <div class="col-6"> <button type="submit" class="btn btn-soft-primary">{{btn_type}}</button> <a href="{% url tree_url %}" class="btn btn-soft-gray">Bank</a> </div> </div> </form> </div> Js.file $('#id_template').change(function () { var id_template = $("#id_template").val() $.ajax({ type:'GET', url:'{% url "templates_find" %}', data:{id_template:id_template}, success:function (data, status) { var h_content = data.t_data console.log(h_content) } }); When I'm change dropdown jQuery ajax call and get right template value but can't set on summernote editor I have try using this $('.summernote').summernote('code', data.message); but still not working please guide. -
Improving Deployment Time for Django Project on Azure Web App
I have a Django project deployed on an Azure Web App (Linux, P2v2, Python 3.10, Django 4.2), which is functioning as expected. However, the deployment time is extremely slow, taking between 15 to 20 minutes to complete even a small change in the code. This is significantly longer than the deployment times I have experienced with other services. Here is a snippet of the deployment log: 2023-10-31T12:50:59.953Z - Updating branch 'master'. 2023-10-31T12:51:04.983Z - Updating submodules. 2023-10-31T12:51:05.086Z - Preparing deployment for commit id 'XXXXXXXXX'. 2023-10-31T12:51:05.338Z - PreDeployment: context.CleanOutputPath False 2023-10-31T12:51:05.432Z - PreDeployment: context.OutputPath /home/site/wwwroot 2023-10-31T12:51:05.535Z - Repository path is /home/site/repository 2023-10-31T12:51:05.638Z - Running oryx build... 2023-10-31T12:51:05.644Z - Command: oryx build /home/site/repository -o /home/site/wwwroot --platform python --platform-version 3.10 -p virtualenv_name=antenv --log-file /tmp/build-debug.log -i /tmp/8dbda100b9921ec --compress-destination-dir | tee /tmp/oryx-build.log 2023-10-31T12:51:06.599Z - Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx 2023-10-31T12:51:06.614Z - You can report issues at https://github.com/Microsoft/Oryx/issues 2023-10-31T12:51:06.643Z - Oryx Version: 0.2.20230508.1, Commit: 7fe2bf39b357dd68572b438a85ca50b5ecfb4592, ReleaseTagName: 20230508.1 2023-10-31T12:51:06.658Z - Build Operation ID: 10aafab84d551a74 2023-10-31T12:51:06.664Z - Repository Commit : XXXXXXXXXXXXXX 2023-10-31T12:51:06.670Z - OS Type : bullseye 2023-10-31T12:51:06.677Z - Image Type : githubactions 2023-10-31T12:51:06.695Z - Detecting platforms... 2023-10-31T12:51:15.575Z - Detected following platforms: 2023-10-31T12:51:15.608Z - nodejs: 16.20.2 2023-10-31T12:51:15.613Z - python: 3.10.8 2023-10-31T12:51:15.618Z - Version '16.20.2' of platform 'nodejs' is … -
Make env file as .gitignore in djangp project?
image How to move my broenv (env folder) folder inside gitignore. I don't want to store my broenv folder to Github. How can I remove that from github? Plzzz help! Is that okay to store env folder in github?. I don't want to store my broenv(env) folder to Github repository. -
How to create mongodb models with multiple dictionaries for django
So i have a databases which stores players positions in time in mongoDB, then i connect to it with django and this works fine. _id: "", timeline: { "1":{ "Player 1":{ "x":"554", "y":"581" }, "Player 2":{ "x":"554", "y":"581" }, } "2":{ "Player 2":{ "x":"554", "y":"581" }, "Player 1":{ "x":"554", "y":"581" }, } ... } team1: "ABC" team2: "BCD" in models.py i have class Game(models.Model): _id = models.CharField(max_length=100, primary_key=True) timeline = JSONField() team1 = models.CharField(max_length=100) team2 = models.CharField(max_length=100) and i get the error "the JSON object must be str, bytes or bytearray, not OrderedDict" is there a problem with my data? Or how should i define it in my model.py? -
Email Verificationl is not sent after registration. Django + Celery
I use Windows without WSL. Recently I have installed Redis for caching in my Django project. I've done it without some problems using this link: https://github.com/microsoftarchive/redis/releases Next task was working with Celery for registration optimization (If I understand correctly, I'm watching a development course). I've done everything as in my course. But Email Verification didn't worked. I have the same code like author code. But author use MacOS. I don't fully understand the work with Celery, but I need to do it. I will be grateful for your help! base - root directory users - app for working with users base/_init_.py: from .celery import app as celery_app __all__ = ('celery_app',) base/celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') app = Celery('base') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() base/settings.py: CELERY_BROKER_URL: str = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND: str = 'redis://127.0.0.1:6379' users/forms.py: class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Enter the name', })) last_name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Enter the surname', })) username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-4', 'placeholder': "Enter the user's name", })) email = forms.CharField(widget=forms.EmailInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Enter the email address', })) password1 = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Enter the password', })) password2 = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control py-4', … -
How do I Link the following two tables in Django?
I have two models; Employee and Product. The two tables already have data. All I need to do is Assign each Employee to a Product(eg. Computer) and then be able to retrieve the data and display it. Here are the models. from django.db import models from django.utils import timezone from django.dispatch import receiver from more_itertools import quantify from django.db.models import Sum # Create your models here. class Employee(models.Model): address = models.EmailField(max_length=100,null=True) first_name = models.CharField(max_length=50,null=True) sec_name = models.CharField(max_length=50,null=True) department = models.CharField(max_length= 50,null=True) company = models.CharField(max_length= 50,null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name + ' - ' + self.department class Product(models.Model): model=models.CharField(max_length=50, null=True) serial=models.CharField(max_length=50, null=True) hd_size=models.CharField(max_length=50,null=True) ram=models.CharField(max_length=50, null=True) processor=models.CharField(max_length=50, null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.serial + ' - ' + self.model -
How to make classes separately for each word in django
To begin with I would like to say that I write with the help of django. The question itself. I have models in the folder models.py, there is specified in fact all that I output in the post, I also have a file views.py and in general everything works fine, the posts are displayed on the page that I need. But! I need to modify the posts, for example, change the color of the header, make that one was after the other, but I can not assign just a class or an idi to a certain header or a certain piece of text, because they are all united in one line, look at the code and understand. <body> {% for post in post_list %} <h3>{{post.title }}</h3> <p>{{ post.description}}</p> <p>{{ post.time_posts}}</p> {{ post.author }} {% endfor %} </body> If i put a class front example <div class="prjclass"><p>{{ post.time_posts}}</p></div> Then I have that when working in css with this prjtitle class I move absolutely all headings and they just merge 1 in 1. How can I make it so that I can edit almost every word with css classes or idi. -
Issues with django file logger
I have a created a django logger settings. It is intended that console django.db.backends should not be applied to console. But it is printing in console as well. LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "file": { "level": "DEBUG", "class": "logging.handlers.TimedRotatingFileHandler", "filename": "debug/debug.log", 'when': 'W0', # Weekly log staring from Monday 'interval': 1, 'backupCount': 10, }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", }, }, "root": {"level": "INFO", "handlers": ["console"]}, "loggers": { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['file'], } }, } This is my logger configuration. With this it is logging sql commands in file as well as console. I want this to be logged only for file. Please help if you have encountered this issue before. -
django-allauth and django-phone-auth clash on EmailAdress.User mutual accessors
I have my auth app in Django and a custom user defined as #auth/models.py class User(AbstractUser): pass And it is set as the user_model in settings: AUTH_USER_MODEL = 'auth.User' I'd like to use django-phone-auth for authenticating with phone or email, and django-allauth to authenticate with social providers. After I add the both to my virtual environment and try migrate I get the error: account.EmailAddress.user: (fields.E304) Reverse accessor 'User.emailaddress_set' for 'account.EmailAddress.user' clashes with reverse accessor for 'phone_auth.EmailAddress.user'. The problem is in the same-named models having foreign key relation to the user model in the two packages. #allauth/account/models.py class EmailAddress(models.Model): user = models.ForeignKey( allauth_app_settings.USER_MODEL, verbose_name=_("user"), on_delete=models.CASCADE, # # !!!! related_name='accountuser' would solve the conflict ) ... vs. #phone-auth/models.py class EmailAddress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... The clash is due to reverse reference conflict, and adding related_name='accountuser' to any of the user fields does solve it. But changing original code of installed packages is not a good idea. Can anyone advise how it should be sorted out, please. Many thanks!