Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django-admin-sortable2 and django-import-export package together in admin panel?
I want to use django-admin-sortable2 django-import-export package together in admin panel. Here is the code: class University(models.Model): name = models.CharField(max_length=50, help_text="University or Institution Name") short_name = models.CharField(blank=True, max_length=10, help_text="University or Institution Short Name") order = models.PositiveIntegerField( default=0, blank=False, null=False, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.id}-{self.name}' class Meta: ordering = ['order'] admin.py: from import_export import resources from import_export.admin import ImportExportModelAdmin from adminsortable2.admin import SortableAdminMixin # Register your models here. class UniversityResource(resources.ModelResource): class Meta: model = University exclude = ('created_at', 'updated_at',) class UniveresityAdmin(ImportExportModelAdmin, SortableAdminMixin, admin.ModelAdmin): resource_classes = [UniversityResource] admin.site.register(University, UniveresityAdmin) But this is not working, If I remove ImportExportModelAdmin then sortable works and if I remove SortableAdminMixin, import-export works. But I want to use both package together. Is there workaround to solve this issue? Thanks in advance. -
My Django project is not displaying some components, I've tried everything but it's not working [closed]
So I have this resume builder web app project, and it has an experiences section. In the experiences, I have main experience and additional experiences. Whereby in a form, a person enters their experience, and if they have additional experiences, they click the "additional experiences" button and add more experiences. However when I visit preview page, the additional experiences are not displaying, only the main experiences are displaying. models.py: class experience(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) position = models.CharField(max_length=200) company = models.CharField(max_length=200) startdate = models.DateField() enddate = models.DateField() roles = models.TextField(max_length=500) is_main_experience = models.BooleanField(default=False) views.py: # Create experiences @login_required def experience_v(request): if request.method == 'POST': position = request.POST['position'] company = request.POST['company'] startdate = request.POST['startdate'] enddate = request.POST['enddate'] roles = request.POST['roles'] main_experience = experience(user=request.user, company=company, position=position, startdate=startdate, enddate=enddate, roles=roles) main_experience.is_main_experience = True main_experience.save() return redirect('education') else: form = ExperienceForm() return render(request, 'experience.html', {'form': form}) # Create additional experiences def addexperience_v(request): if request.method == 'POST': additional_experience_positions = request.POST.get('additional_experience_position') for i in range(len(additional_experience_positions)): additional_experience_position = request.POST.get('additional_experience_position[' + str(i) + ']') additional_experience_company = request.POST.get('additional_experience_company[' + str(i) + ']') additional_experience_startdate = request.POST.get('additional_experience_startdate[' + str(i) + ']') additional_experience_enddate = request.POST.get('additional_experience_enddate[' + str(i) + ']') additional_experience_roles = request.POST.get('additional_experience_roles[' + str(i) + ']') additional_experience = experience.objects.create( user=request.user, position=additional_experience_position, … -
HTTPConnectionPool Max retries exceeded with url" Error in Python Selenium
I have a web application where users can perform searches on specific retailers and view the results in tables. When two users start searching on t:he same retailer at the same time, after a while, I receive an error message saying HTTPConnectionPool(host='localhost', port=57640): Max retries exceeded with url: /session/9b99c06c009ea88cba5295bd6fb3725a/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000021B3ED66310>: Failed to establish a new connection: [WinError 10061])) (Sometimes I also receive InvaliedSessionIdException at /search/) If the retailers being searched are not the same, the program works fine. It also works fine if the searches don't start or end at almost the same time. Python Selenium Code: def standart_analysis(self, product_keys:list[str], category:str,search_method:int=0, img_method:int=0, goal:int=50, sleep_time:float=1): """ It searches for the given product codes in the given retails and analyzes the information it finds. * product_keys: The products from which information will be obtained in the search and analysis should be given as a list of strings. * category: Category type of products to be searched. ----------- * search_method '0': Google search with Request library * search_method '1': Google search with Google library * search_method '2': Google search with Selenium Webdriver * search_method '3': Search in Retail ----------- * img_method '0': Take screenshot * img_method '1': Download … -
django-ses: Connect timeout when using django.core.mail
I am using django-ses==3.4.1 to send email via django.core.mail and both send_mail() and EmailMessage() get the connection timeout after one minute: botocore.exceptions.ConnectTimeoutError: Connect timeout on endpoint URL: "https://email-smtp.eu-central-1.amazonaws.com/ Using this configuration in settings.py according to the instructions on https://pypi.org/project/django-ses/ EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_USER = 'my-verified@email' AWS_SES_ACCESS_KEY_ID = '-my-access-key-' AWS_SES_SECRET_ACCESS_KEY = '-my-secret-access-key-' AWS_SES_REGION_NAME = 'eu-central-1' AWS_SES_REGION_ENDPOINT = 'email-smtp.eu-central-1.amazonaws.com' Where I use the variable AWS_SES_USER as from_email while calling email = EmailMessage(subject, message, from_email, recipient_list) email.content_subtype = 'html' email.send() I have also tested if the SES works without Django, i.e. simply using smtplib and it does. The working example derived from https://realpython.com/python-send-email/#option-2-using-starttls smtp_server = "email-smtp.eu-central-1.amazonaws.com" port = 587 # Create a secure SSL context context = ssl.create_default_context() # Try to log in to server and send email try: server = smtplib.SMTP(smtp_server,port) server.ehlo() # Can be omitted server.starttls(context=context) # Secure the connection server.ehlo() # Can be omitted server.login(AWS_SES_ACCESS_KEY_ID, AWS_SES_SECRET_ACCESS_KEY) message = """\ Subject: Test SES This message is sent from Python.""" receiver_email = 'my-recipient@email' server.sendmail(AWS_SES_USER, receiver_email, message) I have tried changing the parameters in settings.py in many ways, but without success. -
Is there any workaround to get celery task result if celery result backend is disabled?
I need to get a result of celery task but there is no CELERY_RESULT_BACKEND in the project I'm working on. | -------------- celery@e465919cc343 v5.2.3 (dawn-chorus) | --- ***** ----- | -- ******* ---- Linux-5.19.0-43-generic-x86_64-with-glibc2.31 2023-06-13 18:45:02 | - *** --- * --- | - ** ---------- [config] | - ** ---------- .> app: cms:0x7feb41db9490 | - ** ---------- .> transport: redis://redis-xxxxx:6379/0 | - ** ---------- .> results: disabled:// | - *** --- * --- .> concurrency: 8 (prefork) | -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) | --- ***** ----- It means an expression like task = my_task.delay(keyword=domain).get() won't ever work. What can I do? Is there any workaround? Everything I tried failed to work. It seems that it's impossible according to Celery documentation. -
How to write/mock testcases for uidb64 and tokens in DRF
I'm trying to verify user once user signup is done. I'm not sure how i can mock the uidb64 and token fields here. Can I get help with some mock test case here ? I have views.py class VerifyUserEmailAPIView(generics.GenericAPIView): serializer_class = EmailVerificationSerializer def patch(self, request): serializer = self.serializer_class(data = request.data) if serializer.is_valid(): user = serializer.validated_data user.is_verified = True user.save() return Response(status = status.HTTP_200_OK) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py class EmailVerificationSerializer(serializers.Serializer): uidb64 = serializers.CharField(min_length = 1, max_length = 20) token = serializers.CharField(min_length = 10, max_length = 100) class Meta: fields = ['uidb64', 'token'] def validate(self, attrs): attrs = super().validate(attrs) uidb64 = attrs.get('uidb64', '') token = attrs.get('token', '') pk = urlsafe_base64_decode(uidb64).decode() if not pk.isnumeric(): raise ValidationError("Invalid type received for user id") if not User.objects.filter(pk = pk).exists(): raise ValidationError("Unable to find user") user = User.objects.get(pk = pk) isTokenValid = account_activation_token.check_token(user, token) if not isTokenValid: raise ValidationError("Invalid or expired token") return user -
Understanding PromQL in grafana dashboard
I am trying out django dashboards for grafana. I imported a django dashbord from grafana.com. It has following panel: (I have greyed out my app view names) The PromQL query is as follows: topk(20, (1 - (sum(max_over_time(django_http_requests_latency_seconds_by_view_method_bucket{app=~"^$application$",le="$threshold"}[$__range]) / ignoring(le) max_over_time(django_http_requests_latency_seconds_by_view_method_count{app=~"^$application$"}[$__range])) by (method, view) / count(present_over_time(django_http_requests_latency_seconds_by_view_method_count{app=~"^$application$"}[$__range])) by (method, view))) > 0.0099) Also, the bar gauge does not change as long as I select "Last X", i.e. from "Last day" to "Last Year". Q1. Is it because all data is generated in last day it is convered in "Last Year" and the query takes Max over whole range? Q2. Can someone help me understand this PromQL? Is it returning slowest view in given time range? Q3. Also what is ">1s" in its title bar? -
Vue.JS + Django issue, it wouldn't let me update my userprofile from the dashboard(I get no errors, yet my database doesn't update)
So I am working on this time tracking app for myself, to learn Django and Vue.js, I found a tutorial from Code with Stein. I got stuck at editing the profile part from the tutorial. I get no errors, yet there are no changes made to my username or email(the changes don't even apply to my admin dashboard or database). The thing is that I get no error, which leaves me completely in the dust. I used Python, Django, Vue.JS, and soon SaaS if I find a resolution for this issue. So here is my code in project/apps/userprofile/templates/userprofile/signup.html {% extends 'core/base.html' %} <!-- Extends the base template 'base.html' --> {% block title %}Sign Up | {% endblock %} <!-- Sets the page title to "Sign Up" --> {% block content %} <!-- Begins the content block --> <section class="hero is-medium is-light is-bold"> <!-- Creates a hero banner --> <div class="hero-body"> <div class="container"> <h1 class="title">Sign Up</h1> <h2 class="subtitle">To get started you need an account.</h2> </div> </div> </section> <div class="columns" id="signup-app"> <!-- Creates a container with two columns --> <div class="column is-6 is-offset-3"> <form method="post" action="." class="mt-6" v-on:submit="validateForm" novalidate> <!-- Sign-up form --> {% csrf_token %} <!-- Generates a CSRF token input … -
Django websocket - path not found
I looked everywhere in Stackoverflow discussions. I can't resolve my issue with django websocket. I'm working with React client side and Django server side. Following my code: asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from flow import consumers os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject_project.settings') import flow.routing application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(flow.routing.websocket_urlpatterns) }) setting.py ASGI_APPLICATION = 'agonet_project.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'django_celery_results', 'django_dump_die', 'django_extensions', 'channels', 'flow', 'authentification', 'rest_framework', 'rest_framework_simplejwt.token_blacklist' ] flow/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class MyConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data=None, bytes_data=None, **kwargs): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.send(text_data=json.dumps({'message': message})) flow/routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from django.core.asgi import get_asgi_application from . import consumers websocket_urlpatterns = [ path('ws/flow/', consumers.MyConsumer.as_asgi()), ] WebSocket.js const ws = new WebSocket('ws://127.0.0.1:8000/ws/flow/'); ws.onopen = () => { console.log('WebSocket connection opened.'); ws.setRequestHeader('Host', window.location.host); // Send the message once the connection is open ws.send(JSON.stringify({ message: 'Hello, server!' })); }; ws.onmessage = (event) => { const message = JSON.parse(event.data); console.log('Received message:', message); }; ws.onclose = () => { console.log('WebSocket connection … -
DJANGO non nullable field migration issue
Im a DJANGO/python novice. I have added two fields so that changes in enterprise and DJANGO admin are logged as who updated them and what date it was updated. the constraint is that these fields cannot be null. my changes are as follows: class Enterprise(models.Model): last_updated = models.DateTimeField( null=False, auto_now=True, verbose_name='Last Updated Date', help_text="Points to time this was last modified", ) last_updated_by = models.CharField( null=False, max_length=100, default='N/A', ) AND class EnterpriseAdmin(admin.ModelAdmin): model = Enterprise readonly_fields = ( "last_updated", "last_updated_by",) fieldsets = ('last_updated','last_updated_by',), however when I run pytest, I'm receiving an error: null value in column "last_updated" violates not-null constraint. when I ran makemigrations, Django prompted me to add a default for last_updated: You are trying to add a non-nullable field 'last_updated' to enterprise without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) so I chose option '1' and default=datetime.datetime(1970, 1, 1, 0, 0),preserve_default=False, is added to last_updated in my migration file. migrations.AddField( model_name='enterprise', name='last_updated', field=models.DateTimeField(auto_now=True, default=datetime.datetime(1970, 1, 1, 0, 0), help_text='Points to time this was last modified', verbose_name='Last Updated Date'), preserve_default=False, ), I was under the impression … -
Tastypie queries for all fields, is it possible to only SELECT specific fields
With tastypie you create a resource for your Django model and point the queryset at your model.objects.all(). I was expecting "fields" to allow me to declare which fields i want to return: https://django-tastypie.readthedocs.io/en/latest/resources.html?highlight=exclude#fields This does work, but the sql query generated doesnt care it selects all fields. For me this seems a bit bit pointless if im querying a large table and only want to return 2 columns, and not the other 8. Hopefully I've missed something obvious in the TP documentation. If anyone has any pointers/ideas that would be great -
creating tags during post creation works, but using existing ones don't - possible problem with serializer or something else
I am trying to write a code that will make it able to create tags during creating post and use tags created by urself, other users earlier. I think thats a common approach. This test works without a problem, because it creates a tag during post creation: class TagTests(TestCase): """Tests for tags.""" def setUp(self): self.client = APIClient() self.user = User.objects.create_user(email='mail@example.com', password='password123') self.client.force_authenticate(self.user) self.admin = User.objects.create_superuser(email='admin@example.com', password='password123') self.post = Post.objects.create(user=self.user, text='Test post') self.tag1 = Tag.objects.create(user=self.user, name='Existing Tag 1') self.tag2 = Tag.objects.create(user=self.user, name='Existing Tag 2') self.url_post = reverse('posts-list') def test_create_tags_during_post_creation(self): """Test creating tags during post creation.""" payload = {'text': 'Test', 'tags': [{'name': 'tag1'}, {'name': 'tag2'}]} res = self.client.post(self.url_post, payload, format='json') post_id = res.data['id'] post = Post.objects.get(id=post_id) tags = post.tags.all() tag_names = set(tag.name for tag in tags) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertIn('tag1', tag_names) self.assertIn('tag2', tag_names) However I cannot get my next test to work, because it returns error 400 and response is {'tags': [{'name': [ErrorDetail(string='tag with this name already exists.', code='unique')]}, {'name': [ErrorDetail(string='tag with this name already exists.', code='unique')]}]} def test_create_post_with_existing_tags(self): """Test creating post with existing tags.""" payload = {'text': 'Test post creating with existing tags', 'tags': [{'name': 'Existing Tag 1'}, {'name': 'Existing Tag 2'}]} res = self.client.post(self.url_post, payload, format='json') print(res.data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) post_id = … -
Django: Attach passed id to instance?
I am trying to attach the id I pass through my query string to an instance of a form field user_id. I have tried many different ways and can't seem to get it to work. The id IS being passed successfully. urls for how I passed it (tried int: still didn't work) path('customer_note/<id>', views.customer_note, name='customer-note'), views def customer_note(request, id): obj_instance = Customer.objects.get(user_id= id) obj_instance.user_id = id obj_instance.save(update_fields=['user_id',]) #this is the start of the form save. I couldn't figure out how to do it here either. if request.method =="POST": customer_form = CustomerForm(request.POST) if customer_form.is_valid(): . . . Thank you I have tried using request.user.customer.id and attaching it. I have tried update() in various ways. -
getting exception in working process in gunicorn with django (on digitalocean)
having trouble deploying django project with gunicorn and ningix on digital ocean. I have already created the droplet and am following the steps as mentioned in their official step by step guide but am stuck with these errors This is the error im getting when i run this gunicorn --bind 0.0.0.0:8000 wsgi:app [2023-06-13 11:58:41 +0000] [68713] [INFO] Starting gunicorn 20.1.0 [2023-06-13 11:58:41 +0000] [68713] [INFO] Listening at: http://0.0.0.0:8000 (68713) [2023-06-13 11:58:41 +0000] [68713] [INFO] Using worker: sync [2023-06-13 11:58:41 +0000] [68714] [INFO] Booting worker with pid: 68714 [2023-06-13 11:58:41 +0000] [68714] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/dist-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'wsgi' [2023-06-13 11:58:41 +0000] [68714] [INFO] Worker … -
How can I solve the problem please suggest me?
Even I am also getting same error. After adding UUID in cart model, It is showing the (django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: …LE “store_cart” ALTER COLUMN “id” TYPE uuid USING “id”::uuid) error. I deleted migration file and again migrate it but still I am facing this issue. I am using sqlite3 database so should I use postgresql database, please give me hint for it. Thank you!! What is solution please answer for it? -
django error when trying to migrate, I tried deleting the app but still not working
raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration lead.0004_lead_team dependencies reference nonexistent parent node ('team', '0001_initial') py manage.py migrate team zero raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration lead.0004_lead_team dependencies reference nonexistent parent node ('team', '0001_initial') manage.py migrate team [62024:0613/154507.114:ERROR:cache_util_win.cc(20)] Unable to move the cache: Access is denied. (0x5) [62024:0613/154507.114:ERROR:disk_cache.cc(205)] Unable to create cache -
Django login function not working when server run on host 0.0.0.0
def UserLogin(request): if request.method == 'POST': try: username = request.POST["username"] cif = request.POST["cif"] password = request.POST["password"] user = Users.objects.get(username=username) if user : if user.role == '001': login(request, user) return redirect('webapp:bank-details') elif user.role == '002': login(request, user) json = { "service": "CORE_BANKING_LOGIN", "request": { "username": f"{username}", "cif": f"{cif}", "password": f"{password}", "channelType": "CORPORATE" } } this is the code ive been using to log users in when using the localhost to run the server but ive discovered that when i run it using the host 0.0.0.0 i couldnt log in anymore, can someone help or explain why i tried specifying the authentication backend in my settings but that didnt help -
Mixed Content warning over http
I've deployed my django rest framework project, it works fine and running on docker, the site is loading over https but images, videos are being loaded over http, and getting Mixed content warning, and browser also showing insecure even if actual site has ssl certifate. I searched for related questions but didn't solve my problem. mysite.conf server { server_name cp.mysite.com; location / { proxy_pass http://127.0.0.1:3180; # docker container listens here proxy_read_timeout 3600s; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/cp.mysite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/cp.mysite.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = cp.mysite.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name cp.mysite.com www.cp.mysite.com; listen 80; return 404; # managed by Certbot } docker nginx.conf upstream django { server django:5000; } server { listen 80; location / { proxy_pass http://django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Host $host; client_max_body_size 100M; proxy_redirect off; } location /media/ { alias /usr/share/nginx/media/; } } settings.py SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = "DENY" SECURE_PROXY_SSL_HEADER = … -
Sending files through Socket from Javascript to Django
I am trying to add a feature in my chat app(with Django-channels) that allows users sending files. I am searching for a way that sends files from Javascript to Django. I am using this code in Javascript : // Access the file using fileInput.files[0] var file = fileInput.files[0]; // Read file data using FileReader API var reader = new FileReader(); reader.onload = function(event) { var fileContent = event.target.result; // Send file data via WebSocket var data = { 'command': 'file_included_message', 'file': { 'name': file.name, 'content': fileContent, }, }; chatSocket.send(JSON.stringify(data)); }; reader.readAsDataURL(file); and this code for the consumer(in Django): file_content = file_data['content'] # Base64 encoded file content # Save the file to a temporary location file_content_decoded = base64.b64decode(file_content) # Save the file to a temporary location file_path = os.path.join(settings.MEDIA_ROOT, str(file_name)) with open(file_path, 'wb') as file: file.write(file_content_decoded) -
how to extand two header file in same template before login other and after login another header file
how to extand two header file in same template before login other and after login another header file {% if not request.user.is_authenticated %} {% extends 'portal/v1/base-template.html' %} {% else %} {% extends 'portal/v1/auth/base-template.html' %} {% endif %} -
What is currently a good approach to input masks when using Django model forms?
I'm trying to find out what the best current approach is for input masks in Django when using model forms. I have tried: https://dobsondev.com/2017/04/14/using-jquery-mask-to-mask-form-input/ and https://imask.js.org/guide.html#masked-number but both approaches require that I catch the postback and remove the masking to prevent the model form validation from failing. I can't help but wonder if there is a more eloquent approach/plugin. -
Unit Test for a QuerySet class
I need to unit test a queryset class. I don't have a chance to refactor the class. class MyQuerySet(models.QuerySet): def my_method(self, my_flag=True): ...some logic... return self.annotate(....some logic here...) Since my_method uses self.annotate and import within the method, things get harder. Should I extend this class in unit test class? class MyQuerySetTestCase(TestCase, MyQuerySet): Or should I mock whole QuerySet? @mock.patch("path.to.MyQuerySet") class MyQuerySetTestCase(TestCase, query_set_mock): query_set_mock = QuerySet() How should I approach to this code? -
How to deal with multi-page react application with django?
Has anyone built a multi page react app using ReactJS, Django and Django-REST. I have a good idea on how to achieve it. But the problem i want to build a multi html page app with ReactJS. There will be some endpoints which deliver HTML and others which deliver API data. For delivering HTML, i will use Django templates and for API data i will use DJango-REST. I can make a GET request for an HTML page from a react component with Axios, but the problem is i will need a way to render this HTML response from the frontend. My plan is to rewrite the DOM using document.write(ReturnedHTML). Will there be any potential performance problems with this approach? The returned HTML file will be extremely simple with the only difference being the React files being imported. Have not started yet. Asking for design approaches. -
Any one can help me in Gmail Push notifications
I am woriking on email client app in django i want to enable realtime notification in my app i had use my service accout credential and topic name but when i enable it rase an excepion as preconditation failed this is my code def setup_gmail_push_notification(): SCOPES = ['https://www.googleapis.com/auth/gmail.modify'] credentials = service_account.Credentials.from_service_account_file('automate-38413-b49e282b6eeb.json',scopes=SCOPES) # Create the Gmail API service service = build('gmail', 'v1', credentials=credentials) # Define your webhook URL webhook_url = 'https://1ad5-182-178-213-15.in.ngrok.io/Gamil/Login/gmail-webhook/' # Create the push notification watch request request_body = { 'labelIds': ['INBOX'], # Specify the label(s) to watch for notifications 'topicName': 'projects/automate-83413/topics/gmail-push-notification', 'labelFilterAction': 'INCLUDE', 'pushConfig': { 'pushEndpoint': webhook_url, 'payloadFormat': 'FULL' } } try: # Send the watch request # request = service.users().watch(userId='me', body=request_body) request = {'labelIds': ['INBOX'],'topicName': 'projects/automate-383413/topics/gmail-push-notifications'} service.users().watch(userId='me', body=request_body).execute() response = request.execute() # Handle the push notification setup response print('Gmail push notification setup successful:', response) except Exception as e: # Handle authentication errors return(e) -
Django custom model field do work after save
I've got a custom model field class VaultField(CharField): which is used like: class MyClass: secret = VaultField(max_length=200, blank=True) It should save that field's value to HashiCorp Vault and store the Vault path in the database. That's all nice and easy when the Vault path is static, but what I'd like to do is to build the Vault path based on the model instance ID. But none of the methods from_db_value, to_python, get_prep_value are being called post save and therefore don't have any data about the instance. Is there any way to run field code post save? To get the path /fields/[my-class-name]/[my-class-id].