Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to write unit test using pytest for django url
my url and function are as follows url path('drivers/', views.drivers, name='drivers'), views.py @login_required(login_url='/account/login') def drivers(request): drivers = Drivers.object.all() return render(request, "drivers.html", {'drivers': drivers}) I've just started learning unit testing. How do i write unit test to check my url is working as expected. -
Nasa API pass the data so slow
I'm trying to get near-earth asteroid data from NASA API. And I'm getting the data I need but it's coming very slow. How can I optimize my code to get data quickly? @api_view(['GET']) def getDates(request, start_date, end_date): dates = [] all_data = list() api_key = 'hpdCBykg6Bcho1SitxAcgAaplIHD1E0SzNLfvTWw' url_neo_feed = "https://api.nasa.gov/neo/rest/v1/feed?" params = { 'api_key': api_key, 'start_date': start_date, 'end_date': end_date } response = requests.get(url_neo_feed, params=params) json_data = orjson.loads(response.text) date_asteroids = json_data['near_earth_objects'] for date in date_asteroids: dates.append(date) # Splitting the data to make it more meaningful for date in dates: collection = json_data.get('near_earth_objects') all_dates = collection.get('{}'.format(date)) all_data.append(all_dates) return Response(all_data) -
Many tasks at once in Celery?
If we use celery beat and run about 1000 tasks by same crontab schedule, will tasks run one by one or some tasks will not run (cause of out of time)? redis as MQ -
Third party Api with Header key integration in django-python
I want to use my old rest API for my new Django project. In the old API, I used the header key, but I don't know how to use this API key in my new Django project. Could anyone help me? -
Upload Django app to Heroku. ModuleNotFoundError:No Module named 'Name of Project"
I can not upload Django App to Heroku by command: git push heroku master. After uploading I have error: ModuleNotFoundError: No module named 'bot_diller' Procfile: web: gunicorn bot_diller.wsgi --log-file - enter image description here -
Jinja subtraction and variable declaring
In jinja, how to subtract. Eg: I have some number inside {{ review.rating }} , and I want to subtract the number with 5. Is it like {{ 5 - review.rating }} or how? And is it possible to put the answer in another variable in jinja itself? -
Is there a way to overwrite the Django Admin's Inline instance change text "Change" to something else more intuitive?
I am customizing the Django Admin and have an inline model's instances listed under another model. I am looking to change the text "Change" that leads to the selected inline model's instance change page but was unable to figure this one out. I just need to change this to something like "Change view/display all fields" as I am displaying only a limited number of fields in the inline view. Image displaying the text to be changed #models.py class TourItem(models.Model): tour = models.ForeignKey(Tour, related_name='items') ... class Tour(models.Model): ... #admin.py class TourItemInline(admin.TabularInline): model = TourItem show_change_link = True ... class TourAdmin(admin.ModelAdmin_ model = Tour inlines = (TourItemInline, ) ... -
No table is created when excuted "python3 manage migrate"
python version: 3.6.4 django version: 3.1.7 db: sqlite3 my_app: robot my_models: Check_Monitor_Task, Action_Manager, Questions_Answers_Task Step1: models Step2: python3 manager makemigrations Migrations for 'robot': robot/migrations/0001_initial.py - Create model Action_Manager - Create model Check_Monitor_Task - Create model Questions_Answers_Task Step3: python3 manager migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, robot, sessions Running migrations: Applying robot.0001_initial... OK Step4: confirm the tables There is record in django_migrations sqlite> select * from django_migrations order by id desc limit 3; id|app|name|applied 25|robot|0001_initial|2022-05-11 17:33:16.780900 18|sessions|0001_initial|2022-05-10 21:30:28.049031 17|auth|0012_alter_user_first_name_max_length|2022-05-10 21:30:27.985724 But no tables showed: python3 manage.py dbshell SQLite version 3.21.0 2017-10-24 18:55:49 Enter ".help" for usage hints. sqlite> .tables auth_group auth_user_user_permissions auth_group_permissions django_admin_log auth_permission django_content_type auth_user django_migrations auth_user_groups django_session sqlite> I have tried to delete migration files and pycache, but working like every times. Please tell my why, and how to create table. Thanks. -
Optimize recursive function in Django Tree structure Model
I am trying to implement a team hierarchy in a Django work application. My requirements are Team may have Team Lead, members and a Parent Team. current node will be considered as one of the child of parent team Team lead can access the members and all child team members( sub child nodes at any level in that hierarchy) For Example Team A have a child team Team A1 and Team Team A2, and Team A2 another child TEAM A21, Team Lead of A can acces all members data of Team A,Team A1,Team A2, and Team A21 Please see my model structure class Team(models.Model): title=models.CharField(max_length=200,null=True) team_lead=models.ForeignKey(StaffUser,on_delete=models.SET_NULL,related_name='teams_leaded',null=True) member_staffs=models.ManyToManyField(StaffUser,related_name='teams_joined') parent=models.ForeignKey("self", on_delete=models.SET_NULL,blank=True, null=True,related_name='children') published_date = models.DateTimeField(blank=True, null=True) class StaffUser(models.Model): name=models.CharField(max_length=100,null=True) email=models.CharField(max_length=100,null=True) user=models.OneToOneField(User, on_delete=models.CASCADE,related_name='staffs',null=True) My intentian is to append all accesable members id'to user input when a request comes Fo that I have written a recursive function to extract the all subchilds after getting a staff object . But it is very slow. Is there any way to optimazie this function. def extractMembers(staff_obj,sub_members): try: if(staff_obj.user.id not in sub_members): sub_members.append(staff_obj.user.id) if(staff_obj.teams_leaded is not None): leaded_teams=staff_obj.teams_leaded.all() for team_obj in leaded_teams: team_members=team_obj.member_staffs.all() for tmember_obj in team_members: if(tmember_obj.user.id not in sub_members): sub_members.append(tmember_obj.user.id) child_teams=team_obj.children.all() for team_child_obj in child_teams: child_team_staffs=team_child_obj.member_staffs.all() … -
Send a dictionary where values are in a list back to an ajax request and try to parse it there
I am trying to send a dictionary like this (values in a list): datax = { "name": ["bhanu", "sivanagulu","daniel"], "department": ["HR", "IT", "FI"]} back to an ajax request. I use two methods, it is sent, but can't unpack the content. Here are the two methods and what it looks: return HttpResponse(simplejson.dumps(datax)) This is what gets sent: 0 Object { name: […], department: […] } name [ "bhanu", "sivanagulu", "daniel" ] department [ "HR", "IT", "FI" ] If I try this: json_dict = json.dumps(datax) return JsonResponse(json_dict,safe=False) I get this: [{\"name\": [\"bhanu\", \"sivanagulu\", \"daniel\"], \"department\": [\"HR\", \"IT\", \"FI\"]}]" in both cases, when at the client I try to parse the content, obj = JSON.parse( data); I get this when I try to tabulate: name undefined [object Object] [object Object] -
Model CharField Dynamic Choices with instance object
i haven't found anything on having a method returning tuple for the choices of Charfield. It can only be done for Filters. So Basically i have a class model as follow: def existing_document(instance): if instance.file == 'x' return [('test', 'test')] else return [('test1', 'test')] class ModelInsert(models.Model): file = models.ForeignKey(ModelFile, on_delete=models.CASCADE, related_name='insert', null=True, blank=True) page = models.CharField(verbose_name="Position après la page:", max_length=3, validators=[RegexValidator('^[0-9]+$')]) document = models.CharField(verbose_name='Document', choices=existing_document(), max_length=128) Sending a method as an output work. But i would like to catch the instance of my current object (like upload_to= of fileField) so i can choose what will be displayed. It does not seem to be possible directly in the method but maybe in an init or something ? -
Django / error : Object of type *** is not JSON serializable
I have seen this is a common mistake and there are a lot of entries in StackOverflow, but I can't connect the dots on this one. in my views.py, this one works def start(request): whichScene = request.session.get('whichScene') myScene=Scenes.objects.get(name=whichScene) scene_list=myScene.next.all() return render(request,'scenes3d/start.html', {'scene_list':scene_list}) this one doesn't work : def newPage (request, scene_slug): sceneToRender = Scenes.objects.get(name=scene_slug) return render(request,'scenes3d/new_scene.html', {"myScene" :sceneToRender }) It gives an error : Exception Value: Object of type Scenes is not JSON serializable Scenes is imported with : from .models import Scenes models.py class Scenes(models.Model): name = models.SlugField('Scene name', max_length=60,unique=True) description = models.TextField(blank=True) fileGltf = models.FileField(null=TRUE, blank=False, upload_to="3dfiles/") record_date = models.DateTimeField('Scene date') manager = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) prev = models.ForeignKey( 'self', related_name='next', blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name -
Password recovery - Django token never expires
I've set up a password recovery system in my application which work pretty well however I'm facing a problem with the token issued which apparently never expire, at least when it gets used multiple time by the user. The link sent by email to the user remain valid even after changing the password x times with the same link. I'm using the regular way I've found on internet with token_generator.make_token(user) utils.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active), text_type(user.pk), text_type(timestamp)) token_generator = AppTokenGenerator() api_email.py def send_email_user_account_password_recover(request, user, language): try: uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) token = token_generator.make_token(user) url_base = get_url_base(request) email_text = emailText["user_account_password_recover"][language] if language == "fr": link_text = "Réinitialiser mon mot de passe" activate_url = url_base + f"/fr/recover-password-authorised/{uidb64}/{token}/" else: link_text = "Reset my password" activate_url = url_base + f"/en/recover-password-authorised/{uidb64}/{token}/" context = {"title": email_text["title"], "content": email_text["text"], "url_base": url_base, "link": activate_url, "link_text": link_text, "language": language} html_content = render_to_string("email/email-template-extends.html", context) text_content = strip_tags(html_content) email = EmailMultiAlternatives( subject=email_text["title"], body=text_content, to=[user.email]) email.attach_alternative(html_content, "text/html") email.send(fail_silently=False) logger.info(f"Email user password recover for user ({user.id_code}) sent from {EMAIL_HOST_USER} to {user.email}.") return True except: logger.error(f"Email user password recover for user ({user.id_code}) could not be sent.") return False views.py def AccountVerification(request, language=None, uidb64=None, … -
DRF ViewSet extra action (`@action`) serializer_class
When I try to use Django Rest Framework extra actions on a viewset, I can not make the decorator's serializer_class work. class ClientViewSet(ModelViewSet): queryset = Client.objects.all() serializer_class = ClientSerializer def get_queryset(self): # Do things def get_serializer_class(self): # Do things @action(detail=True, methods=["get"], serializer_class=ClientDetailSerializer) def get_by_name(self, request, name=None): """ Get one Client searching by name. @param request: @param name: Client code @return: Response """ queryset = get_object_or_404(Client, name__iexact=name) serializer = self.get_serializer(queryset) return Response(serializer.data) So, even if the extra action is supposedly overriding the ViewSet default serializer class, I still get ClientSerializer instead of ClientDetailSerializer. The official documentation states that... The decorator allows you to override any viewset-level configuration such as permission_classes, serializer_class, filter_backends...: My get_serializer_class override defaults to the ViewSet serializer_class attribute for my extra actions. If I understand correctly, this is basically what GenericAPIView get_serializer_class does under the hood: def get_serializer_class(self): """ (...) """ assert self.serializer_class is not None, ( "'%s' should either include a `serializer_class` attribute, " "or override the `get_serializer_class()` method." % self.__class__.__name__ ) return self.serializer_class I guess I'm missing something obvious here. Just can not figure out what... Any help is appreciated. Thanks in advance :) -
Object of type <> is not JSON serializable Django REST Framework
I am trying to create a search function inside my class-based view using Django Rest Framework, but it does not seems to work. when I try to search for some customers it gives me an error: raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type Customer is not JSON serializable I know there is some question out there looking like mine, but I dont think any of them can help my. I am a bit new to Django REST framework. my view: class staff_search_partial(generics.ListAPIView): renderer_classes = [JSONRenderer, TemplateHTMLRenderer] template_name = 'BankApp/staff_search_partial.html' serializer_class = CustomerSerializer permissions_classes = [permissions.IsAuthenticated, ] def post(self, request): assert request.user.is_staff, 'Customer user routing staff view.' search_term = request.POST['search_term'] print(type(search_term)) customers = Customer.objects.filter( Q(user__username__contains=search_term) | Q(user__firstname__contains=search_term) | Q(user__lastname__contains=search_term) | Q(user__email__contains=search_term) | Q(personalid__contains=search_term) | Q(phone_contains=search_term) )[:15] return Response({'customers': customers}) the Customer model: class Customer(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.PROTECT) rank = models.ForeignKey(Rank, default=2, on_delete=models.PROTECT) personal_id = models.IntegerField(db_index=True) phone = models.CharField(max_length=35, db_index=True) @property def full_name(self) -> str: return f'{self.user.first_name} {self.user.last_name}' @property def accounts(self) -> QuerySet: return Account.objects.filter(user=self.user) @property def can_make_loan(self) -> bool: return self.rank.value >= settings.CUSTOMER_RANK_LOAN @property def default_account(self) -> Account: return Account.objects.filter(user=self.user).first() def make_loan(self, amount, name): assert self.can_make_loan, 'User rank does not allow for making loans.' assert amount … -
You have SHARED_APPS that are not in INSTALLED_APPS
I've just started migrating an old Django app to 1.11. After the upgrade to this version, when running python manage.py runserver I get ?: You have SHARED_APPS that are not in INSTALLED_APPS HINT: ['myappname.apps.MyAuthConfig'] WARNINGS: ?: Your default storage engine is not tenant aware. If I print print(settings.INSTALLED_APPS) in manage.py, in that array, there is 'myappname.apps.MyAuthConfig' so I don't know why this error happens. Right now I'm looking to fix the error, not the warning, but I posted it too just because they might be more useful together. What can be the reason for the first error and how can I fix it? -
why django model in test returned empty queryset?
I used ThreadPoolExecutor in my API. in the test case, I generated a Movie instance and saved it in the database (PostgreSQL). I printed movie count in the test case, API, and thread pool function. why in the thread pool return an empty queryset? view.py: def movie_count(): print(Movie.objects.count(), "movie count in the thread") class MovieListView(APIView): renderer_classes = ( render.CamelCaseJSONRenderer, renderers.BrowsableAPIRenderer, ) def get(self, request, key, format=None): print(Movie.objects.count(), "movie count before the thread") with ThreadPoolExecutor(1) as executor: bookmarked_future = executor.submit(movie_count) bookmarked_future.result() return Response({}) test.py def test_mock_function(self): Movie.objects.create( title="Title" ) print(Movie.objects.count(), "movie count in the test") url = reverse('video_api:list', args=('tops',)) self.client.get(url, format='json', data={'limit': 30}) result: 1 movie counts in the test 1 movie count before the thread 0 movie count in the thread -
Looping in jinja
I have a Integer value inside {{ review.rating }} . Now I want to loop using jinja , the number of times the value of review.rating. Eg. if I have review.rating = 4 , I want to display <div>A</div> , 4 times. How can I do so? -
ERROR: Failed building wheel for M2Crypto for django in WSL2
I am trying to install some django dependencies however m2crypto seems to fail as in the following logs also there's an error below error: command 'swig' failed with exit status 1. I am also using WSL2 • Installing m2crypto (0.38.0): Failed EnvCommandError Command ['/home/menna/kr8/celo-digital-sports-card/api/.venv/bin/pip', 'install', '--no-deps', 'file:///home/menna/.cache/pypoetry/artifacts/ef/3f/ce/4feb630731f44d2868dd6413e2dda6d6593c62852be40b8d43b7b6a029/M2Crypto-0.38.0.tar.gz'] errored with the following return code 1, and output: Processing /home/menna/.cache/pypoetry/artifacts/ef/3f/ce/4feb630731f44d2868dd6413e2dda6d6593c62852be40b8d43b7b6a029/M2Crypto-0.38.0.tar.gz Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Building wheels for collected packages: M2Crypto Building wheel for M2Crypto (setup.py): started Building wheel for M2Crypto (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /home/menna/kr8/celo-digital-sports-card/api/.venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-req-build-ycua_cfq/setup.py'"'"'; __file__='"'"'/tmp/pip-req-build-ycua_cfq/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-u7uierq1 cwd: /tmp/pip-req-build-ycua_cfq/ Complete output (61 lines): running bdist_wheel running build running build_py copying src/M2Crypto/RC4.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/Engine.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/BN.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/Rand.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/ASN1.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/m2urllib2.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/m2.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/m2urllib.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/m2crypto.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/RSA.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/six.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/callback.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/httpslib.py -> build/lib.linux-x86_64-3.8/M2Crypto copying src/M2Crypto/BIO.py -> build/lib.linux-x86_64-3.8/M2Crypto … -
Getting the the users who have submitted 2 knowledge
I have a table which has like 10 records of knowledge in it which different users have submitted them...so my question is how can i get the user or users who have submitted exactly 2 knowledges? -
Multible dynamic URLs in django
Making a clinic website, in which the user is the clinics, who can then create "patient" objects. To navigate the page, I want the URLs to be dynamic and specific for the clinic and the given patient. Im having trouble making a selecting button on the clinics dashboard. The Dashboard has the following URL: /<str:kl_id>/ . the button should link to a patient page with the URL: /<str:kl_id>/patientside/<str:pt_id>/ The Views.py file looks like this: def klinik(request, kl_id): klinik = Klinik.objects.all() kliniknavn = Klinik.objects.get(navn=kl_id) E_patient = kliniknavn.patient_set.all() context = {'E_patient':E_patient, 'klinik':klinik} return render(request,'DentHelp/klinik.html', context ) I have tried in the template to make the following code, making a list of eksisting patients, with buttons leading to the dynamic patient page: {% for patient in E_patient %} <tr> <td>{{patient.id_nr}}</td> <td>{{patient.fornavn}}</td> <td><a href="{% url 'patientside' kl_id=klinik.navn pt_id=patient.id_nr %}" class="btn btn-primary">Vælg patient</a></td> </tr> {% endfor %} With this code do I get a NoReverseMatch error when trying the klinik page. Looking forward to getting help. -
make two fields in serializer from a same model
how are you? I used a nested serializer in another serializer and I have two models (Object and ObhectMedia)... here are the serializer class ObjectMediaSerializer(serializers.ModelSerializer): media_address = serializers.SerializerMethodField() class Meta: model = ObjectMedia fields = ["media_address", "type"] class ObjectAddEditSerializer(serializers.ModelSerializer): slug = serializers.SlugField(read_only=True) object_medias = ObjectMediaSerializer(many=True, required=True) class Meta: model = Program fields = [ "slug", "object_medias", ] I want to add object media in two fields(separated by their type) like below but I don't know how it is possible: { "slug":"my_slug", "object_media_type1": [ { "media_address ": "somewhere", "type":TYPE1 } ], "object_media_type2": [ { "media_address ": "somewhere", "type":TYPE2 }, { "media_address ": "somewhere\else", "type":TYPE2 }] } Thanks for reading -
403 CSRF verification failed. Request aborted. Django-Heroku-Cloudflare issue
I’ve made a heroku app with django and used the free ssl certificate of Cloudflare for my custom domain. The problem is that on a page I have a POST method with csrf token which shows ok in herokuapp.com but returns an error 403 in my custom domain served by Cloudflare! What should I do? -
how to setup daphne with nginx with djnago channels for websockets
I have to set up the Django server with WebSockets and HTTP requests. It works fine in my local system. and also on the server without SSL, but when we use the SSL on the server the HTTP request works fine on the https but WebSocket does not work with wss I am using Nginx for the webserver and daphne. this is my Nginx conf file server { listen 80; server_name domain.name; error_log /var/log/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /root/myprojectdir/staff_hiring/static; } location /media/ { autoindex on; alias /root/myprojectdir/staff_hiring/media; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and this is my asgi file import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import staff_admin.routing from channels.security.websocket import AllowedHostsOriginValidator import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'staff_hiring.settings') django.setup() application = ProtocolTypeRouter({ "https": get_asgi_application(), 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( staff_admin.routing.websocket_urlpatterns ) ) ) }) and routing file websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), # Using asgi # url(r'/ws/chat/', consumers.ChatConsumer.as_asgi()) ] -
csrf cookie not set on linux
I know this question is quite popular, before asking it, I researched all the previous questions and their answers, but never found a solution for myself. My problem is that I am trying to remove the csrftoken validation completely in my application. I understand the vulnerabilities that open up in this case, but this is not critical for me. During development, no errors occur on my computer due to csrftoken, I develop on windows, but when I run it on linux, this error appears, it’s hard for me to imagine the reason why this happens only on a linux server, I transfer using docker . I decided to remove csrftoken from my application for the same reason, on the windows computer on which I developed the application, no errors occurred with csrftoken enabled, but when transferred to a linux server, forms using data transfer using js files also gave an error 403. Settings MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', ] CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False I removed in js files csrf_token {# {% csrf_token %}#} I removed in js files headers // headers: {'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value}, I added in form attribute action="" <form class="js-edit-event-form" action=""> I already cleared …