Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rest Framework Ordering Filter for Models Method
I have a model that has method for calculating average rating. How can I add this method to ordering filter fields? I tried to do custom filter with FilterSet but I cannot manage to do that. I received error when I tested my attempts. There are no any example for Order Filtering. I added a filter for average rating with greater than lookup as it is shared below but I couldnt way to add it for order filtering. Model Class: class Establishment(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=255, null= False, blank = False, unique=True) description = models.TextField(max_length=360, blank = True, null=True) address = models.TextField(max_length=360, blank = True, null=True) phone = PhoneNumberField(null=False, blank=False) city = models.CharField(max_length=15, null= False, blank = False) district = models.CharField(max_length=50, null= False, blank = False) latitude = models.DecimalField(max_digits=9, decimal_places=6, null=False, blank=False) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=False, blank=False) cuisine = models.CharField(max_length=255, null= False, blank = False) zipcode = models.IntegerField(null=True, blank=True) average_price = models.IntegerField(blank = True, null=True) profile_photo = models.ImageField(blank=True, null=True, upload_to=upload_path('profile_image')) def no_of_ratings(self): ratings = EstablishmentRating.objects.filter(establishment=self) return len(ratings) def average_rating(self): ratings = EstablishmentRating.objects.filter(establishment=self) return sum(rate.rating for rate in ratings) / (len(ratings) or 1) def __str__(self): return self.name Related ViewSet: class EstablishmentViewSet(viewsets.ModelViewSet): queryset = Establishment.objects.all() serializer_class = EstablishmentSerializer … -
Django Dump Json Data for recommended recipes
Hi everyone I'm looking for help on how to accomplish this. I'm building a Rest API and want to dump an existing db table filled with recipes. this table can be search by users and have recipes selected from the table. Can this be done? is there a command to dump a existing db to json data? I know django will auto create the models, do i then just have to write the serializer and views to search this data and have an authenticated user be able to add a recipe from this to their own list? NOT LOOKING FOR CODE BEYOND SIMPLE COMMANDS. Looking for advice on how to accomplish this? Thanks -
Pop-up message after submiting a form in django
I'm building a website with django, and I have the newsletter functionality. I'm not so good on the frontend but I want to implement a toggle message after the submit button is clicked. I'm not sure how am I suppose to handle this. I've connected the newsletter form with the pop-up message, but the problem is that when the submit is clicked the page is reloaded because of the view function, I tried to not return a redirect but in this case and in the first with the redirect function it doesn't display me the message. the view function def newsletter_subscribe(request): if NewsletterUser.objects.filter(email=request.POST['newsletter_email']).exists(): messages.warning( request, 'This email is already subscribed in our system') else: NewsletterUser.objects.create(email=request.POST['newsletter_email']) messages.success(request, 'Your email was subscribed in our system, you\'ll hear from us as soon as possible !') return redirect('index') newsletter form <section class="bg-gray section-padding"> <div class="container"> <div class="section-intro pb-5 mb-xl-2 text-center"> <h2 class="mb-4">Subscribe To Get Our Newsletter</h2> <p>We post very often on the blog and bring updates on the platform, if you will subscribe you will hear from us everything as soon we made the changes</p> </div> <form class="form-subscribe" action="{% url 'newsletter-subscribe' %}" method="POST"> {% csrf_token %} <div class="input-group align-items-center"> <input type="text" class="form-control" name="newsletter_email" placeholder="Enter … -
How to build a registration and login api using function based views in django rest framework?
I want to create a token authenticated registration and login api using django's built in User model with django rest framework(DRF) using function based views (FBV). Most of the articles which I found in the web are for class based views and there are not much resources available for FBV in the web. From whatever resources including CBV I found in the net, I coded this, # project/settings.py INSTALLED_APPS = [ ... 'rest_framework.authtoken' ] # app/serializers.py from django.contrib.auth.models import User class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user class LoginSerializer(serializers.ModelSerializer): # TO DO # app/views.py @api_view(['POST'],) def register(request): if request.method == 'POST': register_serializer = RegisterSerializer(data=request.data) if register_serializer.is_valid(): print("Its working") return Response({'Failed':'Failed to create'}) @api_view(['POST'],) def login(request): if request.method == 'POST': login_serializer = # TO DO if login_serializer.is_valid(): print("Its working") return Response({'Failed':'Failed to login'}) # app/urls.py urlpatterns = [ path('register/', views.register, name="register"), path('login/', views.login, name="login"), ] The above register and login are not complete and lacks a proper serilizers object and user creation/validation methods. I still tried to run the above code with this post request {id:,username:"user1", email:"email@email.com",password:"password123"}, id was kept … -
I need help regarding structuring django models and quering them with ease
please I need your help with this: I am building a Django web App that will count the total number of persons entering and exiting a school library in a day, week and year and then save to DB. The Web App uses a camera that is controlled by OpenCv to show live feed on frontend (I have successfully implemented this already). My problem is: How can I design and structure my models to store each data by day, week, month and year? And how can I query them to display them on different Bar Charts using chart.js? Thanks. -
Django duplicate queries
I'm trying to optimize my django app using select and prefetch related but for some reason it doesn't work this is my models : class Question(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(blank=True, default='avatar.png') and this is my serializers : class EagerLoadingMixin: @classmethod def setup_eager_loading(cls, queryset): if hasattr(cls, "_SELECT_RELATED_FIELDS"): queryset = queryset.select_related(*cls._SELECT_RELATED_FIELDS) if hasattr(cls, "_PREFETCH_RELATED_FIELDS"): queryset = queryset.prefetch_related(*cls._PREFETCH_RELATED_FIELDS) return queryset class QuestionSerializer(EagerLoadingMixin, serializers.ModelSerializer): profile = serializers.SerializerMethodField() class Meta: model = Question fields = ( 'id', 'title', 'author', 'profile', 'content', ) _SELECT_RELATED_FIELDS = ['author'] _PREFETCH_RELATED_FIELDS = ['author__profile'] @staticmethod def get_profile(obj): profile = Profile.objects.get(user=obj.author) return ProfileSerializer(profile).data but that's what i get in django debug toolbar SELECT ••• FROM "accounts_profile" WHERE "accounts_profile"."user_id" = 14 LIMIT 21 10 similar queries. -
error while deploy Django app to Namecheap error in passenger_wsgi.py file
App 649063 output: File "/home/techmjiu/techpediaa/passenger_wsgi.py", line 1, in <module> App 649063 output: App 649063 output: from blog_app.wsgi import application App 649063 output: ModuleNotFoundError: No module named 'blog_app.wsgi' passenger_wsgi.py file : from blog_app.wsgi import application when i open website it show ..... We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. how to fix this -
how can in create a model for each user in Django?
i am trying to create a model for each user. and I want, the user o be able to upload a file to them model. for example the user be able to upload a file to them model fro this template: {% block content %} <form method="post" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple="multiple" /> <p class="container" style="margin-top: 10px"> <input type="submit" value="upload" class="btn btn-primary" /> </p> </form> {% endblock%} i need a sample code for form.py, model.py, views.py, -
Django + Ajax: Table header repeating after refresh
I am trying to refresh a table after an Ajax call but it isn't functioning as expected. When refreshing the table header (table id="requesttable") repeats like this: Is this due to the Django for loops I have within the template tags or is my javascript the error? I havent been able to figure out what is causing the issue. On the ajax call it is succesful and the item is adding into the table and on a browser refresh the table returns to normal with the correct data. Is it better to build in each additional entry as a row rather than refresh the table? script: $(document).on('submit','#RequestForm',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '/request_new/' + track_id + '/', data:{ req_type:$("#req_type").val(), email:$("#email").val(), first_name:$("#first_name").val(), last_name:$("#last_name").val(), licensor:$("#licensor").val(), percentage:$("#percentage").val(), propossed_fee:$("#propossed_fee").val(), agreed_fee:$("#agreed_fee").val(), mfn:$("#mfn").prop('checked'), //template:$("#template"().val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ $('#add_request').modal('hide'); $("#requesttable").load(window.location + " #requesttable"); }, }) }); HTML: <div class="container-fluid"> <div class="row">... </div> <div class="card shadow mb-4"> <div class="card-body"> {% for track in trackdata %} <div class="card"> <div class="card-header">... </div> <div class="tab-content"> <div role="tabpanel" class="tab-pane" id="stats{{track.pk}}">... </div> <div role="tabpanel" class="tab-pane active" id="details{{track.pk}}">... </div> <div role="tabpanel" class="tab-pane" id="request{{track.pk}}"> <br> <div class="container-fluid"> <div class="row"> <div class="table-responsive"> <table class="table table-hover table-borderless table-sm" id="requesttable"> <thead class="thead-dark"> <tr> <th scope="col" >Type</th> <th scope="col" … -
How to pass multiple parameters of unknown length from react to django url
I have to pass multiple parameters to a Django view through Django URL.I am passing the values from React fetch.The list of parameters is variable.For example,it could be 2 sometimes and 3 or 4 sometimes. I have following urls.py file path('getallvalues/<pk>',views.MultipleValueView.as_view()) views.py class MultipleValueView(APIView): def get(self,request,*args,**kwargs): serializer_class=ValueSerializer listoftopics=["test","test2"] return Response({"weights":getMultipleValueJourney(listoftopics)[0],"years":getMultipleValueJourney(listoftopics)[1]}) React code: fetch("http://127.0.0.1:8000/getallvalues/"+valueList) .then(response => response.json()) .then(json => { var {years,weights}=this.state; this.setState({ weights:json.weights, years:json.years, }} How could I structure my urls.py file?I have seen certain answers from stackoverflow but none of them worked in my scenario. -
Django: Track specific user actions
How can I track specific user actions with Django. For example: user logged in user changes password user visited a specific page rest api call within a specific view took 300ms user deleted / updated / created a specific model Is there a nice third party app which can do this for me and display this information in an human readable admin interface or at least in django-admin? If there is no app out there. How would you do this with Django? -
Django recieve ajax post from javascript
I want to recieve ajax from javascript to django views(below) ajax successfully posted And from views, I want to send httprequest but problem is I don't know how exactly convert recieved ajax to base64 string. I'm not used to these kind of data format Please help me audio: base64 string have to be here -
Django/Python generate and unique Gift-card-code from UUID
I'm using Django and into a my model I'm using UUID v4 as primary key. I'm using this UUID to generate a Qrcode used for a sort of giftcard. Now the customer requests to have also a giftcard code using 10 characters to have a possibility to acquire the giftcard using the Qrcode (using the current version based on the UUID) as also the possibility to inter manually the giftcard code (to digit 10 just characters). Now I need to found a way to generate this gift code. Obviously this code most be unique. I found this article where the author suggest to use the auto-generaed id (integer id) into the generate code (for example at the end of a random string). I'm not sure for this because I have only 10 characters: for long id basically I will fire some of available characters just to concatenate this unique section. For example, if my id is 609234 I will have {random-string with length 4} + 609234. And also, I don't like this solution because I think it's not very sure, It's better to have a completely random code. There is a sort regular-format from malicious user point of view. Do … -
Django Concat cannot be used in AddConstraint
I have a constraint like this CheckConstraint( check=Q(full_path__endswith=Concat(Value("/"), F("identifier"), Value("/"))) # | Q(full_path="/"), name="path_endswith_identifier_if_not_root", ), Makemigrations runs fine, but when I try to actually migrate the generated migration, I get IndexError: tuple index out of range ... File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) IndexError: tuple index out of range When I ran sqlmigrations for the generated migration, I get the following error TypeError: not enough arguments for format string. Here is the full error message: ... File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 345, in add_constraint self.execute(sql) File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 132, in execute self.collected_sql.append((sql % tuple(map(self.quote_value, params))) + ending) TypeError: not enough arguments for format string The string that django tries to format here is: ALTER TABLE "documents_directory" ADD CONSTRAINT "path_endswith_identifier_if_not_root" CHECK (("full_path"::text LIKE '%' || REPLACE(REPLACE(REPLACE((CONCAT('/', CONCAT("documents_directory"."identifier", '/'))), E'\\', E'\\\\'), E'%', E'\\%'), E'_', E'\\_') OR "full_path" = '/')) and the tuple is empty I have tried the following things to rule out plain stupidity: Use Concat(Value("/"), F("identifier"), Value("/")) in an annotation, this works like a charm Replace Value("/") with … -
AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'
i was trying to make my first ecommerce website using django and i stuck at this error like 1 days, i already search in google but i can't find how to fix it. please help me to find the error. this is my code, if u need more just tell me i really need an answer thx i hope someone will help me cart.js : ''' var updateBtns = document.getElementsByClassName('update-cart') for (var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function () { var productId = this.dataset.product`enter code here` var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser') { console.log('Not logged in') } else { updateUserOrder(productId) } }) } function updateUserOrder(productId, action) { console.log('User is logged in, sending data...') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'productId': productId, 'action': action }) }) .then(response => response.json()) .then((data) => { console.log('data:', data); } ); } views.py : from django.shortcuts import render from django.http import JsonResponse from django.http import HttpRequest import json from .models import * def store(request): products = Product.objects.all() context = {'products': products} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, … -
Django query filter with contains and empty list variable
matched = Details.objects.filter(Q(cnp=cnp) | Q(phones__contains=[phone]) | Q(emails__contains=[email])).values('id') class Details(models.Model): ... cnp = models.CharField(max_length=24, blank=True) phones = ArrayField(models.CharField(max_length=50), size=20, blank=True, default=list) emails = ArrayField(models.EmailField(), size=20, blank=True, default=list) Hello! I want to make a query and if any of the fields(cnp,phones or emails) have a match to get the result queryset. The cnp, phone and email variable will get just one value that I need to match with one or more values from the ArrayField. I made the query above using Q but the problem is that I can have empty list/string for phone or email variable and then that matches all my database. If i don't use 'contains', I can match single valued lists(from the db ArrayField) but for example if I have multiple emails in the db I need to match it with 'contains' to get a result. Is this possible only from a django query? Thanks! -
Multiple Django records for one user
I want to add multiple values for a user in Django. in that a user may have several records displayed. Records should belong to a specific user selected. Models.py looks like : class Medrecs(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=60, null=True) clinician = models.ForeignKey(Clinician, on_delete=models.PROTECT) Patient = models.ForeignKey(Patient, on_delete=models.CASCADE) meds = models.TextField() def __str__(self): return self.title models.ForeignKey doesnt work either. It displays records to all patients but I want a specific patient/user selected. OneToOne will display for specific user but only once. Views.py looks like: def my_profile(request): meds = Medrecs.objects.all() if request.user.is_authenticated: return render(request, 'MyDoc/my_profile.html', {'meds': meds}) else: return redirect('MyDoc:login_patient') And my template looks like : {% if meds %} {% for m in meds %} <div class="col-sm-6 panel-primary"> <img class="logo" style="height: 35px; width: 35px; margin-right: 15px;" src="{{ user.patient.image.url }}"> <p>St.Denvers Hospital,</p><br> <p>Healthcare is our compassion</p> <p>{{ m.title }}</p> <div class="panel panel-primary"> <div class="panel-heading active"> <h3 class="text-success">Doctor:{{ m.clinician }}</h3> <p>Name: {{ m.patient }}</p> </div> <div class="panel-body"> <p>Medication: {{ m.meds }}</p> </div> </div> </div> {% endfor %} {% endif %} This works fine but i can only add one patient record and i want multiple for the same user. At the Django database it tells me theres a record … -
Filter data /Disregard null value when filtering in Django
Does anybody know how can I filter data even the passing value is False, it so hassle to make lot of conditions I think there is a way to filter data even the value is false or empty. views.py def sample(request): if request.method=='POST': province = request.POST.get('province', False) municipality = request.POST.get('municipality', False) barangay = request.POST.get('barangay', False) status = request.POST.get('stats', False) batch= request.POST.get('Pbatch', False) it_batch= request.POST.get('Itbatch', False) filter= Person.objects.filter(province=province, municipality=municipality, barangay=barangay,status=status,batch=batch,it_batch=it_batch) return render .. so on and so on... The problem is when some data has no value or let say false it didn't recognize the data filter, is there any solution or idea how to achieve this? -
Django modelformset_factory Filter ForeignKey
Im stuck with this for days, Need help to filter this Item_formset: https://prnt.sc/vlgow4, so its only show record with Price_list.jenis = "Produk" as you can see below, the Model Item.item have a ForeignKey(Price_list), which i need to be filter based on Price_list.jenis record, whic is also have a foreignKey on Jenis_Pricelist, My models.py class Jenis_Pricelist(models.Model): jenis = models.CharField(max_length=10) def __str__(self): return self.jenis class Price_list(models.Model): nama_item = models.CharField(max_length=100, null=True) jenis = models.ForeignKey(Jenis_Pricelist, on_delete=models.PROTECT) def __str__(self): return f"{self.jenis} - {self.nama_item} - Rp{prc:,}" class Item(models.Model): item = models.ForeignKey(Price_list, on_delete=models.PROTECT, null=True) jumlah = models.IntegerField(default=1, blank=True, null=True) harga = models.DecimalField(max_digits=1000, decimal_places=2, null=True) def __str__(self): return self.item my forms.py Item_formset = modelformset_factory( Item, fields=('item', 'jumlah', 'harga'), extra=1, ) my view.py def crt_anm(request): template_name = 'pasien/profil/create_anamnesa.html' kontrol = Form_Anamnesa() item_formset = Anamnesa_Formset(instance=Price_list.objects.filter(jenis_id=3)) return render(request, template_name, { 'anamnesa': kontrol, 'item_formset': item_formset, }) -
Is it possible to have Read and Update inside the same View using Django?
I mean I have a project for inventory control. I wanted to create a single page where I could display the items and aside of the item I would have buttons like Update and Delete. When, say, Update is clicked a popup would appear (in the same page, just like when you open a website and there's that block telling you about cookies, or any promotion of the website you're surfing in). My tries so far: Javascript -> const handleUpdate = (url) => { const Http = new XMLHttpRequest(); url='localhost:8000'; Http.open("POST", url); Http.send(); Http.onreadystatechange = (e) => { console.log(Http.responseText) } } So when I click the button I would get the returned object. I know. Terrible. Quantum List -> While typing I thought: What if I created a form for every single model?! Yeah... 300+ IQ... And if I had like a thousand entries my html would be just like one of those physics book about the quantum universe. So question is: How would you go about that? And actually is there a way of doing it? -
What is the best way to serve static files like image and videos in a react django docker and nginx web app?
I was developing a web app with decoupled frontend and backend with SPA using react and the backend with django and am using docker to containeraize the servers and I don't know what is the best way to serve or to put the static files like image and video. -
My flow of code is not entering into if loop in django views.py
This is the part of code in django views.py , the flow of code is not entering into if loop and directly entering into else and creating problems. Why it is not entering into if(w == '3 Standard Deviation') , this loop ? I want to check if w or z == 3 Standard Deviation or 2 Standard Deviation then save csv file to respective static folder . @csrf_exempt def home(request): #import pdb; pdb.set_trace() global path_of_uploaded_csv if request.method == 'POST': UploadedData = UploadForm(request.POST, request.FILES) if UploadedData.is_valid(): # Dataframe try: dataframe = pd.read_csv(request.FILES['file']) except: return render(request, 'home.html', {'message': True}) No_of_Rows = dataframe.shape[0] d_frame = request.FILES['file'] # import pdb; pdb.set_trace() # File Storage on Disks fs = FileSystemStorage() fs.save(d_frame.name, d_frame) # list of columns df = dataframe.select_dtypes(exclude=["bool_", "object_"]) list_for_pop = df.columns import csv path_of_uploaded_csv = request.FILES['file'] import json json_object = {list_for_pop.get_loc( c): c for idx, c in enumerate(list_for_pop)} path_of_uploaded_csv.flush() return render(request, 'home.html', {'DataFrame': dataframe, 'item': list_for_pop, 'path': path_of_uploaded_csv, 'json_response': json_object, 'noOfRows': No_of_Rows}) elif(request.POST.get): # Dependent dropdown try: dpost_list = request.POST.getlist('dropdown1') except: return render(request, 'home.html', {'warning1': True}) print(dpost_list) # Independent Dropdown try: ipost_list = request.POST.getlist('dropdown2') except: return render(request, 'home.html', {'warning2': True}) w = request.POST.getlist('3std') z = request.POST.getlist('2std') #import pdb; pdb.set_trace() df_path = request.POST.get('path') … -
why django wizard form values disappear when I step back?
It's been days I am trying to split up a simple django form with some charfield and dropdowns to sub forms using django-formtools. I the first step I left 2 dropdowns field and in the second step, 2 char fields and one image file. Once I change dropdowns and go to the second form and vice versa, this is what happens: dropdown values will be kept till I submit the whole form and then will be reset. In the second step, what ever I add, whether char values or image file will be disapear after stepping back to the previews page. I tried to add get_form() and get_context_data() methods. But does not work: here is the code: class NewWizard(NamedUrlSessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos')) def done(self, form_list, **kwargs): ..... def get_form(self, step=None, data=None, files=None): if self.steps.current == 'step_first': step_files = self.storage.get_step_files(self.steps.current) print('step_filesA:', step_files) # return None else: step_files = self.storage.current_step_files print('step_filesB:', step_files) # return None if step_files and files: for key, value in step_files.items(): if files in key and files[key] is not None: step_files[key] = files[key] elif files: step_files = files return super(NewWizard, self).get_form(step=self.steps.current, data=data, files=step_files) def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) if self.steps.step1 == '1': data_step = self.get_cleaned_data_for_step(int(self.steps.step1)+1) … -
To generate a table from a nested list in Django template
I have a nested list as such: dataList = [['Route To Path/file1.txt', 'Route To Path/file2.txt', 'Route To Path/file3.txt', 'Route To Path/file4.txt'], [['Routing', 'Error'], ['Routing', 'Error'], ['Routing', 'Error'], ['Routing', 'Error']], [[['file1.txt', 'Mapping error']], [['file2.txt', 'Mapping error']], [['file3.txt', 'Mapping error']], [['file4.txt', 'Mapping error']]]] My intention is to generate a table like below: Route To Path/file1.txt Routing Error file1.txt Mapping error Route To Path/file2.txt Routing Error file2.txt Mapping error etc... However with my code below, the table I get is: Route To Path/file1.txt Route To Path/file2.txt Routing Error Routing Error file1.txt Mapping error file2.txt Mapping error Can somebody point me where is my error on below code? <table id="myTable"> <thead> </thead> <tbody> {% for k in dataList %} <tr> {% if forloop.counter0 == 0 %} {% for i in k %} <tr> <td> {{ i }} </td> </tr> {% endfor %} {% elif forloop.counter0 == 1 %} {% for i in k %} <tr> <td> {{ i.0 }} </td> <td> {{ i.1 }} </td> </tr> {% endfor %} {% elif forloop.counter0 == 2 %} {% for i in k %} {% for j in i %} <tr> <td> {{ j.0 }} </td> <td> {{ j.1 }} </td> </tr> {% endfor %} {% endfor … -
Angular->Php->Python or Angular->Django, Python in PHP
I have a graduation project. I made the frontend development with Angular. There is also a machine learning system I built using Python. I have to combine these two. So I planned to write a Web API for Angular using Django. But I haven't used Django before. And I approached the deadline. I have created a Web API with PHP before and I am more experienced in PHP. I wonder what pros-cons would be if I developed this project as Angular->Php->Python? Should I learn Django quickly or do it with Php? A second question is, if I am going to do it with Php, what should I do for Python and Php communication? Should I do it by running Python scripts through Php? Or should I write the result returned from Python to the file and get it from the file in Php? Or something else?