Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot import django-smart-selects
I wanted to use the django smart select library to create related dropdowns. I did everything as indicated in the library documentation, but an error occurs: import "smart_selects.db_fields" could not be resolved Pylance(reportMissingImports) [Ln2, Col6] Even when I enter "import ..." the library itself already glows gray, as if it does not find it. This is what my INSTALLED_APPS in settings.py looks like: INSTALLED_APPS = [ 'routes_form.apps.RoutesFormConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'smart_selects', ] USE_DJANGO_JQUERY = True This is my urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('form/', include('routes_form.urls')), path('admin/', admin.site.urls), path(r'^chaining/', include('smart_selects.urls')), ] ...and my model.py: from django.db import models from smart_selects.db_fields import ChainedForeignKey I tried to find a solution to the problem, looked for possible options. That is why I already changed from `JQUERY_URL = True` to `USE_DJANGO_JQUERY = True`. Errors (six) I did not take off. I have only this...: `import "smart_selects.db_fields" could not be resolved Pylance(reportMissingImports) [Ln2, Col6]` I would be incredibly grateful even for trying to help. -
HOW DO I MAKE A TEACHER VIEW ASSIGNMENTS OF STUDENTS BELONGING TO HIS/HER CLASS ONLY?
Hi Guys i need help im developing a django software whereby students submit assignments online on a school platform ,How do i make a teacher view assignments for his specific claass only Right now my software is submiting assignments , and viewing all the assignments even those of students not belonging to his/her class .So i expect the software to view only assignments of students belonging to the class of logged in teacher -
can't get the back end data when I run a react app from other device
I have a project with react on the front and django/python and postgres on the back Everything goes ok on the computer, but if I run it from another device, in the same network, the data can’t be loaded, it says axios network error I found my Ip with ipconfig, suppose it's 192.xxx.xxx.xxx, then I set in the mobile device http:// 192.xxx.xxx.xxx:3000, it runs the application but the data can't be found there, it says AxiosError: Network Error My computer recognizes the wifi network 2.4, then I connect the phone to the 2.4 network In the axios call, I set the address as: const response = await axios.get( `http://127.0.0.1:8000/api/v1/whole_menu/${restaurantId}` ); (I’m not using localhost) But I still get the network error in the phone, but in the computer, everything is ok What could it be? Thanks in advance Rafael -
ensure_csrf_cookie method decorator not setting CSRF token in browser cookies tab
I'm working on a project using Django as API backend (hosted on localhost:8000) and React (hosted on localhost:3000) as frontend. My plan is to host them on different servers in production as well. I'm currently trying to set the CSRF token in the browser cookies tab using the "ensure_csrf_cookie" method decorator. While the javascript API call seems to work and returns the response, no cookie is set in my cookie tab (tested in different browsers). However, the weird thing is that when I type in the CSRF token URL directly in the browser, the cookie is set. This leads me to believe it's not working due to some cross-origin issues. So I've tried many different settings in my settings.py file without success. Django View: @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response ({ "success": "CSRF cookie set"}) React: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } async function … -
DRF tries to create User object when used in nested serializer
DRF docs says that "By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be save."<< In general this is true except for one case. When User class is a nested object in serializer. Use case is to add existing user to newly created organization. Consider my simple example where I noticed that issue: views.py class UserOrganizationViewSet(viewsets.ModelViewSet): # authentication_classes = (JwtAuthentication, SessionAuthentication) # permission_classes = (permissions.JWT_RESTRICTED_APPLICATION_OR_USER_ACCESS,) serializer_class = UserOrganizationSerializer queryset = UserOrganization.objects.all() models.py: class UserOrganization(models.Model): name = models.CharField(max_length=256) users = models.ManyToManyField(User, blank=True, related_name="user_organizations", through='OrganizationMember') def __str__(self): return self.name class OrganizationMember(models.Model): organization = models.ForeignKey(UserOrganization, on_delete=CASCADE) user = models.ForeignKey(User, on_delete=CASCADE) joined = AutoCreatedField(_('joined')) serializers.py: First version - User class has its own simple serializer and it is used as nested serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ['username'] class UserOrganizationSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, required=False) class Meta: model = UserOrganization fields = ['id', 'name', 'users'] read_only_fields = ['id'] Is this case I am able to fetch data via GET method (Organization created through admin panel): But when I am trying to create organization I am … -
i can't add domain name to server
i create Django one click drophlet on Digitalocean. i configure my website and i want add domain name. i configure my nginx and i add to server domain name . i also add nameservers on my domain registrant and configure domain name on digitalocean but still didn't work. here is my configuration. upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name recourse.ge www.recourse.ge; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/django_project/static; } upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0;} } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python3/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } I add nameservers to my domain registrant. i add also A record to my digitalocean domain name. i configure nginx and add my domain name to nginx configuration and i add in settings.py Allowed host my domain name. -
How do I use Django's built in password reset function?
I am using the following code to use Django's built in password reset functions. Everything seems to work for some email addresses but not for others. I know for sure that I am having difficulties with @btopenworld.com addresses. I have read other places saying that the user accounts need to have functional passwords set up. I have tried the same user account with different passwords (some reset emails get delivered, some do not). Any ideas on how to get this working more consistently? In my login template file: <div class="mt-4"> <div class="d-flex justify-content-center login_container"> <a href ="{% url 'reset_password' %}" class="btn btn-warning" >Create / Reset Password</a> In my urls.py file: path('reset_password/', auth_views.PasswordResetView.as_view(template_name="accounts/password_reset.html"), name="reset_password"), In the password_reset.html file: <p>Enter the email address used to create your account, and we’ll email instructions for setting a new password.</p> <form method="post"> {% csrf_token %} {{form}} <input type="Submit" name="Send email"> </form> -
How to call a function after full save of an object in Django
Currently in my project I use different receivers with the post_save signal successfully. However, in one of them I need to perform an update assuming it has already been done, however since the post_save request is fired inside the save function, that updated data is still not reflected in a queryset request. In this case I can use exclude to ignore the data from the present record but I would like to know a cleaner way to do this within the Django schema without resorting to Celery, threading, etc. Any suggestions? -
using rest_framework_simplejwt.authentication - token expire after short time, and then the user have to login again
I new in WEB world and Authentication, and I got some problems. I try to set JWT Authentication with Django and React, but even after I set this in django: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=20) } In the frontend side (my react app), I automatically disconnect after something like 30 min's, and then I have to login again (and I set life time to 10 days!). So im not sure what going there, and why the default value to 'ACCESS_TOKEN_LIFETIME' is 5 min? who want to keep login and login again every 5 minutes? I think I don't understand something or miss something. I've given up already and would appreciate some help - or some diffrent way to do Authentication with django-react app. Just in case, here more configurations that are related: DEFAULTS = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "SIGNING_KEY": settings.SECRET_KEY, "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "JTI_CLAIM": "jti", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } … -
Using some html-to-pdf tool to get invoice.pdf
I want to use other libraries than pdfkit since wkhtmltopdf doesn't work for heroku. I want to replace some of these lines for usage with other libraries. pls guide me! as far as I know, only the generatePDF part needs tweaking. views.py: from django.shortcuts import render, redirect, get_object_or_404, reverse from django.template.loader import get_template from django.http import HttpResponse from django.views import View from .models import LineItem, Invoice from .forms import LineItemFormset, InvoiceForm import pdfkit class InvoiceListView(View): def get(self, *args, **kwargs): invoices = Invoice.objects.all() context = { "invoices": invoices, } return render(self.request, 'invoice/invoice-list.html', context) def post(self, request): # import pdb;pdb.set_trace() invoice_ids = request.POST.getlist("invoice_id") invoice_ids = list(map(int, invoice_ids)) update_status_for_invoices = int(request.POST['status']) invoices = Invoice.objects.filter(id__in=invoice_ids) # import pdb;pdb.set_trace() if update_status_for_invoices == 0: invoices.update(status=False) else: invoices.update(status=True) return redirect('invoice:invoice-list') def createInvoice(request): """ Invoice Generator page it will have Functionality to create new invoices, this will be protected view, only admin has the authority to read and make changes here. """ heading_message = 'Formset Demo' if request.method == 'GET': formset = LineItemFormset(request.GET or None) form = InvoiceForm(request.GET or None) elif request.method == 'POST': formset = LineItemFormset(request.POST) form = InvoiceForm(request.POST) if form.is_valid(): invoice = Invoice.objects.create(customer=form.data["customer"], customer_email=form.data["customer_email"], billing_address=form.data["billing_address"], date=form.data["date"], due_date=form.data["due_date"], message=form.data["message"], ) # invoice.save() if formset.is_valid(): # import pdb;pdb.set_trace() … -
Add user to group in signal post_save
I want to add a user to a group after the user object is saved. Each user has a user type corresponding to the group the user belongs to. For example, if the user_type is 2, then the user belongs to Group_3, and so on. This is my code: class User(AbstractBaseUser, PermissionsMixin): """ Custom user model """ USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student')) email = models.EmailField( ("Email Address"), max_length=255, unique=True, help_text="Ex: example@example.com", ) eec = models.ForeignKey( EEC, on_delete=models.CASCADE, null=True, related_name='eec',blank=True) is_staff = models.BooleanField(("Staff status"), default=False) is_active = models.BooleanField(("Active"), default=True) date_joined = models.DateTimeField(("Date Joined"), auto_now_add=True) last_updated = models.DateTimeField(_("Last Updated"), auto_now=True) user_type = models.IntegerField(default=1, choices=USER_TYPE) lastName = models.CharField(default='', max_length=250) firstName = models.CharField(default='', max_length=250) objects = UserManager() USERNAME_FIELD = "email" def __str__(self): return self.email class Teacher(models.Model): admin = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == 1: Admin.objects.create(admin=instance) if instance.user_type == 2: try: Teacher.objects.create(admin=instance) g1 = Group.objects.get(name='teacher') instance.groups.add(g1) except: print("Exception") if instance.user_type == 3: Student.objects.create(admin=instance) Basically, when I save the user model with a user type of 2, the group does not get updated -
how to delete an object in modelViewset in DRF?
I am doing a project in DRF and using modelviewset, my object has two boolean fields and two users as foreign keys, now i want to show the object only to those users and if both of them set their correspond's boolean attribute to True then the object will be deleted i'm handling the logic of some code in custompermissions.py but i dont know if to handle the deletion of the object in there too or in the view, and since i need to verify if the current user is either one of the users i have some logic to do, i dont know what type of request i should permit also becuase DELETE will delete the object and i need to delete only in case both values are true, and i can do it in a get but then i will have to spllit the show and delete into 2 diffrent routs. can someone recommend what is best for me to do? i want to show and delete an object in a spcifec case -
How to create dynamic delete formset?
I have a formset in the html. I added a addMore button to add a form. Now i want to create dynamically remove button in html, but i am lack experience of js with DOM. How to make delete button dynamically using js? html {% block isi %} <!-- INFORMASI ACARA --> <div class="notification is-light p-1 has-text-centered mt-4"> INFORMASI ACARA </div> <div class="columns is-multiline"> {% if formset6 %} {{ formset6.management_form }} <div class="column is-12"> <div id="ingredient-form-list6"> {% for form in formset6 %} <div class="ingredient-form6 mb-3"> {% for field in form.visible_fields %} {{ field.label_tag }} {{ field }} {% for error in field.errors %} <p class="help is-danger">{{ error }}</p> {% endfor %} {% endfor %} <div class="is-hidden"> {% for field in form.hidden_fields %} {{ field.label_tag }} {{ field }} {% for error in field.errors %} <p class="help is-danger">{{ error }}</p> {% endfor %} {% endfor %} </div> </div> {% endfor %} </div> </div> <div id="empty-form6" class="is-hidden">{{ formset6.empty_form }}</div> {% endif %} </div> <button id="add-more6" type="button" class="button is-small is-outlined pd-1 mb-4">Tambah</button> {% endblock %} js const addMoreBtn6 = document.getElementById('add-more6') const totalNewForms6 = document.getElementById('id_acara-TOTAL_FORMS') if (addMoreBtn6) { addMoreBtn6.addEventListener('click', add_new_form6) } function add_new_form6(event) { if (event) { event.preventDefault() } const currentIngredientForms6 = document.getElementsByClassName('ingredient-form6') const … -
Saving a JSON object as the entire model in DJANGO
I want to save the information that my front sends me in the database (I receive a JSON), the problem is that there are foreign keys in the model and these may or may not be filled and when I try to save some data with the empty FK I receive the 'matching' error query does not exist.' or other errors related to the 'key' not existing in the database. What occurs to me is to remove it from the front before it is sent to DJANGO and save the object as such but I don't know if it's possible, if you also have another solution I would greatly appreciate it Add def agregarIniciativa(request): if request.user.is_authenticated: if request.method =='POST': try: data = json.load(request) iniciativa = Iniciativa( iniciativa = data['nombre'], fecha_inicio = data['fecha_inicio'], fecha_final = data['fecha_final'], canal=Canales.objects.get(id=int(data['canal'])), territorio = data['territorios'], audiencia = AudienciaDirigida.objects.get(id=int(data['audiencia'])), bigbet = BigBet.objects.get(id=int(data['bigBet'])), marca = Marcas.objects.get(id=int(data['marca'])), fgp = float(data['fgp']), objetivo = data['objetivo'], call2action = data['call2Action'], dialogo_valor = data['dialogoValor'], cobertura = data['cobertura'], volumen_datos = data['volumen'], kpi_medicion = data['kpi'], inversion_datos = data['inversion'], beneficio_datos = data['beneficio'], volumen_total = int(data['total_vol']), inversion_total = int(data['total_inv']), beneficio_total = int(data['total_ben']), marcas = data['marcas'], fgp_datos = data['fgpDatos'] ) iniciativa.save() return JsonResponse({ "msg": "Guardado" }) except Exception as … -
How to set permissions for HR and TL for request approval in django rest framework
I'm working on HRMS application in django rest framework I want to set permissions for Hr and Team leader to approve leave request of employees. How can i achieve. If it's admin approval i can easily do that. But since it's hr and tl i should manually create that. How can i achieve it? Also how to request a leave and how tl approved and it can be forwarded to hr for approval? -
I am getting the following error in my Django file. Can someone help me out?
I am getting the following erroR. Can someone look into it and help me out: File "C:\Users\myUsrename\AppData\Roaming\Python\Python310\site-packages\django\contrib\gis\gdal\libgdal.py", line 69, in <module> lgdal = CDLL(lib_path) File "C:\Program Files\Python310\lib\ctypes\__init__.py", line 374, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 127] The specified procedure could not be found -
Get request followed by a Post request in Django, How to?
through my GET request here I can get some mp3 files and download them, Now I would like to pass those files to an other API as a payload. Can you do this in one call ? here is the example : class UserSearchView(APIView): def get(self, request, link): url = config('BASE_URL') querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request("GET", url, headers=headers, params=querystring) name = response.json()['url'] filename = name.split('/')[-1] doc = requests.get(name) with open(filename, 'wb') as f: f.write(doc.content) wave = f.name base_path = '/Users/cyhl/Desktop/TrackID/backend/' absolute_path = base_path + wave sound = AudioSegment.from_mp3(absolute_path) # split sound in 20-second slices and export for i, chunk in enumerate(sound[::20000]): with open("sound-%s.mp3" % i, "wb") as f: chunk.export(f, format="mp3") return JsonResponse(status.HTTP_200_OK) **Not sure how to proceed from here, I would like to loop from this files I've just downloaded and pass them as a payload ** **def post(self, request) : url = config('BASE_URL') payload = "" headers = { "content-type": "multipart/form-data; boundary=---011000010111000001101001", "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request("POST", url, data=payload, headers=headers)** What is the best way to go here -
DRF always return not authenticated in Django rest framework fed on NextJS and Axios
After testing on postman i get the right response but when i pushed the code for the frontend guys, I get a report that it's always returning false... views.py # Check authentication status def check(request): data = {} if request.user.is_authenticated: data['response'] = 'user is authenticated' data['name'] = request.user.name data['email'] = request.user.email data['phone_number'] = request.user.phone_number data['id_user'] = request.user.id_user data['passed_kyc'] = request.user.passed_kyc else: data['response'] = 'user is not authenticated' return JsonResponse(data) -
Using the URLconf defined in myworld.urls
My directory index.html: <h1>Members</h1> <table border="1"> {% for x in mymembers %} <tr> <td><a href="update/{{x.id}}" style="decoration: none">{{x.id}}</a></td> <td>{{ x.f_name }}</td> <td>{{ x.l_name }}</td> <td><a href="delete/{{x.id}}">Delete</a></td> </tr> {% endfor %} </table> <p> <a href="add/" style="decoration: none">Add members</a> </p> update.html: <h1>Update member</h1> <form action="updaterecord/{{mymember.id}}" method="post"> {% csrf_token %} First Name:<br /> <input name="first" value="{{mymember.f_name}}" /> <br /><br /> Last Name:<br /> <input name="last" value="{{members.l_name}}" /> <br /><br /> <input type="submit" value="Submit" /> </form> members/url.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('add/', views.add, name='add'), path('add/addrecord/', views.addrecord, name='addrecord'), path('delete/<int:id>', views.delete, name='delete'), path('update/<int:id', views.update, name='update'), path('update/updaterecord/<int:id>', views.updaterecord, name='updaterecord'), ] myworld/urls.py: from django.contrib import admin from django.urls import include,path urlpatterns = [ path('members/', include('members.urls')), path('admin/', admin.site.urls), ] the url:http://127.0.0.1:8000/members/update error it might be a silly mistake or something but i cant just figure it out...help is appreciated!thanks -
how add custom fild to all objects of django model
i have db where is companies and custom users, i want add custom field for different companies. Example: user have only NAME, if company is "EXAMPLE": user have fields only NAME and AGE, elif "VIN": user have only NAME and SIZE and AGE and WORK, else: only name. How add this custom fields and update it. Thanks, sory for my English)) Company 1: name "+add field" company2: -name -age "+add field" company 3: -name -age -size "+add field" I try many to many, many to one, simple fields, dont work how i want. I wand many custom field how i can edit for every user -
Making a user to edit his/her data only in django admin
I am creating a website in which users can add details about him/her or remove them but I don't want to make a separate page in the front end for that... is there any way that I can only let the logged-in user edit his/her details only.. here is my models.py code from django.db import models from django.contrib.auth.models import User DEPARTMENTS = ( ('CSE', 'Computer Science and Engineering'), ('ECE', 'Electronics and Communication Engineering'), ('EEE', 'Electrical and Electronics Engineering'), ('ME', 'Mechanical Engineering'), ('CE', 'Civil Engineering'), ('R&A', 'Robotics and Automation'), ) class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=100) address = models.CharField(max_length=100) designation = models.CharField(max_length=100) department = models.CharField(max_length=3, choices=DEPARTMENTS, default='CSE') bio = models.CharField(max_length=1000) join_date = models.DateField() scholar_id_link = models.CharField(max_length=100) irns_link = models.CharField(max_length=100) image = models.ImageField(upload_to='display_pictures', blank=True) def __str__(self): return self.user.get_username()+ " " + self.department + " " + self.designation class WorkExperience(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE, default=1) place = models.CharField(max_length=100) designation = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() def __str__(self): return self.staff.user.get_username() + " " + self.place + " " + self.designation -
Database Query returning empty in test cases - Django
I have updated the Django version for my project from Django-2.2.16 --> Django3.2.14. But with this update, some of my test cases are failing and I cannot understand the reason for the failure. My test-case file: import json from os import access from unittest import mock from unittest.mock import patch import asyncio from app.models import UserProfile from django.test import TestCase, TransactionTestCase from requests.models import Response from services.check_status import check_status loop = asyncio.get_event_loop() @mock.patch("services.check_status.save_status") @mock.patch("services..check_status.send_wss_message") class TestUserStatus(TransactionTestCase): def setUp(self): super().setUp() self.account_id = 4 self.sim_profile = UserProfile.objects.create() def test_check_status_completed( self, mock_send_wss_message, mock_save_status, ): mock_save_status.return_value = {} send_wss_message_future = asyncio.Future() send_wss_message_future.set_result(True) mock_send_wss_message.return_value = send_wss_message_future loop.run_until_complete( check_status( self.sim_profile.id, ) ) self.assertTrue(mock_save_status.called) self.assertTrue(mock_send_wss_message.called) My pseudo check_status file is :- import logging from app.models import UserProfile, UserStatus from services.constants import WebsocketGroups from services.user.constants import USER from app.api.serializers import UserStatusSerializer from services.utils import send_wss_message, sim_states, log_activity logger = logging.getLogger(__name__) def save_status(**kwargs): status = UserStatus.objects.filter( status_id=kwargs.get("status_id") ).first() data = kwargs user_status_serializer = UserStatusSerializer(status, data, partial=True) if user_status_serializer.is_valid(): user_status_serializer.save() async def check_status( profile_id ): user_profile = UserProfile.objects.get(id=profile_id) login_token = get_login_token(user_profile) user_creds = env["user_api"] headers = USER["headers"] subscription_details = SimClient.get( USER["url"], headers ) transaction_status = subscription_details.json()["Status"] subscription_data = subscription_details.json()["Data"][0] transaction_status_details = subscription_data["TransactionStatusDetails"] error_message = "" status = "" if transaction_status … -
can't stop celery woker
I have a problem with celery worker. I need to start default celery worker but an error accurate. It says that already using this process mailbox! and when I try below command for kill process it says no processes found. ps auxww | grep 'celery worker' | awk '{print $2}' | xargs kill -9 I tried to kill process but could not kill it. In addition I use celery in django application. -
Django Graphene mutation deletes objects instead of update
There is a such mutation and a pretty simple update function, I expect it will only update one parameter of the object, then saves it. Actually, at the first request, it returns the expected response, but objects delete from DB. class PortfolioMutation(graphene.Mutation): class Arguments: portfolio_id = graphene.ID() visible = graphene.Boolean() portfolio = graphene.Field(PortfolioType) @classmethod def mutate(cls, root, info, portfolio_id, visible): portfolio = Portfolio.objects.get(pk=portfolio_id) portfolio.visible = visible portfolio.save() return PortfolioMutation(portfolio=portfolio) class UpdatePortfolio(graphene.ObjectType): """ Portfolios mutation """ update_portfolio = PortfolioMutation.Field() schema = graphene.Schema(query=QueryPortfolios, mutation=UpdatePortfolio) Exact request mutation UpdatePortfolio{ updatePortfolio(portfolioId: 1509, visible: false) { portfolio { name visible } } } Respnse { "data": { "updatePortfolio": { "portfolio": { "name": "High Yield Corporate Bonds", "visible": false } } } } Where I messed up? -
migration problem while hosting a django project on PythonAnywhere
I recently finished my django project and i switched my database from the local SQLite database witch django provides you to an online postgreSQL database provided by elephantSQL. Clearly, by entering my database credential in the setings.py file of my django project i am able to mugrate to my new database, localy(meaning that when i run my server on port 8000 it loads my data from the postgreSQL, but when i push my website to PythonAnywhere and try to run my migrations from the bash console of PythonAnywhere it throws out the following error:` django.db.utils.OperationalError: connection to server at "'USER'.db.elephantsql.com" ("DATABASE_IP"), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? ` I even changed my database Host from elephanSQL to nhost, but still it promps the same result.