Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checking if a value exists in one template so that I can create a notification in another template
I have a bootstrap card that holds a list of information and within that information there is a boolean value. If that value is true, I'd like to show some kind of notification on the card. Here is what it looks like So if in one of those links there is a value that is true, I'd like something notifying the user that everything is all good and if a value is false, let them know something is wrong. Maybe like a thumbs up and thumbs down from font awesome or something(not important right now). Here is my template that holds that information <link href="{% static 'css/styles.css' %}" rel="stylesheet" /> <div class="card"> <div class="card-header text-dark"> <div class ="card-body"> <div class="table-responsive"> <table class="table table-bordered"> <thead class = "table-light"> <tr class="text-center"> <th>Location</th> <th>RSU ID</th> <th>Install confirmed</th> <th>Winter mode</th> <th>Date created</th> <th>Created by</th> <th>Date updated</th> <th>Updated by</th> </tr> </thead> <tbody> <tr class="text-center"> <td>{{object.location}}</td> <td>{{object.rsu_id}}</td> {% if object.instln_confirmed %} <td><i class="fas fa-check fa-2xl text-primary"></i></td> {% else %} <td><i class="fas fa-x fa-2xl text-danger"></i></td> {% endif %} {% if object.winter_mode %} <td><i class="fas fa-check fa-2xl text-primary"></i></td> {% else %} <td><i class="fas fa-x fa-2xl text-danger"></i></td> {% endif %} <td>{{object.date_created}}</td> <td>{{object.created_by}}</td> <td>{{object.date_updated}}</td> <td>{{object.updated_by}}</td> </tr> </tbody> </table> </div> </div> … -
AWS Pipeline fails when running "container_commands"
Trying to created a CI/CD with AWS Elastic Beanstalk, GitHub and Django. Everything else looks quite fine till I run the migration command. It basically fails when the container commands gets executed. I've tried to run it in different ways but nothing works to me. Try to run the pipeline without the commands and it works fine but of course the app itself won't work without running the migrations . So after retrieving the logs it fails here at the container_commands: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: project.settings "PYTHONPATH": "/opt/python/current/:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: project.wsgi:application NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:proxy:staticfiles": /html: statichtml /static-files: static-files /media: media-files ** container_commands: 10_deploy_hook_permissions: command: | sudo find .platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; sudo find /var/app/staging/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; ** This command will execute a script which is this : #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/manage.py collectstatic --noinput python /var/app/current/manage.py migrate But this is not the issue, Can anyone help pls ?? -
how to call a node js function inside a django page?
i have one web page created in Django , another web page created in node and express js (a function is there to print some barcodes via a barcode printer ) can i call the function from my Django page i am unable to find any idea about how to do whether it is possible or not -
TypeError at /admin_update/2/ BaseForm.__init__() got an unexpected keyword argument 'instance'
I'm trying to update my table view. I passed primary key into update_requests.html so that I can pre-fill the form with the model with the primary key. However, I think it is the problem with model. When I try to access update_requests.html, it shows the error as descripted in the title. Can someone help me with this? urls.py ` path('admin_update/<str:pk>/', views.AdminUpdateRequests, name='admin_update'), ` views.py ` def AdminManageRequests(request): lessons = Lesson.objects.all() return render(request,'admin/manage_requests.html',{'lessons':lessons}) def AdminUpdateRequests(request, lesson_id): lesson = Lesson.objects.get(pk=lesson_id) form = StudentRequestForm(request.POST or None, instance=lesson) context = { 'lesson':lesson, 'form':form } return render(request, 'admin/update_requests.html',context) ` models.py class Lesson(models.Model): lesson_id = models.AutoField(primary_key=True) lesson_name = models.CharField(max_length=255) student = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='studying') teacher = models.ForeignKey(User,on_delete=models.CASCADE, related_name='teaching') start_time = models.DateTimeField(default=timezone.now) interval = models.IntegerField(default=0) duration = models.IntegerField(default=0) created_at = models.DateTimeField(default=timezone.now, blank=True) updated_at = models.DateTimeField(default=timezone.now, blank=True) is_request = models.BooleanField(default=True) number = models.IntegerField(default=-1) price = models.IntegerField(default=-1, blank=True) manage_requests.html ` {% extends 'admin/admin_home_base.html' %} {% block admin_content %} <div> <h3 class="display-8" style="text-align:center"> Admin Lesson Request Management </h3> <hr class="my-4"> <p style="text-align:center"> You can view fulfilled and unfulfilled lesson requests. </p> <p class="lead" style="text-align:center"> {% include 'admin/partials/fulfilled_lessons.html' %} <br> {% include 'admin/partials/unfulfilled_lessons.html' %} </p> </div> {% endblock %} lessons_table_base.html ` ` <div class="card"> <div class="card-header"> <h5 class="card-title">{% block card_title %}{% endblock %}</h5> … -
Django Method Field return Serializer with Hiperlinked field
How can I have a method Field that returns a serializer that has a Hyperlinked field? For example, the Object-1 serializer looks like: from rest_framework import serializers class Object1Serializer((serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api:object-detail') name = serializers.CharField(max_length=50) and Objec2: class Object2Serializer(UserSerializer): objects1 = serializers.SerializerMethodField() def get_objects1(self, obj): objects1 = models.Objects1.objects.get_queryset_by_user(user=obj) serializer = Object1Serializer(objects1, many=True) # serializer.context.update({'request': self.context['request']}) return serializer.data There is a problem here: the url field in Object1 needs a context to construct the url of the field, but I don't know how to get around this. I tried updating the Object1 serializer context, but it doesn't seem to work. -
While using Django GraphQL Auth package, I am able to achieve all the functionality but somehow the passwordReset mutation is always timing out. Why?
I have a GraphQL API in Django which uses the Django GraphQL Auth package for implementing auth related mutations. All of my code works as it did before except for the passwordReset mutation. I have a timeout at 30 seconds in my Gunicorn server and always the passwordReset mutation timesout. I am not seeing any errors in the log. I tried running it locally and the same code seems to work just fine. This seems unusual considering I don't see a reason why a passwordReset should take such a long time to resolve. I am stuck here for a while and don't have any leads on this. Help! -
SQL query to filter on group of related properties
I have a recurring problem in SQL queries, that I haven't been able to solve elegantly, neither in raw SQL or the Django ORM, and now I'm faced with it in EntityFramework as well. It is probably common enough to have its own name, but I don't know it. Say, I have a simple foreign key relationship between two tables, e.g. Book 1 <- * Tag A book has many tags and a tag has one book, i.e. the Tag table has a foreign key to the book table. Now, I want to find all books that have "Tag1" and "Tag2". Raw SQL I can make multiple joins SELECT * FROM books JOIN tags t1 on tags.book_id = books.id JOIN tags t2 on tags.book_id = books.id WHERE t1.tag = 'Tag1' AND t2.tag = 'Tag2' Cool, that works, but doesn't really seem performant Django In django, I could do something similar Book.objects.filter(tags__tag="Tag1").filter(tags__tag="Tag1") Changing filters like that will cause the extra joins, like in the raw SQL version EntityFramework LINQ I tried chaining .Where() similar to changing Django's .filter(), but that does not have the same result. It will build a query resembling the following, which will of course return nothing, because … -
Subsequent Django Unittests raise "MySQLdb.OperationalError: (2006, '')"
I am unittesting a method creating an HttpReponse and delivering a CSV file. def _generate_csv(self): filename = self._get_filename('csv') # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s' % filename writer = csv.DictWriter(response, csv_header_list, delimiter=";") writer.writeheader() for obj in object_list: writer.writerow(csv_dict) response.close() return response When running my unittests, all test before this tests passt but all subsequent fail with this obscure error: MySQLdb.OperationalError: (2006, '') Any idea why testing this method breaks the other tests? Thx! -
Comment recuperer la donnée d'une vue django et la comparer à la donnée d'un template django pour la sauvegarder? [closed]
Je suis entrain de vouloir récupérer les données dans un formulaire et de les enregistrer dans la base de données. if request.method == 'POST': date = request.POST.get("date") libelle = request.POST.get("libelle") operation = request.POST.get("operationListe") piece_justificative = request.POST.get("piece_justificative") client_Fournisseur = request.POST.get("client_Fournisseur") mouvement_Encaiss = request.POST.get("mouvement_Encaiss") mouvement_Decaiss = request.POST.get("mouvement_Decaiss") Sauf que pour la variable opération, dans models.py il a une ForeignKey : class Caisse(models.Model): numero_ordre = models.IntegerField(editable=False, verbose_name='Numéro d\'ordre', null=True) libelle = models.CharField(max_length=255, verbose_name='Libellé', null=False) date = models.DateField(verbose_name='Date', null=False) operation = models.ForeignKey(OperationType, on_delete=models.CASCADE, null=False, blank=False, verbose_name='operation') # type: ignore piece_justificative = models.CharField(max_length=255, verbose_name='Pièce justificative', blank=True, null=True) client = models.CharField(max_length=255, verbose_name='Client', blank=True, null=True) fournisseur = models.CharField(max_length=255, verbose_name='Fournisseur', blank=True, null=True) encaissement = models.IntegerField(verbose_name='Mouvement des encaissements', blank=True, null=True) decaissement = models.IntegerField(verbose_name='Mouvement des décaissement', blank=True, null=True) report_solde = models.IntegerField(verbose_name='Solde du début du mois', blank=True, null=True) class OperationType(models.Model): list_of = models.CharField(max_length=255) Quand je prend directement les données du formulaire, Django me dit que la donnée stockée dans operation en provenance du formulaire doit être du type OperationType : ValueError J'ai donc essayé ce-ci: caisse = Caisse.objects.create( date = date, libelle = libelle, operation = OperationType.objects.get(operation), piece_justificative = piece_justificative, client_Fournisseur = client_Fournisseur, mouvement_Encaiss = mouvement_Encaiss, mouvement_Decaiss = mouvement_Decaiss, ) Mais je tombe dans une autre impasse: ValueError Je vous serrai … -
How can I handle 400 bad request error using DRF in Django
I am trying to perform a POST request using DRF in Django, the program is raising a 400 error (this is the error, Bad Request: /api/menu_items/, the frontend is raising the following error (This field is required) the problem is I cannot see the exact field that is missing. How can I locate the missing field? The error occurs when I try to post a new Menu item. ** This is the place model ** # Place models class Place(models.Model): # When User is deleted the Place gets deleted too owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) image = models.CharField(max_length=255) number_of_tables = models.IntegerField(default=1) def __str__(self): return "{}/{}".format(self.owner.username, self.name) **This is the Menu Item model ** class MenuItem(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="menu_items") name = models.CharField(max_length=255) description = models.TextField(blank=True) price = models.IntegerField(default=0,) image = models.CharField(max_length=255) is_available = models.BooleanField(default=True) def __str__(self): return "{}/{}".format(self.category, self.name) ** This are the serialisers ** * the error is occurring in the MenuItemSerializer * from rest_framework import serializers from . import models class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = models.MenuItem fields = ('id', 'name', 'description', 'price', 'image', 'is_available', 'place', 'category') class CategorySerializer(serializers.ModelSerializer): menu_items = MenuItemSerializer(many=True, read_only=True) class Meta: model = models.Category fields = ('id', … -
FileNotFoundError: [WinError 2] The system cannot find the file specified :-(?
(python_net) PS C:\Users\saman\desktop\my_project\python_net> python who_is.py Traceback (most recent call last): File "C:\Users\saman\desktop\my_project\python_net\who_is.py", line 11, in <module> result = whois.query('instagram.com') File "C:\Users\saman\python_net\lib\site-packages\whois\__init__.py", line 351, in query whois_str = do_query( File "C:\Users\saman\python_net\lib\site-packages\whois\_1_query.py", line 64, in do_query _do_whois_query( File "C:\Users\saman\python_net\lib\site-packages\whois\_1_query.py", line 147, in _do_whois_query p = subprocess.Popen( File "C:\Users\saman\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 969, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\saman\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1438, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] The system cannot find the file specified i am a programmer python my goal find erros in python for delevopers to coding better -
How to override model field in Django for library model?
I need to override library model field in Django. This model is integrated in that library and used there. The changes I need is to add a unique constraint to one of the model fields. But this is not the abstract model so I can't inherit this model as I understand. The question: is there a way to override usual model field in Django without inheritance? -
Python Django 2.2.16
I am running this command on source django when I get this error: python run manage.py localhost:8000 django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal203", "gdal202", "gdal201", "gdal20", "gdal111"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I need help right now? -
Using annotated field to order_by in Django
So I have a queryset that has an annotated value that uses conditional expressions in it: def with_due_date(self: _QS): self.annotate( due_date=models.Case( *[ models.When( FKMODEL__field=field, then=models.F('created_at') - timedelta(days=days) ) for field, days in due_date_mapping.items() ], output_field=models.DateTimeField(), ), ) return self Once trying to apply order_by on this queryset by the annotated value I get an error that the field cannot be resolved File "/code/api/nodes.py", line 2577, in add_order_by return qs.order_by( File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1295, in order_by obj.query.add_ordering(*field_names) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 2167, in add_ordering self.names_to_path(item.split(LOOKUP_SEP), self.model._meta) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1677, in names_to_path raise FieldError( graphql.error.located_error.GraphQLLocatedError: Cannot resolve keyword 'due_date' into field. Choices are: How come I cannot order by the annotated field value here? -
how to get email source endpoints for resulting emails in django rest framework
I've created email tool that will validate,find and domain finding tool in django rest framework. I've used Isitarealemail api's to integrate to find email validation, finding. but for searching domain ive used email finder (emailfinder==0.3.0b0) library, it used to find the domains using google search. it also successfully returns the emails present in the domains, but what i also need is source endpoint (urls of the email link from where it found). how to get it. i've posted the code below This is my views.py file class email_from_google(APIView): def get(self, request): raw_domain = request.query_params.get('domain_name') if raw_domain is not None and raw_domain != '': if raw_domain[-1] == '/': raw_domain = raw_domain.replace('/', '') pattern = re.findall('https|http|www', raw_domain) if raw_domain is not None and pattern == []: try: search_query = Google_email_model.objects.get(domain=raw_domain) return Response(search_query.emails) except: scraped_email = get_emails_from_google(str(raw_domain)) scraped_email_count = len(scraped_email) if scraped_email_count != 0: google_emails = dict(emails=scraped_email,email_count=scraped_email_count) query_data = Google_email_model.objects.create(domain=raw_domain,emails=google_emails) query_data.save() return Response(google_emails,links, status=status.HTTP_200_OK) no_email = dict(emails=[], email_count=[]) return Response(no_email) error = dict(error='valid domain required') return Response(error) error = dict(error='valid domain required') return Response(error) This is my emailfinder domain google.py file def search(target, proxies=None, total=200): emails = set() start = 0 num = 50 if total > 50 else total iterations = int(total/num) … -
Make option HTML tag set something in the url - Django
I am trying to do something, but I don't know if it's acutally possible... Basically I'm trying to pass information in the url... (something like this) <form class="header__search" method="GET" action=""> <input name="q" placeholder="Browse Topics" /> </form> but instead of using a text input I would like the user to simply click an option in a dropdown menu... (like this) <form action="" method="GET"> <div class="units-div"> <label for="units">Units:</label> <select name="units" id="units-selection"> <option value="metric">Metric</option> <option value="imperial">Imperial</option> </select> </div> <div class="language-div"> <label for="language">Language:</label> <select name="language" id="language-selection"> <option value="english">English</option> <option value="italian">Italian</option> </option> </select> </div> </form> Is it possible to do so? Hopefully I've explained myself decently lol -
Django: 'Couldn't reconstruct field' on subclass of `OneToOneField`
I've made a field Extends with this super short declaration: class Extends(models.OneToOneField): def __init__(self, to, **kwargs): super().__init__( to, on_delete=models.CASCADE, primary_key=True, **kwargs ) However, if i use this as a field in a model, say class Person(models.Model): user = Extends(User) I get the following error, when making migrations: TypeError: Couldn't reconstruct field user on app.Person: Extends.__init__() missing 1 required positional argument: 'to' I'm struggling to understand what this means. How can I fix it? -
How to auto increament unique number with a prefix?
How can i increment an invoice number with a prefix “INV” and number that increments ‘0001’, ‘0002’, ‘0003’......and so on..... when the user creates an invoice? class Invoice(model.Models): clients_name = models.ForeignKey(Clients, on_delete=models.CASCADE, blank=True,null=True) invoice_number = invoice_number = models.CharField(max_length=200, blank=True, null=True) once the user creates/saves the invoice form, the hidden field(invoice field) should be autofilled with invoice number e.g. | client | invoice| | -------- | -------- | | client_name1 | INV-001 | | client_name2 | INV-002 | | client_name4 | INV-003 | | client_name8 | INV-004 | -
Accessing field from OneToOne field in ModelForm using Class based Views
I have created a model Agent that is in a OneToOne relation with the User model. I managed to create a form where I can edit the Agent(user) details, but I would like to populate the form with the existing details of the model(Agent/user). Found something similar here but it is not using Class based views. models.py -> class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.user.email forms.py -> from django import forms from django.contrib.auth import get_user_model User = get_user_model() class AgentModelForm(forms.ModelForm): class Meta: model = User fields = ( 'email', 'username', 'first_name', 'last_name' ) views.py -> class AgentUpdateView(OrganisorAndLoginRequiredMixin,generic.UpdateView): template_name = "agents/agent_update.html" form_class = AgentModelForm queryset = Agent.objects.all() def get_success_url(self): return reverse("agents:agent_list") -
Uploading images in Django-React framework returns error 403
I am building an app in Django-React that requires me to upload some images into a folder. When I submit the upload button I get error 403 on the request. Looking at the console, the response says: "CSRF Failed: CSRF token missing or incorrect." I have tried adding the @csrf_exempt decorator over the function in views.py but that is not working. Here's an extract of the relevant code: settings.py MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'frontend', 'build', 'static', 'assets') urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, re_path from django.views.generic import TemplateView from woundapp import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('upload/', views.upload_images), path('admin/', admin.site.urls), ... re_path(r".*", TemplateView.as_view(template_name="index.html")), ] urlpatterns = format_suffix_patterns(urlpatterns) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models class Image(models.Model): image_url = models.ImageField(upload_to='unprocessed/') serializers.py from rest_framework import serializers from .models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'image_url' ] views.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import os from .models import Image from .serializers import ImageSerializer import requests from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_view(['POST']) @csrf_exempt def upload_images(request, format=None): if … -
django forms - CSS alignment
I am pretty new to CSS, however I have a django modelformset_factory which i need to render and align all rendered fields in same line for each field, it has TextArea and Textinput, the problem as per the attached picture i tried to aligned all but they never get aligned together. here my view: from django.forms import modelformset_factory def form_employee(request, employee_id): employee = Employee.objects.get(pk=employee_id) Employee_PM = PMF.objects.filter(badge=employee_id) for pm in Employee_PM: form_reference = pm.form_ref emp_form = PMF_Form.objects.filter(form_ref=form_reference) emp_summary = PMF_Summary.objects.filter(badge=employee_id) PMF_formset = modelformset_factory(PMF_Form, fields=('objective','obj_desc','rating',), extra=0) formset = PMF_formset(queryset=PMF_Form.objects.filter(form_ref=form_reference)) if request.method == "POST": formset = PMF_formset(request.POST, queryset=PMF_Form.objects.filter(form_ref=form_reference)) if formset.is_valid(): formset.save() return redirect('/') for form in formset: form.fields['objective'].widget.attrs['disabled'] = True form.fields['obj_desc'].widget.attrs['disabled'] = True context = {"Employee_PM":Employee_PM,"employee":employee,"emp_form":emp_form,"emp_summary":emp_summary,"formset":formset} return render(request, 'PMS/form_employee.html',context) \* { padding: 2px; margin: 0px; margin-bottom: 4px; background-color: black; color: aliceblue; box-sizing:border-box; flex-direction: column; } .container { background-color: black; } body { background-color: black; } .form2 { margin: 20px; box-sizing: border-box; width:100%; resize: none; overflow-wrap: break-word; /\* display: flex; \*/ margin: auto; } input { /\* width: 50%; \*/ display: inline-block; width:15rem; height: 70px; position: relative; } textarea { width: 50rem; height: 70px; resize: none; } } span { justify-content: center ; display: flex; } <div class="container"> <h2>formset</h2> <form method="POST" class="form2" enctype="multipart/form-data"> … -
Django form 2 not loading
I am trying to build a inventory management project facing some difficulty, Looking for a solution. I have created a 2 form in django model and when I try to load form2 only form1 is loading for all the condition. I have tried to comment form1 and load only form2 with that I got the expected result but when I try to add run with both the forms I am facing the issue. Additional to this in django admin panel I am getting I am getting both the forms as expected. Any kind of help will be appreciated. Views.py from .models import Inventory_Details, Incoming_QC from .forms import MyForm, Incoming_QC_form def my_form(request): if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): form.save() return HttpResponse('Submitted successfully') #return redirect('/home_page/') else: form = MyForm() return render(request, "authentication/Inventory_details.html", {'form': form}) def View_Inventory(request): Inventory_list = Inventory_Details.objects.all() return render(request,'authentication/View_Inventory.html', {'Inventory_list': Inventory_list}) def Incoming_qc_form(request): if request.method == "POST": QC_form = Incoming_QC_form(request.POST) if QC_form.is_valid(): QC_form.save() return HttpResponse('Submitted successfully') #return redirect('/home_page/') else: QC_form = Incoming_QC_form() return render(request, "authentication/Incoming_QC.html", {'QC_form': QC_form}) def View_Incoming_QC(request): Incoming_QC_list = Incoming_QC.objects.all() return render(request,'authentication/View_Incoming_QC.html', {'Incoming_QC_list': Incoming_QC_list}) urls.py url(r'form', views.my_form, name='form'), path('View_Inventory', views.View_Inventory, name="View_Inventory"), url(r'QC_form', views.Incoming_qc_form, name='QC_form'), path('View_Incoming_QC', views.View_Incoming_QC, name="View_Incoming_QC") html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, … -
Show 'POST' method API in urls.py and browser url list
Currently I got create a new API with method('POST') how I can set it in the urls.py so that when I runserver, at the browser able to found this API view.py @transaction.atomic @api_view(['POST']) def posting_simain_api(request,): print("Start Time"+ str(panda.panda_toda urls.py from django.urls import include, path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'ts_TsSimain', views.TsSimainViewSet) router.register(r'ts_TsSimain_parent', views.TsSimainViewSet_parent) urlpatterns = [ path('', include(router.urls)), path('posting_simain_api', views.posting_simain_api, name='posting_simain_api'), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Question is how I going to show this API in this list? enter image description here I want to show the API in the list here, so that Frontend Developer able to know what API are ready -
How to convert this quesry into Django ORM
SELECT * FROM SUbPlans LEFT JOIN orders on SUbPlans.empId=orders.selected_id where orders.user_id=2 I have this query that I want to convert into Django ORM. What I did was : orders = orders.objects.filter(user_id=2).first() userid = orders.some_field subplans = SUbPlans.objects.filter(another_field=some_field) I just want to do this using select_related. SUbPlans and orders are connected via foriegn key -
OpenEdx error while running python code in Codejail Plugins using Dockerize container services
I have installed a stack of OpexEDX platform using Tutor and installed OpexEdx "Codejail" plugin using below link pip install git+https://github.com/edunext/tutor-contrib-codejail https://github.com/eduNEXT/tutor-contrib-codejail I am facing a problem during working on the code jail while importing python matplotlib library. importing the same library inside codejail container is working fine. the only problem is import through OpnexEdx code block. > advance black > problem. I have already installed the Codejail and Matplotlib on docker. I have to run this code. which gives error <problem> <script type="loncapa/python"> import matplotlib </script> </problem> import os but getting error on the import matplotlib open edx version : openedx-mfe:14.0.1 code jail version : codejailservice:14.1.0 please see the error message below cannot create LoncapaProblem block-v1:VUP+Math101+2022+type@problem+block@3319c4e42da64a74b0e40f048e3f2599: Error while executing script code: Couldn't execute jailed code: stdout: b'', stderr: b'Traceback (most recent call last):\n File &#34;jailed_code&#34;, line 19, in <module>\n exec(code, g_dict)\n File &#34;<string>&#34;, line 66, in <module>\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 921, in <module>\n dict.update(rcParams, rc_params_in_file(matplotlib_fname()))\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 602, in matplotlib_fname\n for fname in gen_candidates():\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 599, in gen_candidates\n yield os.path.join(get_configdir(), \'matplotlibrc\')\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 239, in wrapper\n ret = func(**kwargs)\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 502, in get_configdir\n return get_config_or_cache_dir(_get_xdg_config_dir())\n File &#34;/sandbox/venv/lib/python3.8/site-packages/matplotlib/__init__.py&#34;, line 474, in get_config_or_cache_dir\n tempfile.mkdtemp(prefix=&#34;matplotlib-&#34;)\n File …