Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to take data from the admin using Django forms?
I want when the user to select multiple users, a pop-up form will appear and he can send emails after submitting the form to the selected users This is admin.py ` class ReplyForm(forms.Form): message = forms.CharField(widget=forms.Textarea) @admin.register(ContactUs)class ContactUsAdmin(admin.ModelAdmin):actions = ['reply_by_email']list_display = ("id", "first_name", "last_name", "email","phone_number", "created_at", "message")search_fields = ("first_name", "last_name", "email", "phone_number", "message") def reply_by_email(self, request, queryset): if request.POST: form = ReplyForm(request.POST) if form.is_valid(): subject = "Custom email from admin" message = form.cleaned_data['message'] from_email = "admin@@example.com" recipient_list = [user.email for user in queryset] send_mail(subject, message, from_email, recipient_list) else: # check the form's errors print(form.errors) else: form = ReplyForm(request.POST or None) context = self.admin_site.each_context(request) context['form'] = form context['queryset'] = queryset return TemplateResponse(request, "reply_by_email.html", context) reply_by_email.short_description = "Send email to selected users" this is reply_by_email.html: {% load i18n %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="apply" value="Send Email"> </form> {% endblock %} when the admin fill the form nothing happens [enter image description here](https://i.stack.imgur.com/dAlaF.png) enter image description here Iam expecting a message from the user -
Azure Storage - FileNotFoundError: [Errno 2] No such file or directory
I am using django-storage to handle media files on Azure Storage. I am using Docker to deploy an app to Web App for Containers. When I am trying to run my celery task it gives me an error: File "/code/myapp_settings/celery.py", line 59, in test_task spec.loader.exec_module(spider_module) File "<frozen importlib._bootstrap_external>", line 839, in exec_module File "<frozen importlib._bootstrap_external>", line 975, in get_code File "<frozen importlib._bootstrap_external>", line 1032, in get_data FileNotFoundError: [Errno 2] No such file or directory: 'https://myapp.blob.core.windows.net/media/python/test.py' I checked Azure Storage and file with such name and path exists. I can access it from Azure and from URL normally without any issues. I can also upload and download file from admin panel. Below is my celery task that I am trying to run: @shared_task(name="test_task") def test_task(myapp_id): myapp = myapp.objects.get(id=myapp_id) python_config_file = myapp.python_config_file module_path = os.path.join(MEDIA_URL, f"{python_config_file}") spec = importlib.util.spec_from_file_location("myapp", module_path) myapp_module = importlib.util.module_from_spec(spec) sys.modules["myapp"] = myapp_module spec.loader.exec_module(myapp_module) asyncio.run(myapp_module.run( task_id = test_task.request.id )) return f"[myapp: {myapp_id}, task_id: {test_task.request.id}]" Below are my media variables that I have in settings.py DEFAULT_FILE_STORAGE = 'azure.storage_production.AzureMediaStorage' MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = os.environ.get('AZURE_ACCOUNT_NAME') AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' If anyone can tell me what am I doing wrong I'd be grateful. -
Celery Beat stuck on starting it
The Problem: I have issue with celery beat it only show starting on the terminal and not run any tasks also when I deploy it on heroku it do the same behavior. Here is the Terminal it only show starting: (shap-backend-venv) mahmoudnasser@Mahmouds-MacBook-Pro rest.shab.ch % celery -A server beat -l info --logfile=celery.beat.log --detach (shap-backend-venv) mahmoudnasser@Mahmouds-MacBook-Pro rest.shab.ch % celery -A server worker --beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler Secure redis scheme specified (rediss) with no ssl options, defaulting to insecure SSL behaviour. [2023-01-25 13:00:29,570: WARNING/MainProcess] Secure redis scheme specified (rediss) with no ssl options, defaulting to insecure SSL behaviour. [2023-01-25 13:00:29,571: WARNING/MainProcess] Secure redis scheme specified (rediss) Setting ssl_cert_reqs=CERT_NONE when connecting to redis means that celery will not validate the identity of the redis broker when connecting. This leaves you vulnerable to man in the middle attacks. -------------- celery@Mahmouds-MacBook-Pro.local v5.1.2 (sun-harmonics) --- ***** ----- -- ******* ---- macOS-12.6-arm64-arm-64bit 2023-01-25 13:00:29 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: server:0x106872730 - ** ---------- .> transport: rediss://127.0.0.1:6379/0 - ** ---------- .> results: rediss://127.0.0.1:6379/0 - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** … -
ModuleNotFoundError: No module named 'channels.http'
I found a couple of similar questions, but nothing really helped. I tried updating asgiref version and also updated channels and django-eventstream. I mainly followed the instruction from the django-eventstream-setup page. relevant packages from my setup: Package Version ------------------ --------- asgiref 3.6.0 channels 4.0.0 Django 4.1.2 django-eventstream 4.5.1 django-grip 3.2.0 django-htmx 1.12.2 gripcontrol 4.1.0 huey 2.4.3 MarkupSafe 2.1.2 requests 2.28.1 Werkzeug 2.2.2 The error I get upon executing python manage.py runserver: ... File "...\venv\lib\site-packages\django_eventstream\routing.py", line 2, in <module> from . import consumers File "...\venv\lib\site-packages\django_eventstream\consumers.py", line 7, in <module> from channels.http import AsgiRequest ModuleNotFoundError: No module named 'channels.http' I created an asgi.py file next to settings.py: import os from django.core.asgi import get_asgi_application from django.urls import path, re_path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import django_eventstream os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'channels_test.settings') application = ProtocolTypeRouter({ 'http': URLRouter([ path("events/", AuthMiddlewareStack(URLRouter(django_eventstream.routing.urlpatterns)), { 'channels': ['test'] }), re_path(r"", get_asgi_application()), ]), }) In setup.py I updated for using asgi: WSGI_APPLICATION = "channels_test.wsgi.application" ASGI_APPLICATION = "channels_test.asgi.application" This is the folder structure: -
Graphene-Django - 'int' object has no attribute 'pk'
I'm new to working with GraphQL and Django and I am trying to test out in the playground but I am getting a 'int' object has no attribute 'pk' error. My models.py class Managers(models.Model): id = models.IntegerField(primary_key=True) jointed_time = models.DateField() started_event = models.IntegerField() favourite_team = models.ForeignKey( Teams, models.DO_NOTHING, db_column='favourite_team', blank=True, null=True) player_first_name = models.TextField() player_last_name = models.TextField() player_region_id = models.IntegerField() player_region_name = models.TextField() player_region_iso_code_short = models.TextField() player_region_iso_code_long = models.TextField() team_name = models.TextField() class Meta: managed = False db_table = 'managers' class Gameweeks(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() deadline_time = models.DateField() deadline_time_epoch = models.IntegerField() class Meta: managed = False db_table = 'gameweeks' class ManagerGwStats(models.Model): id = models.OneToOneField(Managers, models.DO_NOTHING, db_column='id', primary_key=True) active_chip = models.TextField(blank=True, null=True) gameweek = models.ForeignKey( Gameweeks, models.DO_NOTHING, db_column='gameweek') points = models.IntegerField() total_points = models.IntegerField() rank = models.IntegerField() rank_sort = models.IntegerField() overall_rank = models.IntegerField() bank = models.IntegerField() value = models.IntegerField() event_transfers = models.IntegerField() event_transfers_cost = models.IntegerField() points_on_bench = models.IntegerField() class Meta: managed = False db_table = 'manager_gw_stats' unique_together = (('id', 'gameweek'),) Schema.py class GameweekType(DjangoObjectType): class Meta: model = Gameweeks fields = "__all__" class ManagerType(DjangoObjectType): class Meta: model = Managers fields = "__all__" class ManagerGwStatType(DjangoObjectType): class Meta: model = ManagerGwStats fields = "__all__" class Query(graphene.ObjectType): all_managers = graphene.List(ManagerType) manager = … -
How to run the socket io server using gunicorn service
I'm using the socket.io service in my Django app, and I want to create one gunicorn service that is responsible for starting the socket.io service. Below is the socket io server code File name: server.py from wsgi import application from server_events import sio app = socketio.WSGIApp(sio, application) class Command(BaseCommand): help = 'Start the server' def handle(self, *args, **options): eventlet.wsgi.server(eventlet.listen(('127.0.0.1', 8001)), app) Below is the actual code of the server with connect, disconnect and one custom method File name: server_events.py from wsgi import application sio = socketio.Server(logger=True) app = socketio.WSGIApp(sio, application) @sio.event def connected(sid, environ): print("Server connected with sid: {}".format(sid)) @sio.event def disconnect(sid): print("Server disconnected with sid: {}".format(sid)) @sio.event def run_bots(sid): print("func executed") **# Here custom logic** When I hit python manage.py server in local, it will work fine, but on a production server, I don't want to type the python manage.py server command. What I want is to create one Gunicorn service and provide some instructions to that service so that when I hit the Gunicorn service command, it will start the socket IO server automatically, just like the runserver command. I tried to implement those things by creating the Gunicorn service file, but it couldn't work. socket-gunicorn.service [Unit] Description=SocketIO … -
Django - Filter same value with multiple dates
I'm having trouble selecting the first occurrence of the same value with multiple dates. I have the two following models in a logistic app: class Parcel(models.Model): """ Class designed to create parcels. """ name = models.CharField(max_length=255, blank=True, null=True) tracking_number = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) class ParcelStatus(models.Model): """ Class designed to create parcel status. """ SLA_choices = ( (_('Parcel shipped'), 'Parcel shipped'), (_('Delivered'), 'Delivered'), (_('In transit'), 'In transit'), (_('Exception A'), 'Exception A'), (_('Exception B'), 'Exception B'), (_('Exception C'), 'Exception C'), (_('Other'), 'Other'), (_('Claim'), 'Claim'), ) parcel = models.ForeignKey(Parcel, on_delete=models.CASCADE, blank=False, null=True) status = models.CharField(max_length=255, blank=True, null=True, choices=SLA_choices) event = models.ForeignKey(GridEventTransporter, on_delete=DO_NOTHING, blank=True, null=True) reason = models.ForeignKey(GridReasonTransporter, on_delete=DO_NOTHING, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) I'm getting multiple statuses for a parcel. For example: Parcel Status Date XXXX Delivered 2022-22-12 13:00 XXXX Delivered 2022-15-12 18:20 XXXX Delivered 2022-12-12 15:27 XXXX Delivered 2022-12-12 15:21 XXXX In transit 2022-12-12 03:21 Inside my class, I'm retrieving parcels such as: def get_parcels(self): return Parcel.objects.filter(company=self.company) def get_parcels_delivered(self): parcels = self.get_parcels() parcels = parcels.filter(parcelstatus__status='Delivered', parcelstatus__date__date=self.date) parcels = parcels.distinct() return parcels My issue is the following: as you can see, I get multiple Delivered status with different dates. I would like to only retrieve the parcel with … -
SimpleJWT returns different access and refresh token each time
So, I have a django project, and have added JWT authentication. The problem is that each time I use TokenObtainPairView with the same credentials I get different access and refresh tokens. Is this the default behavior, as I have not changed anything in the settings? Is there a way to get the previous token unless it has expired? If you need more info please let me know. -
Command django-admin --version in windows terminal while using virtual environment displaying error
After installing Django version 1.9 in virtual environment using windows cmd command "django-admin --version" is displaying long error ending with the following: File "C:\Users\DELL\env\Lib\site-packages\django\db\models\sql\query.py", line 11, in from collections import Counter, Iterator, Mapping, OrderedDict ImportError: cannot import name 'Iterator' from 'collections' (C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\collections_init_.py) Python is installed Virtual environment was activated. Django is installed using pip install django==1.9 What should I do run the command django-admin --version?? -
How to access environment variable in react?
I added react into django using webpack and when I created .env file in app_name/, I am trying to access environment variable like this process.env.base_url but I am getting undefined. file structure Django_React -- app_name -- src -- .env -- urls.py ... ... How can I create and access environment variable if react app is created like this ? -
Templates hmtl in view
I work under Django-python for the development of an application. For a few hours I have been stuck on the integration of html pages, let me explain: I can't associate several HTML pages under the same python class... class DieeCreateView(DieeBaseView, FormView): """View to create a Diee""" form_class = DieeForm template_name = 'diee_create.html' So I modified urls.py urlpatterns = [ path( "diee/new", diee_view.DieeCreateView.as_view(), name="diee_create", ), path( "diee/new/newthree", diee_view.DieeCreateView.as_view(), name="diee_create_03", ),] then make a list class DieeCreateView(DieeBaseView, FormView): """View to create a Diee""" form_class = DieeForm template_name = ['diee_create.html', 'diee_create_03.html'] but nothing works... Thanks in advance -
Custom JWT authentication
I want to authenticate the user with email and confirmation code. But JWT uses by default username and password for authentication. How can I change that? Should I override TokenObtainSerializer? -
How to compare list of models with queryset in django?
I have a serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass fields = "__all__" def validate(self, data): user = self.context.get("request").user users = data.get("users") users_list = User.objects.filter(organization=user.organization) return data users will print a list of models like this: [<User: User 1>, <User: User 2>] users_list will display a queryset: Queryset: <QuerySet [<User: User 1>, <User: User 2>, <User: User 3>]> I want to write a query which checks if list of models e.g.users are present inside a queryset users_list. How to do that? -
I want to be able to update a user's password in my React.js and Django app
Backend is Dango The front end is made with React.js. What I want to achieve it I want to users to update their registered passwords. Issue/error message If you update the password on the React.js side, it will look like the following and the update will fail. . Django side Terminal {'password': 'welcome1313'} username {'detail': [ErrorDetail(string='Invalid data. Expected a dictionary, but got str.', code='invalid')]} Bad Request: /users/12/ [15/Jan/2023 15:42:10] "PATCH /users/12/ HTTP/1.1" 400 13 React.js const MyPagePasswordUpdate = () => { const [my_password, setValue] = useState(null); const [my_ID,setMyID] = useState(null); const isLoggedIn= useSelector(state => state.user.isLoggedIn); const { register, handleSubmit, errors } = useForm(); useEffect(() => { async function fetchData(){ const result = await axios.get( apiURL+'mypage/', { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${cookies.get('accesstoken')}` } }) .then(result => { setValue(result.data.password); setMyID(result.data.id); }) .catch(err => { console.log("err"); }); } fetchData(); },[]); const update = async (data) =>{ console.log(data) await axios.patch(`${apiURL}users/`+my_ID+'/', { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${cookies.get('accesstoken')}` }, password:data.password, }, ).then(message => { alert("Updated!") }) .catch(err => { console.log("miss"); alert("The characters are invalid"); }); }; return ( <div> {isLoggedIn ? <div class="update-block"> <form onSubmit={handleSubmit(update)}> <label for="password">Password:</label> <input className='form-control' type="password" {...register('password')} /> <input className='btn btn-secondary' type="submit" value="Update" /> </form> <Link to="/mypage">Back to … -
CheckboxSelectMultiple widget Django renders already collapsed in form
I am trying to create a form where you can enter the language or languages. I want to use a CheckboxSelectMultiple widget, but it renders already collapsed in the form: The form with already collapsed select How can I fix this? forms.py: class TweetForm(forms.ModelForm): class Meta: model = TweetSearch fields = ['search_term', 'query_type', 'start_date', 'end_date', 'language', 'country', 'tweet_count'] widgets = { 'search_term': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Search...'}), 'query_type': forms.Select(attrs={'class': 'form-control'}), 'tweet_count': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Number of tweets'}), 'start_date': DateTimePickerInput(attrs={'class': 'form-control', 'placeholder': 'From'}), 'end_date': DateTimePickerInput(attrs={'class': 'form-control', 'placeholder': 'Till'}), 'language': forms.CheckboxSelectMultiple(attrs={'class':'form-control'}) } html: <div id="searchcontainer"> <div class="card w-50 text-center mx-auto mt-8" id="searchcard"> <div class="card-header"> Search </div> <div class="card-body"> <h5 class="card-title">Search for tweets</h5> <form action="" method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4"> {{form.search_term}} </div> <div class="form-group col-md-4"> {{form.query_type}} </div> <div class="form-group col-md-4"> {{form.tweet_count}} </div> </div> <div class="form-row"> <div class="form-group col-md-6"> {{form.start_date}} </div> <div class="form-group col-md-6"> {{form.end_date}} </div> </div> <div class="form-row"> {{form.language}} </div> <input class="btn btn-primary mb-2" type="submit"> </form> </div> </div> -
django multi file upload fields
List item registration start date Year Vin# Make Title Owner (Upload field) ==== (can be several files) HUT # (Upload field) ==== (can be several files) Ifta # (Upload field) ==== (can be several files) I need that model If file upload fields had to be for a single file, then it would be okay, but how Can I handle that model? (Should I create ForeignKey models for every file_upload field in order to handle multi file uploads??) -
nested result for nested serializer in django with many to many fields
i have four models : CommonAccess model that have four ManyToMany to AccessSubject,AccessGroup,AccessAction and AccessSubGroup class CommonAccess(TimeStampedModel): name = models.CharField(blank=True,null=True,max_length=200,) subjects = models.ManyToManyField(AccessSubject,) groups = models.ManyToManyField(AccessGroup,blank=True,) actions = models.ManyToManyField(AccessAction,blank=True,) sub_groups = models.ManyToManyField('AccessSubGroup,blank=True, ) def __str__(self): return self.ename or '' AccessSubject model: class AccessSubject(): name = models.CharField(blank=True, null=True, max_length=200, unique=True,) AccessGroup model: class AccessGroup(): name = models.CharField(blank=True, null=True, max_length=200, unique=True,) access_subject = models.ForeignKey(AccessSubject,on_delete=models.SET_NULL,related_name='access_groups') AccessSubGroup model: class AccessSubGroup(): name = models.CharField(blank=True, null=True, max_length=200, unique=True,) access_subject = models.ForeignKey(AccessSubject,on_delete=models.SET_NULL,) access_group = models.ForeignKey(AccessGroup,on_delete=models.SET_NULL,related_name='accessgroup_subgroups') i need to when pass a commonAccess id get commonAccess with nested subject,group and sub group that fileter with ManyToMany fields in CommonAccess model like : name: 'sample' subject: [ name: 'sub1' group : [ name: 'gr1' sub_group: [ name: 'sgr1' ] [ name: 'sgr2' ] ] group : [ name: 'gr2' sub_group: [name: 'sgr3'] ] ] [ name: 'sub2' group : [ name: 'gr3' ] ] i have used serializer like below, but only subjects filtered by CommonAccess ManyToMany fileds, i want Group and SubGroup also filtered by CommonAccess : class NewCommonAccessSerializer(ModelSerializer): subjects = NewAccessSubjectNestedSerializer(read_only=True, many=True) class Meta: model = CommonAccess fields = "__all__" class NewAccessSubjectNestedSerializer(ModelSerializer): accesslevel_groups = NewAccessGroupNestedSerializer(many = True) class Meta: model = AccessSubject fields = '__all__' class NewAccessGroupNestedSerializer(ModelSerializer): … -
AttributeError: module 'django.db.models' has no attribute 'SubfieldBase'
I'm trying to run application originally created using python 3.6 and django 1.11 with python 3.7 and django 2.2. I'm now getting problems when starting django server: python manage.py runserver Exception in thread Thread-1: Traceback (most recent call last): File "/opt/python/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/opt/python/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/srv/work/miettinj/tandt_putki/python/django/tandt/tandt/models.py", line 20, in <module> from select_multiple_field.models import SelectMultipleField File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/select_multiple_field/models.py", line 20, in <module> class SelectMultipleField(six.with_metaclass(models.SubfieldBase, AttributeError: module 'django.db.models' has no attribute 'SubfieldBase' my virtualenv: (python-3.7-django-*) miettinj@ramen:~/tandt_putki/python/django/tandt> pip freeze adal==1.2.7 aniso8601==7.0.0 anyascii==0.3.1 asgiref==3.6.0 azure-core==1.26.2 backports.zoneinfo==0.2.1 bcrypt==4.0.1 beautifulsoup4==4.11.1 bleach==6.0.0 … -
Retrieve the value of a field linked by foreign key to a Profile that extends the User (oneToOne relationship) in Django views.py
What I want to do : Display a phone book from Django User model extended with a Profile model related to several models What I have done : Of course, I've read Django documentation (4.1) I have my classic Django User model I have created a "Profile" model to extend the User model via a OneToOne relationship (here simplified) : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) entity = models.ForeignKey(Entity, null=True, blank=True, on_delete=models.CASCADE) class Meta: ordering = ['entity__name', 'user__last_name'] def __str__(self): return self.user.first_name + " " + self.user.last_name @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I have created an "Entity" model (more or less the company where people work) (here simplified) : class Entity(CommonFieldsUUID): name = models.CharField(max_length=100, unique=True, null=False, default="N.C.") alias = models.CharField(max_length=25, unique=True, null=False, default="N.C.") class Meta: verbose_name = "Entity" verbose_name_plural = "Entities" def __str__(self): return self.alias Here is my views.py : from .models import User from django.http import HttpResponse from django.template import loader def phonebook(request): user = User.objects.filter(is_active=True).values('first_name','last_name','email','profile__entity','profile__pro_ext','profile__pro_gsm','profile__pro_trigram','profile__location') template = loader.get_template('phonebook/phonebook.html') context = { 'colHeaders': ['Firstname LASTNAME', 'Entity', 'Extension', 'Mobile', 'Email', 'Initials', 'Location'], 'user': user, } return HttpResponse(template.render(context, request)) Here is my template phonebook.html : {% extends "main/datatables.html" %} … -
How can I query item wise stocks and revenue in django ORM?
`class RevenueStockDashboardViewset(ViewSet): sale = InvSaleDetail.objects.filter(sale_main__sale_type='SALE') sale_returns = InvSaleDetail.objects.filter(sale_main__sale_type='RETURN') purchase = InvPurchaseDetail.objects.filter(purchase_main__purchase_type='PURCHASE') purchase_returns = InvPurchaseDetail.objects.filter(purchase_main__purchase_type='RETURN') def list(self, request): total_revenue = (self.sale.annotate(total=Sum('sale_main__grand_total')) .aggregate(total_revenue=Sum('total')) .get('total_revenue') or 0) - (self.sale_returns.annotate(total=Sum('sale_main__grand_total')) .aggregate(total_revenue=Sum('total')) .get('total_revenue') or 0) - (self.purchase.annotate(total=Sum('purchase_main__grand_total')) .aggregate(total_revenue=Sum('total')) .get('total_revenue') or 0) + (self.purchase_returns.annotate(total=Sum('purchase_main__grand_total')) .aggregate(total_revenue=Sum('total')) .get('total_revenue') or 0) total_stocks = (self.purchase.annotate(total=Sum('qty')) .aggregate(total_stock=Sum('total')) .get('total_stock') or 0) - (self.purchase_returns.annotate(total=Sum('qty')) .aggregate(total_stocks=Sum('total')) .get('total_stock') or 0) - (self.sale.annotate(total=Sum('qty')) .aggregate(total_stock=Sum('total')) .get('total_stock') or 0) - (self.sale_returns.annotate(total=Sum('qty')) .aggregate(total_stock=Sum('total')) .get('total_stock') or 0) return Response( { 'total_revenue': total_revenue, 'total_stocks': total_stocks, # 'item_wise_stocks': items, } )` I have Inventory Dashboard where I want to show the item wise revenue and item wise stocks. I have done query for total stocks and revenue but I want item wise. If you need more information. Please let me Know. -
localstorage alternatives for a django iframe app
Are there any alternatives for localstorage as we are using this to store a few data. Our issue is that our app is working as an iframe in Shopify, so when testing in incognito window it denies the access of localstorage. This is the error we are getting: Uncaught DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document. Can someone please suggest a solution for this issue? -
Get the string of two upper levels in foraign relations
Good Morning, How to get the value Entity.name about ProjectsComments row. Top model : class Entities(models.Model): code = models.CharField(verbose_name='Código', max_length=10, blank=False, unique=True, help_text='Codigo de entidad.') name = models.CharField(max_length=150, verbose_name='Nombre', unique=True, help_text='Nombre de la entidad.') def __str__(self): return self.name def toJSON(self): item = model_to_dict(self) return item Second Level: class Projects(models.Model): entity = models.ForeignKey(Entities, on_delete=models.DO_NOTHING, verbose_name="Entidad") def __str__(self): return f'{self.entity}' + ' \ ' + f'{self.code}' + ' \ ' + f'{self.name}' # + ' \ ' + f'{self.phase}' def toJSON(self): item = model_to_dict(self) item['entity'] = self.entity.toJSON() return item Third Level class ProjectsComments(models.Model): project = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=0, verbose_name='Proyecto', help_text='Proyecto') def __str__(self): return f'{self.date}' + f' ' + f'#' + f'{self.user}' + f'# ' + f'{self.comment}' def toJSON(self): item = model_to_dict(self) item['project'] = self.project.toJSON() item['entity'] = Entities.objects.get(pk = ) item['user'] = self.user.toJSON() return item I would need that from projectscommentsListView get the value of ProjectsComments__Projects__Entity.name I have tried get into ProjectsComments.toJSON() with : item['entity'] = Entities.objects.get(pk = ) AND item['entity'] = self.entity.toJSON() I do not know anymore. -
Design a MLM Binary tree structure
I have the data coming from Django rest framework, I've created the tree using jQuery and also used some CSS for the structure. but the structure is not in a proper way. want perfect design just like a mlm binary tree I have the data coming from Django rest framework, I've created the tree using jQuery and also used some CSS for the structure. but the structure is not in a proper way. want perfect design just like a mlm binary tree. I want the design to be perfect and smooth. -
I want to run R modules in Django Framework on production using rpy2 ? is it possible ? Please let me know the steps
I want to run R modules in Django Framework on production using rpy2 ? is it possible ? Please let me know the steps. File "/mnt/d/venv/lib/python3.8/site-packages/rpy2/robjects/conversion.py", line 370, in _raise_missingconverter raise NotImplementedError(_missingconverter_msg) NotImplementedError: Conversion rules forrpy2.robjects appear to be missing. Those rules are in a Python contextvars.ContextVar. This could be caused by multithreading code not passing context to the thread. -
Filling a website page with info about ongoing proccess with Django and Selenium
Hey I'm currently building a website that uses Django as front and back and selenium automations with python. I'm unsure how to implement this idea, for example user is creating an object and then he's redirected into another blank page and I want this blank page to fill with paragraph about each of the processes Selenium does (where it succeeds and where it fails for a re run) I thought about using javascript to load dynamic late into the dom as selenium runs its functions and the results outputted into the blank page for the user to see, is there any other way to do so with django?