Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic nested formsets Django
i have a django project with a circuit model and an exercise model (circuit has an exercise field which is Many2Many relationship to exercise model. I want each user to be able to dynamically add circuits and to each circuit dynamically add exercises, so each circuit will have the exercises added to it specifically. I managed to dynamically add the 2 formsets (circuitFormSet and exerciseFormSet) with javascript but couldn't connect between the circuits and exercises. models.py: class Exercise(models.Model): name = models.CharField() num_of_rounds = models.IntegerField() class Circuit(models.Model): name = models.CharField() exercises = models.ManyToManyField(Exercise) forms.py class ExerciseForm(ModelForm): class Meta: model = Exercise fields = '__all__' class CircuitForm(ModelForm): class Meta: model = Circuit fields = '__all__' ExerciseFormSet = formset_factory(ExerciseForm, extra=1) CircuitFormSet = formset_factory(CircuitForm, extra=1) -
django filterset search object that contain text
I'm not experience with python or django before. but I just started to create new custom plugin for NetBox using django the plugin works well but I still struggle with search function. I can search if the values are text. but if the value is an object, it not able to search in the postgresql, the table I've created with member show as member_id that refer to ipam_ipaddress(id) models class memberlist(NetBoxModel) member = models.ForeignKey( to='ipam.IPAddress', related_name='member', verbose_name='Member IP Address', on_delete=models.PROTECT ) filtersets class memberlistFilterSet(django_filters.FilterSet): q = django_filters.CharFilter( method="search", label="Search", ) class Meta: model = memberlist fields = [ 'name', 'member', ] def search(self, queryset, name, value): if not value.strip(): return queryset qs_filter = ( Q(name__icontains=value) |Q(member_icontains=value) ) return queryset.filter(qs_filter) Please help!! I want to search by name or member value that references to IPAddress model in NetBox I've tried many method but it didn't work e.g. member = IPAddress.objects.filter(address__contains=) -
Celery worker connection with Rabittmq met broken pipe error IN Gevent Mode
This does not happen with our dev environment, tasks there run on a much smaller db, so issuing much less db queries and external requests, I imagine this issue might have something to do with task loads. error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 246, in perform_pending_operations self._pending_operations.pop()() File "/usr/local/lib/python3.8/site-packages/vine/promises.py", line 160, in __call__ return self.throw() File "/usr/local/lib/python3.8/site-packages/vine/promises.py", line 157, in __call__ retval = fun(*final_args, **final_kwargs) File "/usr/local/lib/python3.8/site-packages/kombu/message.py", line 128, in ack_log_error self.ack(multiple=multiple) File "/usr/local/lib/python3.8/site-packages/kombu/message.py", line 123, in ack self.channel.basic_ack(self.delivery_tag, multiple=multiple) File "/usr/local/lib/python3.8/site-packages/amqp/channel.py", line 1407, in basic_ack return self.send_method( File "/usr/local/lib/python3.8/site-packages/amqp/abstract_channel.py", line 70, in send_method conn.frame_writer(1, self.channel_id, sig, args, content) File "/usr/local/lib/python3.8/site-packages/amqp/method_framing.py", line 186, in write_frame write(buffer_store.view[:offset]) File "/usr/local/lib/python3.8/site-packages/amqp/transport.py", line 347, in write self._write(s) File "/usr/local/lib/python3.8/site-packages/gevent/_socketcommon.py", line 699, in sendall return _sendall(self, data_memory, flags) File "/usr/local/lib/python3.8/site-packages/gevent/_socketcommon.py", line 409, in _sendall timeleft = __send_chunk(socket, chunk, flags, timeleft, end) File "/usr/local/lib/python3.8/site-packages/gevent/_socketcommon.py", line 338, in __send_chunk data_sent += socket.send(chunk, flags) File "/usr/local/lib/python3.8/site-packages/gevent/_socketcommon.py", line 722, in send return self._sock.send(data, flags) BrokenPipeError: [Errno 32] Broken pipe This is my celery command: celery -A analytics worker -P gevent -c 500 -l info -E --without-gossip --without-mingle --without-heartbeat & and my Django configs: CELERY_IGNORE_RESULT = True CELERY_WORKER_PREFETCH_MULTIPLIER = 100 CELERY_WORKER_MAX_TASKS_PER_CHILD = 400 CELERYD_TASK_SOFT_TIME_LIMIT = 60 * … -
While converting HTML to pdf, the page is stuck in loading at create pdf
While trying to generate a pdf file with the below code, the browser is stuck loading from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() print('RESULT') pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) print('PDF') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None and generate_pdf view: def generate_pdf(request): pdf = render_to_pdf('doc.html', data) response = HttpResponse(pdf, content_type='application/pdf') filename = "Document_to_mail.pdf" content = "inline; filename=%s" %(filename) download = request.GET.get("download") if download: content = "attachment; filename=%s" %(filename) response['Content-Disposition'] = content return response browser is stuck in pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) -
Product Pop-up using Reach and Django
I am working through a tutorial on React and creating an ecommerce store with a Django backend. I am new to React. I have been able to get the React "FrontEnd" home page to display the products from the Django "products.py" which is a simple JSON file stored in the Django file system using the React Axios library. There is a product pop-up which displays the product information when the use clicks on the view button. I can't work out how to direct the pop-up to the "products.py" file. It is still drawing its information from the products.js in the React "FrontEnd" file system. The code is below. Any assistance would be appreciated. The code for the product page is below. Bestsellershop.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { handleOutofStock } from '../../../helper/shopHelper'; import { RatingShop } from '../../../helper/helper'; import Quickview from '../../layouts/Quickview'; import { Modal } from 'react-bootstrap'; import axios from 'axios' class Bestsellershop extends Component { constructor(props) { super(props); this.state = { error:null, modalshow: false, lastActiveBox: -1, data:[] } this.modalShow = this.modalShow.bind(this); this.modalClose = this.modalClose.bind(this); } componentDidMount(){ var str = "GeeksforGeeks"; this.setState({loading:true}); axios .get('/api/products/') .then(res=>{ console.log(res.data); this.setState({data:res.data, loading:false}); }) .catch(err … -
AttributeError at /login 'str' object has no attribute '_meta'
Guys i'm getting error in django login can you please help me to solve this error View.py def login_user(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, username) return render(request, 'auth/login.html') login.html <form method="post"> {% csrf_token %} <div class="mb-3"> <label for="username" class="form-label">Username</label> <input type="text" name="username" class="form-control" id="username"> </div> <div class="mb-3"> <label for="password" class="form-label">Password</label> <input type="password" name="password" class="form-control" id="password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> -
django manage static files accessibility
example app tree: articles ├── admin.py ├── apps.py ├── models.py ├── static │ ├── css │ │ ├── article_change.css │ │ ├── article_create.css │ │ ├── article_detail.css │ └── js (obfuscated) │ ├── article_create.js │ ├── article_list.js │ ├── edit_process.js │ ├── editor.js │ └── js (readable) │ ├── article_create.js │ ├── article_list.js │ ├── edit_process.js │ └── editor.js ├── templates │ └── articles │ ├── article_create.html │ ├── article_detail.html │ ├── edit_process.html │ └── editor.html ├── tests.py ├── urls.py └── views.py static/js/js contains javascript that is human readable static/js contains obfuscated javascript files. I wrote a template tag to includes files: @register.simple_tag def jstatic(path): s = '' if settings.DEBUG: s = 'js/' return static(s + path) in templates, I can do: <script src="{% jstatic 'js/info.js' %}"></script> which conditionally renders static javascript files based on DEBUG mode. whereas, if not in DEBUG mode, will serve obfuscated files. the thing is, I don't want unobfuscated file to be accessed when DEBUG is not on, which is running the application on server. when debug is on, I want user user only to visit obfuscated files: static/js/js/info.js and have no access to static/js/info.js all the apps follows this root tree convention, I wonder … -
405 HTML: Method Not Allowed
I have created a calendar that is embedded in my website. There is an option for admins to create events and when I try to create an event, I get faced with a 405 Error. Could someone please point me in the right direction into why this isn't working, when in previous versions of Python Django, it was working? My code is below for convenience: urls.py from django.urls import path from main_website import views from main_website.views import (AboutView, ArticleCreateView, ArticleDeleteView, ArticleUpdateView, CalendarView, ContactUsView, DonateView, EditEventView, EventView, HelpUsView, ImageAddView, ImageCategoryAddView, ImageDetailView, ImageGalleryView, IndexView, SearchView, TaggedView) urlpatterns = [ path('', IndexView.as_view(), name='main_website_home'), path('about', AboutView.as_view(), name='main_website_about'), path('search/', SearchView.as_view(), name='main_website_search'), path('article_create', ArticleCreateView.as_view(), name='main_website_article_create'), path('article/<slug:slug>', views.article_detail, name='main_website_article_detail'), path('article/update/<slug:slug>/', ArticleUpdateView.as_view(), name='main_website_article_update'), path('article/delete/<slug:slug>/', ArticleDeleteView.as_view(), name='main_website_article_delete'), path('tags/<slug:slug>/articles/', TaggedView.as_view(), name="main_website_article_tags"), path('calendar/', CalendarView.as_view(), name='main_website_calendar'), path('calendar/event/new/', EventView.as_view(), name='main_website_calendar_new_event'), path('calendar/event/edit/<event_id>/', EditEventView.as_view(), name='main_website_calendar_edit_event'), path('waiting_list/register', views.waiting_list_register, name='main_website_waiting_list_register'), path('gallery', ImageGalleryView.as_view(), name='main_website_gallery'), path('gallery/upload', ImageAddView.as_view(), name='main_website_gallery_upload'), path('gallery/category/add/', ImageCategoryAddView.as_view(), name='main_website_gallery_add_category'), path('gallery/image/<str:pk>/', ImageDetailView.as_view(), name='main_website_gallery_image_detail'), path('help_us', HelpUsView.as_view(), name='main_website_help_us'), path('ways_to_donate', DonateView.as_view(), name='main_website_ways_to_donate'), path('contact_us', ContactUsView.as_view(), name='main_website_contact_us') ] utils.py import calendar from calendar import HTMLCalendar from datetime import date, datetime, timedelta from main_website.models import Event class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, … -
Django.db.utils.DatabaseError with MongoDB as Backend Database
Internal Server Error: /loginapi/registeruser/ Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 929, in _insert query.execute() File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 397, in execute res = self.db[self.left_table].insert_many(docs, ordered=False) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\collection.py", line 770, in insert_many blk.execute(write_concern, session=session) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\bulk.py", line 533, in execute return self.execute_command(generator, write_concern, session) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\bulk.py", line 366, in execute_command _raise_bulk_write_error(full_result) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\bulk.py", line 140, in _raise_bulk_write_error raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: PP1.loginapi_user index: email_1 dup key: { email: "m@gmail.com" }', 'keyPattern': {'email': 1}, 'keyValue': {'email': 'm@gmail.com'}, 'op': {'id': 18, 'last_login': None, 'is_superuser': False, 'first_name': '', 'last_name': '', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2022, 11, 8, 7, 7, 44, 901495), 'name': 'g', 'email': 'm@gmail.com', 'password': '', '_id': ObjectId('636a0040d416e6cc888d66d5')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 869, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: INSERT INTO … -
windows 11 - python 3.11.0 - error installing psutil, How to resolve?
note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psutil Failed to build psutil ERROR: Could not build wheels for psutil, which is required to install pyproject.toml-based projects I was trying to install locust in Tastypie Project. The requirements used in project are :- -
python app setup option from cPanel software section is missing
I bought a domain and hosting from webhost python for my Django web site but python app setup option from cPanel software section is missing and, in every tutorial, they follow the same the step means without python app setup option I have no way to live my Django site, I am completely new in web development and this first time I want live my website I try to follow my YouTube tutorial, but everyone follows same steps so don't understand what should i do -
Using {{auth_errorcode}} in django
while trying to sign in with google I encounter the following error Social Network Login Failure An error occurred while attempting to login via your social network account. I want to find out what's gone wrong in here. I found some solutions like using {{auth_error.code}} but as a noob, I don't to how to use that. If the command can give me clues to the errors I would appreciate the detailed instruction regarding all changes. -
how to fix 504 gateway timeout error in gunicorn
gunicorn app:app -b :8080 --timeout 120 --workers=3 --threads=3 --worker-connections=1000 I am new to devops and I am currently using this command to run my app on port 9=8080 but if i receive too many requests i am getting 504 gateway timeout error, i know workers =3 means if three request comes simultaneiously they will be processed simultaneously by worker but what is the use of threads and worker connections, do i need to increase the worker, threads and worker-connection size to prevent 504 from happening, kindly explain me Thanks! I need to know is this command correct. If not how do i modify this so that 504 error should not occur again -
Django Queryset check value if exists
I have two values to check if it's existed in my PostgreSQL. I also have columns named ref_name, ref_surname for example: //this is the data// name: John Surname: Lee //this is some queryset from django// Employee.objects.filter(ref_name=name & ref_surname=Surname).exists I want to check if the data is already existed in my database. I have read the Queryset documentation and I can't find an answer. I'm open to any suggestion. -
use local postgres database to docker container
Hey everyone i am trying to connect my postgres database install in ubuntu 20.04 to the docker container, which will be outside of the container. I am working on django project. I am able to create the postgres database inside the docker container and connect my django project to that database, but i want is to connect localdatabase to the django project which is running in docker container Here is my docker-compose.yml file version: '3.3' services: # Description (For the postgres databse) kapediadb: image: postgres restart: always container_name: kapediadb # For accessing env data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} # Description (For django applications) kapedia: restart: always container_name: kapedia command: - /bin/bash - -c - | python manage.py makemigrations accounts python manage.py makemigrations posts python manage.py makemigrations quiz python manage.py migrate gunicorn kapedia.wsgi:application --bind 0.0.0.0:8000 image: kapedia # Description (define your dockerfile location here) build: . volumes: - .:/kapedia ports: - "8000:8000" depends_on: - kapediadb env_file: - .env # Description (For volumes) volumes: static: -
Grouping group permissions in django and drf
I'm creating ecommerce website with many apps (catalog, analytics, sale, warehouses, users...) and I created group permissions for each of apps (like group which has all permissions in catalog app and etc). I also created a new admin-dashboard. I want to make dynamic role-based authentication and let's say superAdmin wants to create role like "operator" and he should add some of the groups as permissions (for example he can access to catalog and sale group permissions). How can I group another groups dynamically? Or are there any better methods? -
Html to PDF conversion in Django
I have to convert an html page to pdf format and download it in Django.I have used xhtml2pdf library for the same.But the issue is i have to create 3 pages with different contents from database with header and footer in a single pdf file.I am not getting an idea,how to manage this.Can anyone help me how to handle it -
Trying to place postgresql database information inside a dotenv file to hide important info, like passwords etc
I'm using the django rest framework and trying to connect a postgresql database. If I have the connection to the database written explicitly in the settings.py file, running python manage.py runserver works fine, but as soon as I replace the database connection with the dotenv values, the connection breaks. How do I fix this? example This works fine DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ticketdb', 'USER': 'postgres', 'PASSWORD': 'pretendmyrealpasswordishere', 'HOST': 'localhost', } } This does not and throws this error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_USER_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } Traceback Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run self.check_migrations() File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/core/management/base.py", line 564, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/backends/base/base.py", … -
500 internal Server Error while setting up django in apache
I was working to setup apache2 for my django and while i started my apache server it shows 500 error ` <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match t`your text`his virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn Alias /static /var/www/isvr/static <Directory /var/www/isvr/static> Require all granted </Directory> <Directory /var/www/isvr/isvr_certs> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/var/www/isvr python-home=/var/www/isvr/myprojectenv WSGIProcessGroup myproject WSGIScriptAlias / /var/www/isvr/isvr_certs/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is … -
How to redirect urls?
this is my main urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include("shop.urls")), ] i want that any url enter by user it will redirect to shop.urls and find here. like if user enter /index it will search index in shop.urls not in main urls my shop.urls from django.urls import path from . import views urlpatterns = [ path('', views.index), path('index', views.index), ] -
Django formtools Wizard done function not executed
(Reference: Django formtools done function not executed) I am trying to do the same thing. The steps are working and individual form data able to get, but after the submit button is clicked and final form is submitted, I expect all three form data to be submitted at once and the done function has to process that but it is not happening. I am not able to find the reason why. Because of policy I can't share the code but putting a dummy code here and logic what I am implementing. Kindly please direct. Following is my code, (This is a Edit Form I am trying to create, in each form init method is also overrided for initial data wrt pk, this all is working not an issue) done.html {% extends CURRENT_TEMPLATE %} {% load static %} {% block content %} Hi you are watching done.html {{ data }} {% endblock content %} form.html {% extends CURRENT_TEMPLATE %} {% load i18n %} {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form.as_table }} {% … -
TypeError: check_password() missing 1 required positional argument: 'encoded'
I am trying to authenticate the user made using python manage.py shell, the password looks like :- pbkdf2_sha256$390000$------------------------$- . I have used custom user model (abstractbaseuser) and a email authentication backend, right now I am handling the user authentication by diretly creating the user in the DB table. settings.py AUTH_USER_MODEL = 'accounts.Usermanagement' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.EmailAuthBackend', ] backends.py # from django.contrib.auth.models import User from django.contrib.auth.hashers import check_password from django.contrib.auth import get_user_model Usermanagement = get_user_model() class EmailAuthBackend: def authenticate(self,request,username,password): print("Custom authenticate rqst: ",request) try: user = Usermanagement.objects.get(emailid=username) # print(password) # print(user.password) # print(check_password(password)) # print(user.check_password(password)) if user.password == password or user.password == check_password(password): #! PROBLEM return user return None except user.DoesNotExist: return None def get_user(self,user_id): try: return Usermanagement.objects.get(pk=user_id) except Usermanagement.DoesNotExist: return None managers.py from django.contrib.auth.models import BaseUserManager from django.contrib.auth.hashers import make_password class UsermanagementCustomUserManager(BaseUserManager): # create_user(username_field, password=None, **other_fields) def create_user(self,emailid,roleid,organizationid,firstname, password=None, passwordexpirydate="2022-12-12 12:00:00",createdby=0,modifiedby=0): """ Creates and saves a User with the given email, date of birth and password. """ if not emailid: raise ValueError('Users must have an email address') user = self.model( emailid=self.normalize_email(emailid), roleid = roleid, organizationid=organizationid, firstname = firstname, password= make_password(password), createdby = createdby, modifiedby = modifiedby, ) views.py from django.contrib import messages from django.http import HttpResponse from django.contrib.auth import … -
Why is Django database save not permanently saving the update?
I am using a postgresql database. I am updating a certain field of an existing database row and saving it again. However, this is change not reflecting inside the database (viewing it on DBeaver). The bizarre thing is that the change is properly reflected using the debugger and querying the database with the same ID. p_details: ProjectDetails = ProjectDetails.objects.get(pk=res['id']) p_details.build_status = ProjectBuildEnums.PASSED.value if res['error'] is None else ProjectBuildEnums.FAILED.value p_details.build_error = json.dumps(res) p_details.save(update_fields=["build_status", "build_error"]) sleep(1) new_p = ProjectDetails.objects.get(pk=res['id']) This is the line of code where I am updating the database. After the save, I am requerying the database using the same primary key ID. At this instance, using the debugger, I can see the changes clearly. However, viewing this database using DBeaver after refreshing the database doesnt show this change yet. Once the view is complete, and I refresh the database again, this change is still not present, meaning the update has disappeared. Does anyone know what is going on? After the above lines, the ProjectDetails database is no longer being touched. No errors are shown in the terminal/debugger either. -
How can I automatically update two objects in same model after 7 days continuously on Django?
I have a 2 models that I wish to interact/update every 7 days without needing me to execute. ( wether the website is online or offline )( local hosting for now ) class Model: name = model... quantity = models.IntegerField(default=0) obj A name = A quantity = 0 obj B name = B quantity = 1,000,000 I'm trying to find a way to transfer 1000 from obj B to obj A, every 7 days. I am looking but still can't find an answer that simplifies this situation. Thanks for the help! I haven't tried anything yet since I do not know where to start. I know how to update objects manually, on page load or with signals. it may have something to do with DateTime but I am not sure. Currently, there is no date field in the model. Or celery, but I have never used it before. -
How to update custom user's model fields using APIView update method
I am trying to code up a APIView's update method so I can change model fields in my custom AbstractUser model. I read the documentation for APIViews and other examples, but most of them involved another OneToOne 'profile' model like in this example and or coding up the serializer which I don't think it's necessary for user model(correct me if I'm wrong) I am unsure how to implement the same update method for a user model. This is my custom user model. I am trying to update referred_count and tokens fields here from frontend users/models.py class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None first_name = models.CharField(max_length=100, default="unknown") last_name = models.CharField(max_length=100, default="unknown", blank=True) profile_pic = models.CharField(max_length=200, default="unknown") premium = models.BooleanField(default=False) referred_count = models.IntegerField(default=0) tokens = models.IntegerField(default=0) email = models.EmailField(unique=True, db_index=True) secret_key = models.CharField(max_length=255, default=get_random_secret_key) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() class Meta: swappable = "AUTH_USER_MODEL" users/api.py class UpdateFields(ApiAuthMixin, ApiErrorsMixin, APIView): def update(self, request, *args, **kwargs): # update various user fields based on request.data # I am not sure what should go inside here. return request.user.update(request, *args, **kwargs) I want to send something like the following from frontend which will pass through the UpdateFields APIView and 'patch' …