Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test is user is one of the groups in a list of groups
I have a list of groups, and I want to test if the user belongs to any one of the groups. I can get a list of user's groups: user_groups = user_object.groups.all() And I can use sets: if not set(user_object.groups.all()).isdisjoint(group_list): Is this the best way? -
What is the best way to relate rows in the same table
I'm trying to design a table of rows, each row can relate in some manner to another row. On the practical level we are talking about layers of soil (archaeology). One row - one layer - is above another layer, essentially A is above B is above C, equally C is below B is below A. In a graph database this would be very trivial, unfortunately we are using a relational database. Each relation ship has a direction, A is above B, but B is not above A. The data will be added as A is above B although we may want to search and find what is above B, with or without being explicit about this relationship, if A is above B then B must be below A. A further complication is that D could equal E, as in it is the same as, so D=E and E=D, however this is not directional because the relationship is true both ways. So that's the logic. But, what is the best way to design some tables to allow this? I should note we use PostgreSQL and Django. A basic example follows. Table name: Layer id Layer_name I assume we need a … -
How to show username on header templates on every page?
I'm new to Django so please be patient. I'm trying to save the username of the logged in user to show it on the header of every page, but I have no idea how to do that. I've looked at this approach but I still do not understand how it works. Any suggestion? -- views.py -- def login_user(request): if (request.method == 'POST'): username = request.POST['username'] password = request.POST['password'] auth = LDAPBackend() user = auth.authenticate(request, username=username, password=password) # Check if user can be authenticated in LDAP server if user is not None: print(username + " has successfully authenticated on LDAP server") # Get user objects from auth_user table usr = User.objects.get(username=username) # Check if user already exist in UserDetail model # Create user if user does not exist previously if UserDetail.objects.filter(user_id=username).count() > 0: # Start user session request.session['username'] = username print("Current session username: " + request.session['username']) # Redirect successfully authenticated LDAP user to the ACL home page return index(request) else: # Create new user for successfully authenticated LDAP user # Set values for new user name = usr.last_name user_id = usr.username email = usr.email section = "" status = usr.is_active roles = "Normal User" # Create new user to database UserDetail.objects.create(name=name, … -
During UserCreationForm, id does not register into system
First of all, it's my error code: https://imgur.com/0XHUEvz In my Django Project, need to register a doctor account. Every doctor has a 'hospital.' So, Doctor model has a hospital as a Foreign Key. class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default="") name = models.CharField(max_length=50, default='isim') gsm = models.CharField(max_length=11) address = models.CharField(max_length=200) email = models.EmailField() title = models.CharField(max_length=20) department = models.CharField(max_length=100) hospital = models.ForeignKey(Hospitals, on_delete=models.CASCADE) class Hospitals(models.Model): name = models.CharField(max_length=100) province = models.ForeignKey(Province, on_delete=models.CASCADE) district = models.ForeignKey(District, on_delete=models.CASCADE) phone = models.CharField(max_length=15) numBeds = models.CharField(max_length=5) numRooms = models.CharField(max_length=5) class UserRegisterForm2(UserCreationForm): email = forms.EmailField(label='Email address') email2 = forms.EmailField(label='Confirm Email') hospital = forms.ChoiceField( choices=[(x.id, x.name) for x in Hospitals.objects.all()] ) class Meta: model = User fields = [ 'username', 'email', 'email2', 'hospital' ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError("Emails must match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError( "This email has already been registered") return super(UserRegisterForm2, self).clean(*args, **kwargs) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'hospital': return super().formfield_for_foreignkey(db_field, request, **kwargs) def save(self, commit=True): instance = super().save(commit=False) pk = self.cleaned_data['hospital'] instance.hospital = Hospitals.objects.get(pk=pk) instance.save(commit) return instance When i go to the registration page, I can see the hospitals registered in the database. Like it's a … -
Django: Can't get models fields to show in template
I can't get the cat name and kitten type from the Cat and Kitten models into the template. This is my model.py class Cat(models.Model): cat_name = models.CharField(max_length=200) def __str__(self): return self.cat_name class Kitten(models.Model): cat = models.ForeignKey(Cat, on_delete=models.CASCADE, related_name='kittens') kitten_type = models.CharField(max_length=200) def __str__(self): return self.kitten_type My views.py class CatViews(generic.ListView): model = Cat template_name = 'polls/cats.html' class CatDetail(generic.DetailView): model = Kitten template_name = 'polls/kitten.html' My urls.py urlpatterns = [ path('cats/', views.CatViews.as_view(), name='catlist'), path('cats/<int:pk>/', views.CatDetail.as_view(), name='catdetail'), ] And finally, polls/kitten.html <h3>{{cat.cat_name}}</h3> {% for kitty in cat.kittens.all %} <p>{{ kitty.kitten_type }}</p> {% endfor %} The url is working, I'm just not able to display the fields from the models into their respective html elements. What am I missing? -
Error on deployment Heroku + cookiecutter application
i'm trying to deploy an cookiecutter application on heroku. Once the build is finished, when i run heroku open, the browser shows me the following error: ERR_TOO_MANY_REDIRECTS My allowed hosts are: ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["main_url","{app-name}.herokuapp.com"]) Heroku logs: 2020-01-15T23:39:33.514722+00:00 heroku[router]: at=info method=GET path="/" host={app-name}.herokuapp.com dyno=web.1 connect=0ms service=2ms status=301 bytes=296 protocol=https What is the best way to solve it? -
How do I get a Null value to validate in a serializers.DateTimeField() field?
I'm using django-rest-framework to validate JSON passed to a URL which acts as a webhook. Below is the JSON I'm passing and the Serializer used to validate the data. Is there any way I can get the serializers.DateTimeField() field to allow null values? I've marked the relevant fields below... JSON passed to webhook: { "type": "transaction.created", "data": { "account_id": "acc_00008gju41AHyfLUzBUk8A", "amount": -350, "created": "2015-09-04T14:28:40Z", "currency": "GBP", "description": "Ozone Coffee Roasters", "id": "tx_00008zjky19HyFLAzlUk7t", "category": "eating_out", "is_load": false, "settled": null, <-- this field is sometimes null "merchant": { "address": { "address": "98 Southgate Road", "city": "London", "country": "GB", "latitude": 51.54151, "longitude": -0.08482400000002599, "postcode": "N1 3JD", "region": "Greater London" }, "created": "2015-08-22T12:20:18Z", "group_id": "grp_00008zIcpbBOaAr7TTP3sv", "id": "merch_00008zIcpbAKe8shBxXUtl", "logo": "https://pbs.twimg.com/profile_images/527043602623389696/68_SgUWJ.jpeg", "emoji": "🍞", "name": "The De Beauvoir Deli Co.", "category": "eating_out" } } } Serializers.py: class MerchantSerializer(serializers.Serializer): id = serializers.CharField(required=True, max_length=50) name = serializers.CharField(required=True, max_length=100) logo = serializers.URLField(max_length=250, required=False) class DataSerializer(serializers.Serializer): account_id = serializers.CharField(required=True, max_length=50) amount = serializers.IntegerField(required=True) created = serializers.DateTimeField() currency = serializers.CharField(required=True, max_length=3) description = serializers.CharField(required=True, max_length=250) id = serializers.CharField(required=True, max_length=50) category = serializers.CharField(required=True, max_length=100) is_load = serializers.BooleanField() settled = serializers.DateTimeField(required=False) # <-- fails validation here merchant = MerchantSerializer() class TransactionSerializer(serializers.Serializer): type = serializers.CharField(required=True, max_length=50) data = DataSerializer() -
How can i get Json records from all the pages with Django Rest Framework?
I created an API endpoint with Django Rest Framework. I'm now querying this endpoint from a Jquery script. The problem is that, once the request is sent, DRF will return Json data only from the first page of my API endpoint. How can i set it to retrieve all the data, instead? Here is my view: class tstList(generics.ListCreateAPIView): queryset = tst.objects.all() serializer_class = tstSerializer filter_backends = [DjangoFilterBackend] My serializer: class tstSerializer(serializers.ModelSerializer): class Meta: model = tst fields = ('Amount', 'Perc') def create(self, validated_data): return tst.objects.create(**validated_data) I'm querying the endpoint to this url: http://127.0.0.1:8000/tst -
What's causing my windows 10 firewall to block Docker drive sharing?
I have been following this tutorial on Docker's documentation to try to learn how to develop Django websites using Docker. When I try running the sudo docker-compose run web django-admin startproject composeexample . command, I get an error that states the following: Cannot create container for service web: b'Drive sharing seems blocked by a firewall' I tried going into Docker's settings and setting the C drive to be accessible to containers, but then I get an error that says: Firewall detected A firewall is blocking file sharing between Windows and the containers. See documentation for more info. I've tried googling around for some different solutions. I've tried going through this github thread, and I've tried, for example, changing the vEthernet(DockerNAT) properties. I've also tried some other troubleshooting methods, which I will link below: Link 1 Link 2 Link 3 So far, nothing I has tried worked. I am trying to do this on a work computer that runs Windows 10 Enterprise, however I have talked with my IT team and I have been told that the firewall is not blocking any ports or programs that would keep Docker from running. Is it possible that I am missing something? Any kind … -
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
this is my first django project so apologies if I'm not explaining myself well. I'm trying to write some unit tests. This works fine from unittest import TestCase class TestModel(TestCase): def test_CalculatePercentage(self): assert 1 == 1 However, the problem I face is that as soon as I try to import something from the application i.e. from unittest import TestCase from investor.models import Investor class TestModel(TestCase): def test_CalculatePercentage(self): assert 1 == 1 I start getting this error FAILED (errors=1) Error Traceback (most recent call last): File "C:\Program Files\Python38\lib\unittest\case.py", line 60, in testPartExecutor yield File "C:\Program Files\Python38\lib\unittest\case.py", line 676, in run self._callTestMethod(testMethod) File "C:\Program Files\Python38\lib\unittest\case.py", line 633, in _callTestMethod method() File "C:\Program Files\Python38\lib\unittest\loader.py", line 34, in testFailure raise self._exception ImportError: Failed to import test module: tests Traceback (most recent call last): File "C:\Program Files\Python38\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Program Files\Python38\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\Users\lbrusokas\Documents\Dev\website\website_env\src\webapp\investor\tests.py", line 1, in <module> from investor.models import Investor File "C:\Users\lbrusokas\Documents\Dev\website\website_env\src\webapp\investor\models.py", line 2, in <module> from django.contrib.auth.models import AbstractBaseUser, BaseUserManager File "C:\Program Files\Python38\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Program Files\Python38\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Program Files\Python38\lib\site-packages\django\db\models\base.py", line 87, in __new__ app_config = apps.get_containing_app_config(module) File … -
Can I add a custom method to a Django queryset?
Suppose I have two models, in a one-to-many relationship: from django.db import models class Quantity(models.Model): name = models.CharField(max_length=64) class Measurement(models.Model): value = models.FloatField() date = models.DateField() quantity = models.ForeignKeyField(Quantity, on_delete=models.CASCADE) And I make some records... weight = Quantity.objects.create(name="Body Weight in kg") Measurement.objects.create(value=80, date="2020-01-01", quantity=weight) Measurement.objects.create(value=81, date="2020-01-02", quantity=weight) Measurement.objects.create(value=80.6, date="2020-01-03", quantity=weight) Measurement.objects.create(value=80.1, date="2020-01-04", quantity=weight) Measurement.objects.create(value=79.5, date="2020-01-05", quantity=weight) Measurement.objects.create(value=81, date="2020-01-06", quantity=weight) Measurement.objects.create(value=81, date="2020-01-07", quantity=weight) Is there anyway I can calculate metrics from the queryset like this... weight.measurement_set.all().average() weight.measurement_set.filter(date__gt="2020-01-04").average() weight.measurement_set.all().sum() ...where I define the relevant methods somewhere... def average(queryset): return sum([m.value for m in queryset]) / queryset.count()) def average(queryset): return sum([m.value for m in queryset]) I have read this post from 2011 but the answers seem a little out of date and don't seem to work. I am using django 2.2 currently. -
I wanted to save a PIL image to imagefield in django. This part of code solved the problem. But i dont understand it
I found this code on stackoverflow itself. It solved the problem of saving a PIL image to django ImageField without giving the '_commited' error. But observing it, I don't understand its functioning. How did things happened. Can you explain it to me so that become able to modify it according to the future needs and get an overall better understanding of this particular codes function. not giving anything related to the PIL image to the imagefield.save and still saving and adding the record of that PIL image is all i see it as. and its confusuing. from PIL import Image from io import BytesIO from django.core.files.base import ContentFile f = BytesIO() try: pil_image_obj.save(f, format='png') model_instance.image_field.save(model_instance.image_field.name, ContentFile(f.getvalue())) #model_instance.save() finally: f.close() Thanks in advance. -
Access Django Test Database
I have an API running on Heroku and would like to be able to test it using the test database. My problem I have is that the TestCase setUp(self) method adds the data to an automatically created test database. Then my tests send a POST request to the locally running version of itself. That code then is just using the regular default database instead of the test database the tests are running in. Here's some code and what I've tried. In my main settings.py I have named my database like so DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'theOneTrueDB', } } And I read here (https://docs.djangoproject.com/en/3.0/topics/testing/overview/#the-test-database) that The default test database names are created by prepending test_ to the value of each NAME in DATABASES. So I figured in my views file for one of my apps I could just do Tenant.objects.using('test_theOneTrueDB').all() and that would work but it says django.db.utils.ConnectionDoesNotExist: The connection test_theOneTrueDB doesn't exist I have also tried Tenant.objects.using('test_default') and many other things. I am lost. I would also be okay with setting up another database and then using that in the setup with Tenant.objects.save(using='theOneTrueDBTest) or something like that. Any help would be appreciated! -
django-dynamic-formset issue when delete
When I'm trying to remove a row, the formset send me the following error [{}, {}, {}, {'id': ['This field is required']}]. If I change the following parameter can_delete=True inside the modelformset_factory, I can delete object but rows stays display even after I pressed the remove button. I tried to add {% if form.instance.pk %}{{ form.DELETE }}{% endif %} in the template, it didn't change anything. I am using django 2.2 and django-dynamic-formset, the country_fr/en come from modeltranslation. Views @login_required def view_countries(request): CountryFormSet = modelformset_factory( Country, fields=('country_fr', 'country_en'), formset=BaseCountryFormSet, can_delete=True) if request.method == 'POST': formset = CountryFormSet(request.POST) if formset.is_valid(): formset.save() else: formset = CountryFormSet() context = { 'formset': formset, 'menu': 'cards', 'menu_cards': 'countries', 'model': _('countries'), 'fields': [_('countries')+' [fr]', _('countries')+' [en]'], } return render(request, 'cards/index_formset.html', context) Html <form method="post" class="mt-2"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div id="form" class="row_formset d-flex text-center mb-1"> {% if form.instance.pk %}{{ form.DELETE }}{% endif %} {% for field in form.hidden_fields %} <div class="invisible"> {{ field }} </div> {% endfor %} {% for field in form.visible_fields %} <div class="flex-fill field"> {{ field }} </div> {% endfor %} </div> {% endfor %} <div class="d-flex mt-2 justify-content-center"> <input type="submit" value="{% trans 'submit'|capfirst %}" … -
How can i display a Foreign Key on a select tag in my django template?
I'm trying to display some information on a SELECT tag on my template that passes through a for loop and can't seem to find a how to. The examples I find on the internet aren't dynamics (from another table) and I'm really struggling on that. Bellow are my codes, hope you guys can help me on this. This is my models.py class Books(models.Model): [...] category_cod_category = models.ForeignKey( 'Category', on_delete = models.CASCADE ) class Meta: db_table = 'Books' class Category(models.Model): category_name = models.CharField( max_length = 45 ) def __str__(self): return '%s' % self.category_name class Meta: db_table = 'Category' This is my views.py and this bit of code is from another template where I have a button for editing. def edit(request,id): book = Books.objects.get(id=id) return render(request,'edit.html',{'edit_book':book}) This is my template edit.html where i need the category of the books to be displayed. Every other field is OK. <form method="POST" class="post-form" action="/update/{{ book.id }}"> {% csrf_token %} [...] <div class="container"> <label>Categoria do Livro:</label> <select class="selectpicker form-control" data-live-search="true"> {% for books in Books %} <option value="{{ edit_livro.category_cod_category}}">{{ edit_livro.category_cod_category}}</option> {% endfor %} </select> <div> [...] Can you guys help me? Or send me a place where I can learn how to solve this? Sorry for … -
Need architectural advice on how to handle and/or avoid circular imports when using Django/DRF
I would like advice regarding an architectural problem I've encountered many times now. I have a Model Event in events.py: # models.py import events.serializers class Event(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, db_index=True) ... def save(self, *args, **kwargs): is_new = not self.pk super().save(*args, **kwargs) if is_new: self.notify_organiser_followers() def notify_organiser_followers(self): if self.organiser: event_data = events.serializers.BaseEventSerializer(self).data payload = {'title': f'New event by {self.organiser.name}', 'body': f'{self.organiser.name} has just created a new event: {self.name}', 'data': {'event': event_data}} send_fcm_messages(self.organiser.followers.all(), payload) The model has a serializer called BaseEventSerializer. In the save method, I use notify_organiser_followers to and in the process serialize the current event being saved. To do this, I have to import BaseEventSerializer. Here's how the code of events.serializers looks: # serializers.py import events.models class EventTrackSerializer(serializers.ModelSerializer): class Meta: model = events.models.EventTrack fields = ('id', 'name', 'color') class BaseEventSerializer(serializers.ModelSerializer): event_type = serializers.CharField(source='get_event_type_display') locations = serializers.SerializerMethodField() As you can see, serializers.py has to import models to use them in ModelSerializers. In this step, I end up with an obvious circular import. The way I solved this was by importing BaseEventSerializer locally in the notify_organiser_followers function: def notify_organiser_followers(self): if self.organiser: from events.serializers import BaseEventSerializer This eliminates the issue, but I would really like avoiding this, especially because I … -
Problems with python django module, to be specific , debug mode
Iam having problems with django. I have a web app called profile that shows a users profile. Now the problem comes in when i turn debug to false. All the profile photos of all users goes missing and 404 status code is thrown on the terminal running the server. Help will be appreciated. -
Loading gif while backend script is executed
So I've got a form and when I submit it, a backend script.py is executed in Django. It makes some statistical analysis which takes about 8 secs and when it finishes I get redirected to a next page. So I've been trying to find a way to implement a loading gif while the script is executed but I failed in every one of my efforts. I was thinking about using AJAX and javascript onclick method (or even onsubmit), but they didn't work. Thank you all in advance. -
how to create sub classes model in list form in django
i am making a class in which i want like a admin model to be prepared which first add name of countries then on selecting any country name another sub classes ahould be made for name of states and then in each state other sub class should be made for showing cites and so on but i am able to create separete class for all but not in a list view. class country(models.Model): country = models.CharField( max_length=100) def __str__(self): return self.country class states(models.Model): states=models.CharField(max_length=100) def __str__(self): return self.states -
Django Model is not printing the Model Details
I am new to Django/python and I am helping the team in migrating Django project as the installed server needs to be migrated. Old Version Django - 1.6.5 Python - 2.7 Due to some compatibility and versions not available, below the versions which we migrated to and was able to bring up the application without any errors. There were some compilation error related to deprecated methods and was able to correct that. Migrated Version Django - Django-1.6.5 Python – 3.4 Database – sqllite Pillow - Pillow-3.3.0 PIP - pip-1.5.4 Everything looks fine, except the admin module. In the main admin screen instead of displaying the module fields, it is just displaying the object name. Below the location model list it used to display before migration Location Room: A | Cabinet: 23 | Drawer: 7 Room: A | Cabinet: 24 | Drawer: 4 After Migration, it just displays the location object name Location Location object Location object I looked at the model.py and below the location model defined **class Location(models.Model): room = models.CharField(max_length=31, help_text='(Required) e.g. A, B, C, D, E, F') station = models.IntegerField(max_length=5, blank=True, null=True, help_text='e.g. 1, 2, ...') cabinet = models.IntegerField(blank=True, null=True, help_text='e.g. 1, 2, ...') shelf = models.IntegerField(blank=True, … -
Docker is running but cannot access local development server [Django]
I can't access the Django's welcome page from locahost. I've tried many of the answers already and nothing seems to be working. I've done the following: Changed my port from 8000 to 9000 and exposed them. I've CMD from the Dockerfile. Exposed several ports on the docker-compose.yml file but nothing works. Run docker build . several times after making changes Changed ALLOWED_HOSTS to '*' and ['*'] Will appreciate your help. Config: Docker version 19.03.1, build 74b1e89e8a OS: Windows 10 Home Docker Toolbox Dockerfile: FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN apk update && apk add libpq RUN apk add --virtual .build-deps gcc python3-dev musl-dev postgresql-dev RUN pip install psycopg2 RUN apk del .build-deps RUN mkdir /myapp WORKDIR /myapp COPY ./myapp/myapp RUN adduser -D user USER user docker-compose.yml: version: "3" services: db: image: postgres web: build: . command: sh -c "python manage.py collectstatic --no-input && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:9000" environment: - DB_NAME=postgres - DB_USER=postgres - DB_PASS=postgres - DB_HOST=db - DB_PORT=5432 - DEBUG=${DEBUG} - SECRET_KEY=${SECRET_KEY} volumes: - ./myapp:/myapp ports: - "9000:9000" depends_on: - db -
Contact Form is not working. IntegrityError at /contact/
Models.py class ContactForm(models.Model): name = models.CharField(max_length=50) subject = models.CharField(max_length=200) email = models.EmailField() message = models.TextField() def __str__(self): return self.name views.py def contact(request): if request.method == "POST": name = request.POST.get('name') subject = request.POST.get('subject') email = request.POST.get('email') message = request.POST.get('message') ContactForm.objects.create( name = name, subject = subject, email = email, message = message ) return render( request, 'blog/contact.html', { 'msg':'Details have been saved. We will get back to you.' } ) else: return render(request, 'blog/contact.html') contact.html {% extends 'blog/base.html' %} {% block content %} <div class="container wrap mb-5" style="margin-top: 100px"> <h2 class="text">Contact Us</h2> <form action="{% url 'contact' %}" method="POST"> {% csrf_token %} <input type="text" placeholder="Enter Your Name" name="name"> <input type="text" placeholder="Subject" name="subject"> <input type="email" placeholder="Enter Your Email" name="email"> <input type="message" placeholder="Write Your Message" name="msg"> <input type="submit" value="Send" name="Submit"> </form> {% if msg %} <div class="alert alert-success"> {{ msg }} </div> {% endif %} </div> {% endblock %} This error was occurs while I click on the submit button. It shows IntegrityError at /contact/ NOT NULL constraint failed: blog_contacts.message. The above exception (NOT NULL constraint failed: blog_contacts.message) was the direct cause of the following exception: -
Django message form to add multiple recipients to a field?
I am working on a messaging app and have a model with a field recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='received_messages', null=True, blank=True, on_delete=models.SET_NULL) and a form for that model with a field recipient = forms.ModelMultipleChoiceField(label='Recipient', queryset=User.objects.all()) Now right now I know its just a MultipleChoiceField, but I am looking to make this a TextArea, which only allows users already in the database to be entered into that TextArea, and also to be able to add multiple recipients to this field. I am just trying to figure out the best course of action to take on this. Thanks in advance! -
How to share a grpc client stub variable with Django workers?
I have a Django app running in wsgi. In the app there is a method that starts grpc client connection and stores it in a variable stub. Here's an example code in views.py from app.models import * stub='' def connect(): channel = grpc.insecure_channel('localhost:50051') stub = helloworld_pb2_grpc.GreeterStub(channel) def hello(): response = stub.SayHello(helloworld_pb2.HelloRequest(name='you')) print(response) Now when I run this code with 'python manage.py runserver' command, it works because, of a single thread development environment. But when I launch my application in production, because the wsgi can create multiple works, my stub variable is not shared with other workers. And because the connect method ran in only one worker and not all, in other workers the stub variable is an empty string and which leads to inconsistent variable value on querying. Essentially is there any way I could share the stub variable across all workers. I tried to use django cache but storage in it is required to be a string. Any help is appreciated. -
How to update a dict inside a list
I have the following list in my view context, which contains dictionaries: [{ < CustomUser: admin@admin.com >: [ { 'label': 'ID', 'value': 1, }] }, { < CustomUser: admin2@admin.com >: [ { 'label': 'ID', 'value': 4, }] }] I want to merge each dict in the list with the following dict: { < CustomUser: admin @admin.com >: { 'role': 'Company 1' }, < CustomUser: admin2 @admin.com >: { 'role': 'Company 2' } } So that this is the end result: [{ < CustomUser: admin@admin.com >: [ { 'label': 'ID', 'value': 1, 'role': 'Company 1' }] }, { < CustomUser: admin2@admin.com >: [ { 'label': 'ID', 'value': 4, 'role': 'Company 2' }] }] Is there any way to update dict inside a list? I have a lot of key value pairs in reality, so can't do this manually with named fields.