Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I sometime get Coroutine was never awaited when I use asyncio.run
This error is rare, but still present. This happens when two or more requests are sent at the same time. I try to do it: adapter = OperatorCreator.create( title=operator.slug, api_key=operator.api_discount[0] ) terminals = asyncio.run( adapter.find_terminals(locality=locality), debug=True ) return terminal Adapter: async def find_terminals(self, locality: Locality, session: aiohttp.ClientSession = None) -> Mapping[str, Terminal]: if 'dpd_terminals' in cache: terminal_list = await sync_to_async(cache.get)('dpd_terminals') else: terminal_list = await self.add_terminals_from_request_to_cache() terminals = terminal_list[str(locality.kladr)] return terminals And then sometime I get: django_1 | /app/project/apps/geo/services.py:383: RuntimeWarning: coroutine 'CdekAdapter.find_terminals' was never awaited django_1 | adapter.find_terminals(locality=locality) django_1 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback What am I doing wrong? -
Django - Pass Object after redirect
I am building a scrum app where users can create user stories and add them to sprints. I want to have two separate ways of creating stories. If the user is creating a story from the backlog, the story that has been created will not be assigned to a sprint, but the user can also add a story from a sprint's detail screen. I want to make it so that if they add a story from a specific sprint's page, that story's sprint field is populated with that sprint. The way I have tried to go about this is by creating two different functions in my views.py file and two separate templates. I am able to create the story without relating to a sprint as intended, but I cannot think of a way to get the id of the sprint where I navigated from to get to the new template. For reference I have included my function for creating stories without relating to a sprint: def create_story(response, id=None): user = response.user if response.method == "POST": form = CreateNewUserStory(response.POST) if form.is_valid(): name = form.cleaned_data["name"] description = form.cleaned_data["description"] status = form.cleaned_data["status"] assignee = form.cleaned_data["assignee"] estimate = form.cleaned_data["estimate"] userstory = UserStory(name=name, description=description, status=status, … -
deleting multiple records from table in django with checkbox using ajax
I am new to Django and I'm trying to delete multiple leads from a table in my Django application and everything works fine except when i try to do the #select_all checkbox in thead of the table, i get an error such as this in the console: jquery-3.6.0.js:10109 POST http://127.0.0.1:8000/leads/delete/ 500 (Internal Server Error) Here is my code... views.py from django.shortcuts import render, reverse, redirect from django.views import generic from django.contrib import messages from .forms import LeadModelForm from .models import Lead class LeadCreateView(generic.CreateView): model = Lead template_name = "leads/lead_create.html" form_class = LeadModelForm def get_success_url(self): return reverse("leads:lead-index") class LeadUpdateView(generic.UpdateView): model = Lead template_name = "leads/lead_update.html" form_class = LeadModelForm def get_success_url(self): messages.info(self.request, "Lead updated successfully.") return reverse("leads:lead-index") class LeadIndexView(generic.ListView): queryset = Lead.objects.all() paginate_by = 25 template_name = "leads/lead_index.html" def lead_delete(request, pk): lead = Lead.objects.get(id=pk) lead.delete() return redirect("/leads") class LeadView(generic.View): def get(self, request): allleads = Lead.objects.all() context = { 'leads': allleads } return render(request, "leads/lead_index.html", context) def post(self, request, *args, **kwargs): if request.method=="POST": lead_ids=request.POST.getlist('id[]') for id in lead_ids: lead = Lead.objects.get(pk=id) lead.delete() return redirect("/leads") urls.py from django.urls import path from .views import LeadCreateView, LeadUpdateView, lead_delete, LeadView, LeadIndexView app_name = "leads" urlpatterns =[ path('', LeadIndexView.as_view(), name='lead-index'), path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'), path('create/', LeadCreateView.as_view(), name='lead-create'), path('<int:pk>/delete/', lead_delete, … -
Django - ModuleNotFoundError: No module named 'taggit_serializer' in SSH server
I installed 'taggit_serializer' in my django application. It works fine in the local server and I am able to see tags in the response from the serializer. But now I have to deploy it to the server. For that, I have to go to putty and activate the environment. I activate the virtual env and installed the package and it's successfully installed. But when I try to run python manage.py showmigrations it shows the above error. If I try to install the package again, it says the requirement already satisfied. I am not sure what is happening. Traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'taggit_serializer' My serializer: from taggit_serializer.serializers import (TagListSerializerField, TaggitSerializer) class … -
How to make a GET request in an extended Django template
I have a simple navigation bar base.html, that contains links to other pages. Currently, I am extending the base.html template on every other page I have. I want to call a GET request from a weather API in order to display simple information like the city name and current temperature and have it displayed on the navigation bar. Since the base.html template isn't linked with a view itself, I am unsure how to go about this. I have already managed to succesfully get information from the API and display the information in a test page. base.html: <body> <div class="container-fluid bg-light"> <div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start"> <i class="far fa-newspaper fa-5x"></i> <a href="{% url 'news_list:homepage' %}" class="nav-link link-dark display-4">Ziņu portāls</a> <ul class="nav align-items-center ms-auto me-auto"> <li><a href="{% url 'news_list:all_posts' %}" class="nav-link link-dark pt-4"><h2>Visi raksti</h2></a></li> <li><a href="{% url 'news_list:new_post' %}" class="nav-link link-dark pt-4"><h2>Pievienot rakstu</h2></a></li> <li><h2>Information from API</h2></a></li> </ul> </div> <hr/> </div> {% block content %}{% endblock content %} </body> -
TemplateSyntaxError at /register Invalid block tag on line 6: 'csrf_tocken', expected 'endblock'. Did you forget to register or load this tag?
my code TemplateSyntaxError at /register Invalid block tag on line 6: 'csrf_tocken', expected 'endblock'. Did you forget to register or load this tag? -
how to fetch many to many fields in Django models or Django ORM
I have two classes , now I have user id only in the view , what is the Django ORM query to display the badges associated with the user,by using user id field class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.CharField(max_length=50, unique=True) user_badges = models.ManyToManyField(Badges,related_name='badges', null=True,blank=True,) class Badges(models.Model): badge_text = models.CharField(max_length=50) badge_color = models.CharField(max_length=50 -
How to add an extra weight to networkx graph?
I'm doing a Django project, where I put 2 points and get their distance. But, there are two types of weight, I need to get the length of the cable line, and length of the trakt line. Graph is able to get only one weight, How I can add an extra weight, for example, weight1, weight2? def get_distance_length_kls(request, pk1, pk2): point1 = get_object_or_404(Point, pk=pk1) point2 = get_object_or_404(Point, pk=pk2) g = nx.Graph() data = [] content = {'points': None} content1 = {"sum_line": 0, "sum_cable": 0} for form in Form61KLS.objects.all(): g.add_edge(form.point1.point, form.point2.point, weight=form.total_length_line) #here should be another type of length weight=form.total_length_cable) for p in nx.all_simple_edge_paths(g, source=point1.point, target=point2.point): finish_total = copy.deepcopy(content) finish_total['points'] = p data.append(finish_total) path = [] for p in nx.all_simple_paths(g, source=point1.point, target=point2.point): path.append(p) if len(path) > 1: for pt in path: total = copy.deepcopy(content1) path_length = nx.path_weight(g, pt, weight='weight') total['sum_line'] = path_length data.append(total) return JsonResponse(data, safe=False) ``` My output should look like this: **[ { "points": [ [ "UZB/UT/Андиж", "UZB/UT/Пахта" ], [ "UZB/UT/Пахта", "UZB/UT/Тшк" ], [ "UZB/UT/Тшк", "KAZ/ V-Net/Алматы" ] ] }, { "sum_line": 190.103, "sum_cable": 0 } ]** -
How to send looping items into ajax in Django? {% for item in items %} {{ item }} {% endfor %} How to pass all items in a single call of ajax?
All of the names need to call using ajax! Code for ajax I have tried. <script type="text/javascript"> $(document).on('submit','#form',function(e){ e.preventDefault(); alert("No reload") $.ajax({ type:'POST', url:'add-result', data:{ subject:$('#subject').val(), **//How to get all names from loop here?** names:$('#names').val(), test_score:$('#test_score').val(), exam_score:$('#exam_score').val(), class:$('#class').val(), exam_term:$('#exam_term').val(), exam_date:$('#exam_date').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), success:function (){ alert("Here") }, }, success:function (){ alert("Working !") } }); }); </script> -
How to parse an RPCReply python3
Hello I am currently on a project that is not mine and needs updating, I am stuck here, trying to parse an rpc-reply into a string so it can be parse into an xml.The whole project was coded by somebody else and he/she used python2 and now I am required to use python 3.6 but it does not work I have tried some alternatives that I have found online but none of them work (such as this https://mihird.com/parsing-junos-rpc-reply-with-beautifulsoup4/ ) This are the functions giving me issues, the response parameter is <class 'ncclient.operations.rpc.RPCReply'> def is_successful(response): import io doc = parsexml_(io.StringIO(response)) rootNode = doc.getroot() success_list = rootNode.xpath("//*[local-name()='ok']") if len(success_list) > 0: return True, None else: reason_return = '' reason_list = rootNode.xpath("//*[local-name()='error-message']") for reason in reason_list: reason_return = '%s %s' % (reason_return, reason.text) return False, reason_return def parsexml_(*args, **kwargs): if 'parser' not in kwargs: kwargs['parser'] = ET.ETCompatXMLParser() doc = ET.parse(*args, **kwargs) return doc Thanks you so much for the help in advance! -
Login using Post Request of a website and going to the next url from backend using Http(Django) [closed]
Login using Post Request of a website and going to the next URL from backend using HTTP(Django) -
Django Channels Send Msg (Hyperlink)
I studied Django Channels The chat room has been established But i have a problem now If the client sends a http:// message How to make the http message displayed in the chat room have a hyperlink function? Should it be processed on the front-end or on the back-end? -
Synch between Django runserver & Selenium Webdriver
okay so I have made an app from where django webapp will take a id & date-of-birth as input and it will return some json HTTPResponse with details after parsing it from other websites. I have done this with Selenium integration where I have a "Driver" variable in settings.py because I want the Selenium driver to run one time while executing the Django Server and it will be in that background process state while the Django server is running. Now my Question is How can I remove the Driver object because if restart the server the Firefox(Driver) is still in the process. Is there any way to delete the old process and instantiate again with new instance. views.py def search(request): if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): nid = form.cleaned_data['nid_number'] dob = form.cleaned_data['date_of_birth'] json = SearchAction(settings.WEBDRIVER_WINDOW, nid, dob) return HttpResponse(json, content_type="application/json") else: if request.GET.get('nid') and request.GET.get('dob'): nid = request.GET.get('nid') dob = request.GET.get('dob') json = SearchAction(settings.WEBDRIVER_WINDOW, nid, dob) return HttpResponse(json, content_type="application/json") else: form = RequestForm() context = { 'title': "Search NID", 'form': form } return render(request, 'voter_id_parser/search.html', context) browser.py class SingletonBrowser: options = Options() options.add_argument("--headless") __instance = None @staticmethod def get_browser() -> webdriver: if SingletonBrowser.__instance is None: SingletonBrowser() return … -
Showing who viewed the post ( user )
I am building a BlogApp and I build a feature, So i can count post views. BUT i am trying to get who viewed the Post. views.py queryset = BlogPost.objects.annotate(num_views=Count('viewers')).order_by('-num_views') datas = get_object_or_404(queryset,pk=pk) if request.user.is_authenticated: created = Post.viewers.through.objects.get_or_create(post=datas,user=request.user) Below code counts the views of Post whenever i print {{ datas.viewers }}, BUT when i try to print {{ datas.viewers.user.username }} then, It doesn't show the viewed users class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_posts',editable=False) BUT i am trying to show `who viewed the BlogPost. Any help would be Appreciated. Thank You in Advance. -
Django save function model: How to assign "data_counter" as number series when importing from excel file
This is a continuation of these questions: Django: Generate a custom series number upon saving the model https://stackoverflow.com/q/67084479/2380028 I have a scenario of generating series number per location id, which I was able to solved in the above link. Now, my concern is: How can I assigned the data_counter as series number when importing an excel file using the django-import-export? As of now, if I will add a new instance via admin site, the save function is working as intended, but when adding a new instance (bulk) via import function, everything is messed up and I cannot edit the whole property number field xD, below is the result: As you can see in the image, the series number is the second to the last group (4-digit) and the location id is the last group (2-digit) The first 9 data should be like these: 1972-30-40-0001-00 1972-30-40-0002-00 1972-30-40-0003-00 1972-30-40-0004-00 1972-30-40-0001-18 1972-30-40-0005-00 1972-30-40-0001-19 1972-30-40-0002-19 1972-30-40-0006-00 and so on... save funtion def save(self, *args, **kwargs): data_counter = Item.objects.filter(location=self.location).aggregate(counter=Count('id'))['counter'] # Count existing instance with matching "location id" of the new instance if self.pk is None and self.property_number is None: # if new instance and property number field is blank if data_counter is None: # if … -
django csrf token : CSRF token missing or incorrect
I don't use a django form, we only process it with API and respond to the result. When using a form, I know that you are using a tag, but in this case, it is difficult to write a tag. I can't get rid of csrf so I need help. When receiving a request as a post, "CSRF token missing or incorrect." Appears. How can I solve this problem? heres view's.py class EventsView(View): def post(self, request): json_request = json.loads(request.body) ApplyEvent.objects.create( event=event, meta_user=user ) return JsonResponse({"message": "SUCCESS"}, status=201) const response = await axios({ method: "post", url: `${apiHostName}/events`, data: { event_id: 8, user_id: `${props.userStore.user?._id}`, }, withCredentials: true, xsrfHeaderName: "csrftoken", xsrfCookieName: "X-CSRFToken", }) -
How to disable a field in wagtail when another field value changes?
I have a wagtail form as given: from django import forms from wagtail.admin.forms import WagtailAdminPageForm from myapp.models import * class MyClassForm(WagtailAdminPageForm): displayed_on_section = forms.ModelMultipleChoiceField( queryset=DisplayedOnSection.objects.all(), widget=forms.CheckboxSelectMultiple() ) last_name = forms.CharField(required=False) # other fields And my page looks like this: from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page class MyClassPage(Page): content_panels = Page.content_panels + [ FieldPanel('displayed_on_section'), FieldPanel('displayed_on_section') ] base_form_class = MyClassForm Now suppose I have 3 displayed_on_sections like: o Profile Section o Dashboard Section o Feed Section I want that if the user selects Feed Section, the last_name form field should get disabled (and if possible, its value becomes empty). Is it possible to achieve what I'm trying to do, and what are the ways to do it? P.S. I just want to know how to do this, I don't require full solution. -
Raspberry start django app while directly connected with eth0 to a pc
I have to create on my raspberry pi a django app for manage internal settings opening connecting directly a pc to my raspberry via eth0 port. As normally for example for configure routers an user can connect his PC directly to the port and typing for example 192.168.1.65 and open admin configuration panel i would the same with my raspberry. I fix the eth0 address in my /etc/dhcpc.conf to 192.168.1.50, then i start my django app: python manage.py runserver 0.0.0.0:8000 but if i connect my raspbery to local lan, from another pc via network on 192.168.1.50:8000 i see django screen correctly, but if i connect directly Pc to raspberry i get "Cannot connect, timeout" How can i open my app from a specific Ip address connecting directly a PC to my device? So many thanks in advance -
"<Order: Order object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used
So I'm trying to add multiple products or order items into a product and I'm using many to many relationship for that but when I try to create that order I get "<Order: Order object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. error, My code for adding and saving that order is like: userObject = UserLogin.objects.get(token=finalUserToken).user objects = OrderItem.objects.filter(user=userObject) FinalOrder = Order(user=userObject, order_id=another_token) for orderObject in objects: FinalOrder.products.add(orderObject.id) FinalOrder.save() The error screen is pointing to this line FinalOrder.products.add(orderObject.id) I have also tried this FinalOrder.products.add(orderObject) but this gives the same result too -
Cron in docker container with django
I have django project and make managment command for django. This command delete some objects from db. So If I run it manually "docker-compose exec web python manage.py mycommand" it works fine, but when I try add task into cron using crontab (cron located in django container): */1 * * * * path/to/python path/to/manage.py mycommand >> cron.log 2>&1 django raise: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432? Tasks without db connection work fine. Problem is that tasks executed by cron can`t connect to db. Any ideas how to change crontab file or docker-compose.yml? docker-compose.yml version: '3' services: web: container_name: web env_file: - .env.dev build: context: ./ dockerfile: Dockerfile volumes: - .:/domspass - "/var/run/docker.sock:/var/run/docker.sock" command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db db: image: postgres:13.2 container_name: db restart: always env_file: - db.env.dev volumes: - ./postgres:/var/lib/postgresql/data ports: - "5432:5432" volumes: postgres: -
Django Dependencies and Versions
I'm trying to find the list of dependencies Django requires when installing on a per version basis. Is this located in the codebase anywhere? -
django - A object have pk of B (ex 2) but B.objects.get(pk=2) not exists
django - A object have pk of B (ex 2) but B.objects.get(pk=2) not exists why B objects not exists pk2 B objects deleted How make A.objects.filter(???) i have written that A.objects.filter(B__id__isnull=False) but not working -
Does the Backend Distinguish Different API Requests from Different Users in SSR Mode? (Nuxt.js / Django Rest Framework)
I know that the title might be a little bit confusing, so I'll explain my question with an example. I'm using Nuxt.js in SSR mode for frontend, and Django Rest Framework for backend. Consider an API endpoint in DRF that has a rate throttling of 1 request per minute for anonymous users. And imagine that this endpoint is called in a certain page by axios in the frontend, in both SPA and SSR modes. Imagine 2 different users with different IPs request the page in SSR mode (new tab), user A in time t and user B in time t + 2seconds. Now that the frontend server requests the backend for the data, would the rate limiting give 429 - too many requests to user B's request? Or is there some kind of forwarding pattern that prevents this behavior?? Obviously, if user A and B request the page in SPA mode, they would both get their responses. -
Edit AutoSlugField value
Is there any way I can edit the value of an AutoSlugField? I just noticed it added a '-2' to the end of the slug and I'd like to remove that. slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') -
Ajax request not triggering progress event on HTTPS port 443 in Django
I have a Django website served by UVICORN, the ajax request works fine however, the progress event is not triggered when using HTTPS on port 443. For example, when I change port number to anything other than 443, the progress event starts working! It also works when using port 443 on HTTP. I tried HYPERCORN as well, but nothing changed. Below is the configuration I use to run UVICORN. uvicorn ****.asgi:application --host 0.0.0.0 --port 443 --ssl-certfile cert.crt --ssl-keyfile key.key --ws websockets Any help would be appreciated.