Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ajax update context
i want to update my template context "threedobject" my view file def threedProductCategory(request): id = request.GET['id'] todos = mProduct.objects.filter(category_id_id=id).values() return JsonResponse({"threedobject" : list(todos)}) my ajax function refresh(i){ $.ajax({ type:"GET", url: 'cpd/', data:{"id": i}, success: function (result) { threedobject = result; $.each(result.threedobject, function(item){ $(".carousel-indicators").append(item); }); } }); } i want to update my html context threedobject my html: {% for item in threedobject%} {% if foorloop.index == 0 %} <li data-target='#carousel-custom1' data-slide-to='0' class='active '> <img src='{{item.image_url.0}}' alt='' /> <p class="product-name">{{ item.name.0 }}</p> <p class="producer-name">{{ item.user_id.0 }}</p> <div class="rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star"></span> <span class="fa fa-star"></span> </div> </li> {% endif %} <li id="categoryItem" onclick=" document.getElementById('threedSelecteImg').src = '{{ item.image_url }}'; document.getElementById('threedSelecteName').innerHTML ='{{ item.name }}'; document.getElementById('threedSelecteProducer').innerHTML='{{ item.user_id.name }}'; document.getElementById('threedSelecteDescription').innerHTML='{{ item.description }}'; " data-target='#carousel-custom1' data-slide-to='1' > <img class="threedObjectsImg" src='{{item.image_url}}' alt='' /> <p id="threedObjectsName" class="product-name">{{ item.name }}</p> <p id="threedObjectsProducer" class="producer-name">{{ item.user_id.name }}</p> <div class="rating"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star"></span> <span class="fa fa-star"></span> </div> </li> {% endfor %} this ajax not change anythings, but this one change first image: function refresh(i){ $.ajax({ type:"GET", url: 'cpd/', data:{"id": i}, success: function (result) { threedobject = result; for (var … -
post request of the crud functionality not working in my django rest_framework app
I am trying to make a crud api using django rest_framework the get request seems to work fine for me but the post request is not working at all when I try to print the request.data it gives empty dictionary Please help me to resolve this issue views.py file from rest_framework import serializers from . models import freelancerJob from django.http import JsonResponse from .serializers import jobPostSerializer from django.views import View from django.views.decorators.csrf import csrf_exempt from rest_framework.status import HTTP_200_OK,HTTP_400_BAD_REQUEST from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.decorators import parser_classes from rest_framework.parsers import JSONParser from rest_framework import viewsets @csrf_exempt @api_view(['GET', 'POST','DELETE']) @parser_classes([JSONParser]) def jobPostView(request,format=None): if request.method == "POST": print("data",request.data) serializer = jobPostSerializer(data=request.data) print(serializer.initial_data) if serializer.is_valid(raise_exception=True): serializer.save() return JsonResponse({'data':serializer.data},status = HTTP_200_OK ) else: return Response({'status':'error','data':serializer.data},status = HTTP_400_BAD_REQUEST) if request.method == "GET": data = freelancerJob.objects.all().order_by('id') serializer = jobPostSerializer(data ,many = True) return Response({"status":'success','data':serializer.data},status = HTTP_200_OK) My serializers.py file from rest_framework import serializers from . models import freelancerJob class jobPostSerializer(serializers.HyperlinkedModelSerializer): def create(self,validated_data): return freelancerJob.object.create(**validated_data) class Meta: model = freelancerJob fields = ['title','description','skill','duration','budget','types'] my models.py file from operator import truediv from django.db import models class freelancerJob(models.Model): Job_duration = ( ('1','Less than 1 month'), ('3','1 to 3 months'), ('6','3 to 6 month'), ('12','More than 6 … -
How can I create objects in for loop in Django?
Only data coming to database is one record with one key and one value (and this is the last one from frontend). How can I send many records to my database in objects.create()? My HTML <div class="container"> <div class='element row' id='div_1'> <input class="col" type='text' placeholder='Enter key' id='key_1' name='key'> <input class="col-7" type='text' placeholder='Enter value' id='value_1' name="value">&nbsp; <span class='add col-2 btn btn-success'>+</span> </div> </div> Script so user can duplicate or remove div $(document).ready(function(){ $(".add").click(function(){ var total_element = $(".element").length; var lastid = $(".element:last").attr("id"); var split_id = lastid.split("_"); var nextindex = Number(split_id[1]) + 1; var max = 20; if(total_element < max ){ $(".element:last").after("<div class='element row' id='div_"+ nextindex +"'></div>"); $("#div_" + nextindex).append("<input class='col' name='key' type='text' placeholder='Enter key' id='key_"+ nextindex +"'>&nbsp;<input class='col-7' name='value' type='text' placeholder='Enter value' id='value_"+ nextindex +"'>&nbsp;<span id='remove_" + nextindex + "' class='remove col-2 btn btn-danger'>-</span>"); } }); $('.container').on('click','.remove',function(){ var id = this.id; var split_id = id.split("_"); var deleteindex = split_id[1]; $("#div_" + deleteindex).remove(); }); }); and Django views class NoteCreateView(views.View): def post(self, request, pk): data = request.POST note = Note.objects.create( topic = get_object_or_404(Topic, pk=pk), title = data.get('title'), summary = data.get('summary') ) Record.objects.create( key = data.get("key"), value = data.get("value"), note = note ) return redirect('platform:topic-list') -
Getting AttributeError: 'TestCalls' object has no attribute 'assertTemplateUsed' when trying to unit test views.py using unittest framework
Here is my code for unit test fruit view. But getting AttributeError test_views.py class TestViews(unittest.TestCase): def test_fruit_GET(self): client = Client() response = client.get(reverse('products:fruit')) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'products/fruit.html') views.py def fruit(request): product = Product.objects.filter(category="Fruit") n = Product.objects.filter(category="Fruit").count() params = {'product': product, 'n': n} return render(request, 'products/fruit.html', params) -
Django admin view_on_site redirect gives me extra https:// on production
view_on_site works perfect on localhost, but when I tried in production return this: https://https//expample.com//accounts/details/9/ What can i do to fix it? -
How to combine a django frontend + django REST Framework?
I already developed a whole django website (front-end + back-end) and now I would like to "decouple" the back and the front since I want to be able to link an android app to the database. Am I supposed to create two different projects: one for the REST API and one for the front? Or can I just put every thing together? In both cases, how to render the templates in the front-end views? Thank you in advance for your answers! Paul -
Secret Key in Django when upload to Github
I been following a Django course on Youtube and coding an local app. But when I commit to my repo on Github, i get a mail from GitGuardian says that Django Secret key exposed. I don't know anything about this, does this mean my account at risk or something? The app I made just by following step from the course, it just an local app run on my computer. Is there any harm to anything of mine(code, computer,...)? I am very worried now Here is the messeage i get in my mail from gitguardian -
Django not loading content into template
i have a problem with Django not loading content of the html file. I believe i did everything according to tutorial but it doesn't seem to work. When i open server and go to localhost:8000/reviews/ it shows only home.html file This is my template file ("home.html", it is in the same folder as second html file) <!Doctype html> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <div> <div class="review" id="review4"> <img style="grid-area: person;" class="img-responsive img-fluid" id="person" src="{% static 'home/images/pfp.png' %}"></img> <p style="grid-area: name;" class="h3" id="name">Daniel M.</p> <img style="grid-area: star1;" class="img-responsive img-fluid star" id="star1" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> <img style="grid-area: star2;" class="img-responsive img-fluid star" id="star2" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> <img style="grid-area: star3;" class="img-responsive img-fluid star" id="star3" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> <img style="grid-area: star4;" class="img-responsive img-fluid star" id="star4" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> <img style="grid-area: star5;" class="img-responsive img-fluid star" id="star5" src="{% static 'home/images/iconmonstr-star-3-240 5.png' %}"></img> </div> {% block content %} {% endblock content %} </div> And this is html file that i want to put into home.html ("reviews.html") {% extends 'home/home.html' %} {% block content %} <h1>Hello i am working</h1> <form id="reviews-form" method="POST"> <input type="text" name="name" id="form-name" placeholder="Tvoje meno" required> <textarea placeholder="Ako sa ti u … -
Python Django: "Post.author" must be a "User" instance error
I am trying to assign username to author field in Post model , Django spews out the following error: "Post.author" must be a "User" instance. model: class Post(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='',null=True,blank=True) image_url = models.CharField(max_length=200,default=None,null=True,blank=True) date = models.DateTimeField(default=timezone.now) content = models.TextField() author = models.ForeignKey(User, null=False, blank=False,on_delete=models.CASCADE) categories = models.ManyToManyField(Category) published = models.BooleanField() def __str__(self): return self.title view: @login_required def new_post(request): # Add a new post if request.method != 'POST': # No data submitted, create a blank form form = PostForm() else: # Post data submitted, process data form = PostForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user.username new_post.save() return redirect('elogs:posts') #Display a blank or invalid form context = {'form':form} return render(request,'elogs/new_post.html',context) form: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','content','image','image_url','published'] widgets = { 'title': forms.Textarea(attrs={'placeholder': 'Title..'}), 'content': forms.Textarea(attrs={'placeholder': 'What is on your mind?'}), 'categories': forms.TextInput() }enter code here -
FieldError at /answer/ Cannot resolve keyword 'i' into field. Choices are: add_time, answer, detail, id,
believe it or not I've been here for 4 hours trying to get this to work, so yes, I've been trying to make a question and answer site, currently trying to make an answer form so I can send in answers to the question that I am currently viewing, trying to get the id of the question so I can attach the answer into that, but I'm getting this error, I'm sure I wrote 'id' but it thinks I wrote 'i'... What? Anyway here is the traceback, please tell me what I am doing wrong, thanks. Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/answer/ Django Version: 4.0.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.humanize', 'forum', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'crispy_forms', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'vote'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/titsnium/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/titsnium/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/edit.py", line 184, in post return super().post(request, *args, **kwargs) File "/home/titsnium/.local/lib/python3.8/site-packages/django/views/generic/edit.py", line 153, in post return self.form_valid(form) File "/home/titsnium/Documents/eduzec/forum/views.py", line 78, in … -
do we need a package like spatie for Permissions and Roles with Django
i am new with Django, and I have been using Spatie with Laravel for a long time, my question is does I need to use something like it with Django? or even do I need to do anything about multi roles and permission with Django since the admin panel looks perfect and completed already..... Thanks -
Why does order_by in Django is ignoring spaces while sorting with name alphabetically?
Image of the issue Suppliers.objects.all().order_by('name') -
Django Paginate_by not displaying proper pagination
Hello i have a page using paginate_by 10, and instead i'm getting only 9 elements per page, even tho in the element inspector i see 10 grid spaces my for cicle is just being able to fill 9 out of 10 then it goes into the next page. Views.py class VideoListView(generic.ListView): model = Video template_name = 'index.html' context_object_name = 'video_list' paginate_by = 10 def get_queryset(self): return Video.objects.order_by('-date') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['category_list'] = Category.objects.all() return context -
In Django how to delete, retrieve, and update a table when calling an external API
I was wondering what the correct way is to delete one table in the database and update it with new information from an external API every time that is called. Basically, whenever the API would be called, the information saved in the table should be substituted by new one. my views.py from rest_framework import generics from .serializers import TickerSerializer from ticker.models import Ticker import requests import logging logger = logging.getLogger(__name__) class TickerList(generics.ListAPIView): serializer_class = TickerSerializer queryset = Ticker.objects.all() class TickerRetrieve(generics.RetrieveUpdateDestroyAPIView): serializer_class = TickerSerializer queryset = Ticker.objects.all() lookup_field = 'id' def get_object(request): url = 'https://api.kraken.com/0/public/Ticker?pair=1INCHEUR,1INCHUSD' response = requests.get(url) data = response.json() for key in data['result']: if isinstance(data['result'][key], int): continue crypto_data =data['result'][key] ticker_data = Ticker(crypto = (key), crypto = (key), a_0 = (crypto_data.get('a')[0]), ) ticker_data.save() my models.py from django.db import models class Ticker(models.Model): id = models.AutoField(primary_key=True) # auto increment field crypto = models.CharField(blank=True, null=True, max_length=25) a_0 = models.FloatField(null=True, blank=True, default=None) my serializers.py from rest_framework import serializers from ticker.models import Ticker class TickerSerializer(serializers.ModelSerializer): class Meta: model = Ticker fields = ( 'id', 'crypto', 'a_0', ) my urls.py from .views import TickerList, TickerRetrieve from django.urls import path app_name = 'ticker' urlpatterns = [ path('', TickerList().as_view(), name='ticker'), path('tickerretrieve/', TickerRetrieve().as_view(), name='tickerretrieve'), ] Every time that i … -
Django IntegrityError (1048, "Column 'newuser_id' cannot be null")
I'm new to Django. Basically, I'm trying to create a password confirmation field, but when I try to submit the form I get this error: (1048, "Column 'newuser_id' cannot be null") models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from datetime import datetime from django.core.validators import MinLengthValidator from .CHOICES import * from django.utils.translation import gettext_lazy as _ from django.db import models # Create your models here. country_choice = COUNTRY_CHOICE class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, first_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, first_name, password, **other_fields) def create_user(self, email, username, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=50, validators=[MinLengthValidator(8)], unique=True) first_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=False) middle_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=False) # day = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(31)], blank=False) # month = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(12)], blank=False) # year = models.IntegerField(validators=[MinValueValidator(1942), MaxValueValidator(2017)], blank=False) # gender model GENDER_CHOICES = ( ('M', 'Male'), … -
How to update password of Auth user in django rest framework
I'm new to django rest framework. I'm implementing a simple login, signup and forgot password functionality using reactJs and django. All the functionalities are working fine but the problem I'm facing is that, on signup, the passwords in the database encrypted and then saved in the database but on updating password, the new password saved exactly same as user typed it. I want it also be encrypted in the database just like it encrypted in signup. My serializer.py file from dataclasses import fields from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields='__all__' # fields = ('username','first_name', 'last_name', 'email') class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token','first_name', 'last_name','email', 'username', 'password') My views.py file from asyncio.windows_events import NULL from django.http import Http404, HttpResponseRedirect from django.contrib.auth.models import User from rest_framework import viewsets, permissions, status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from .serializers … -
Django - template doesnt render HTML, only see source code
I try to go with https://www.youtube.com/watch?v=PtQiiknWUcI&t=3500s however I have stucked after 56:30 minutes step, when I have created new home.html template file. I have copied and pasted old home.html code into new one however after server refresh I can see only source code. Can you please advice?Thanks -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I do not understand
from django.db import models # Create your models here. class Topic(models.Model): text = models.CharField(max_length=200) data_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text ` I do not understand, what is mean django.core.exceptions.AppRegistryNotReady? ` -
how do I get the value or pk of a model in django?
hey I'm a beginner in django and trying to make a question and answer project using class based views, im trying to make an answer form to write an answer for the question, the posting and all is already good. but I don't know how to make it so that it posts the answer object to the correct question object in class based views, how do I do this? Please explain in a very simple way for a beginner, thank you! -
Django DatField returns null value every time I register information
I have a model that registers a project information which have start date and end date but when I submit those information, the value of start date and end date is null their value never saved to the database. Here is my model.py class Project(models.Model): project_name = models.CharField(max_length=255, blank=False) created_by = models.ForeignKey( Employee, related_name='employee', on_delete=models.CASCADE) status = models.CharField( max_length=50, choices=PROJECT_STATUS_CHOICES, default=COMING_STATUS, null=True, blank=True ) start_date = models.DateField( null=False) end_date = models.DateField( null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.project_name Here is the list of project data { "id": 1, "created_by": "Teshome", "project_name": "Teshome", "status": "Coming", "start_date": null, "end_date": null, "created_at": "2022-04-15T12:16:31.045887Z", "updated_at": "2022-04-15T12:16:31.045887Z" }, { "id": 2, "created_by": "Teshome", "project_name": "Babi", "status": "Ended", "start_date": null, "end_date": null, "created_at": "2022-04-15T12:30:03.332208Z", "updated_at": "2022-04-15T12:30:03.332208Z" }, I did not use any frontend framework to register project information I just did it from Django Admin. How can I solve this Isuue? Thanks -
Mocking django recaptchafield
When testing a view, how do I bypass the recaptcha field inside my user create form? This test fails after adding the captcha field from django-recaptcha, with the validation error "Error verifying reCAPTCHA, please try again." This (incorrect) approach tells me "app.views" is not a package, but I can do "from app.views import *" without error @mock.patch("vividqr.myapp.views.CustomUserCreationForm.fields.ReCaptchaField.validate") def test_outside_signup_ok(self): client = Client(HTTP_HOST='vividqr.local') client.post(reverse('myapp:outside'), data={'action': 'signup', 'signup_form-first_name': 'FirstName', 'signup_form-last_name': 'LastName', 'signup_form-captcha': 'dummystring', 'signup_form-email': 'test24@example.com', 'signup_form-password1': 'DifferentPassword420', 'signup_form-password2': 'DifferentPassword420'}, follow=True) self.assertEqual(User.objects.filter(email='test24@example.com').count(), 1) -
How to get value of defaultdic in JS (Django framework)?
I want to use chartjs to display a chart on the page (Django framework). views.py chart_data = defaultdict(<class 'int'>, {'3': 2, '2': 2, '8': 2, '5': 2, '7': 1}) context["chart_data"] = chart_data home.html <script type="text/javascript"> var my_chart = "{{ chart_data }}"; </script> my_chart.js const data = { labels: labels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: Object.values(my_chart), }] }; But it didn't work. When I used console.log(Object.values(my_chart)) to check, I found that what Object.values(my_chart) returns was ['d', 'e', 'f', 'a', 'u', 'l', 't', 'd', 'i', 'c', 't', '(', '&', 'l', 't', ';', 'c', 'l', 'a', 's', 's', ' ', '&', '#', 'x', '2', '7', ';', 'i', 'n', 't', '&', '#', 'x', '2', '7', ';', '&', 'g', 't', ';', ',', ' ', '{', '&', '#', 'x', '2', '7', ';', '3', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', 'x', '2', '7', ';', '2', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', 'x', '2', '7', ';', '8', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', …], it just disassembled each letter and symbol … -
How to sort a list(queryset) containing a manytomany field
Python: 3.9.10 Django: 4.0.3 I am using Django Paginator. To sort the data on each page, and only the data on that page, I am converting my queryset to a list and then sorting the list by its key using attrgetter(). My model contains two ManyToManyFields and so I cannot sort it using the standard sorted() method as I receive the error message: TypeError: '<' not supported between instances of 'ManyRelatedManager' and 'ManyRelatedManager' I think I understand why this is happening - sorted() cannot compare two lists (manytomanyfields) against each other and determine which is greater than or less than - so therefore the list(queryset) cannot be sorted in this way. I imagine I probably have to iterate through the list(queryset), get the first value of the manytomanyfield and then somehow sort everything by that. I am not what the best way is to go about doing this. models.py class DataExchange(models.Model): name = models.CharField(unique=True, max_length=15, null=True) def __str__(self): return self.name class DataSource(models.Model): name = models.CharField(unique=True, max_length=10, null=True) def __str__(self): return self.name class Provider(models.Model): name = models.CharField(unique=True, max_length=15, null=True) exchange = models.ManyToManyField(DataExchange, related_name="providers_exchange") source = models.ManyToManyField(DataSource, related_name='providers_source') score = models.IntegerField(null=True) def __str__(self): return self.name Paginator helper function: def paginator_helper(request, paginator): page … -
How to turn a LightGBM model into a web-app?
everyone, I'm new to Machine learning. Recently, I've built a LightGBM model with 30 features. The model works great. Then, my boss wants me to build a web app for this model which allows the user to input the data and return the prediction to the users. He wants a web app like this project: http://wwwnew2.hklii.hk/predictor. I don't know where to start. In my understanding, I might need an input form then pass the values to the model and then return the prediction to the front-end. However, I totally had no idea how to get started. Here are my questions: How can I pass the value to the trained model and return the result? Should I build the front-end with Django? Is there any python library that allows me to build such a web app easily? Should I host the web app on a VM? Thank you very much. -
Filtering user post and shared post on his account wall
How best can i filter a user's post and shared post on user's account wall! with what i have done, when i visit let say my account wall i don't see my shared post but but rather when i visit the account of the original post that was shared i see that my shared post on his account with the original post and my shared post with is name! why am i getting this effect as i want to be able to have all the shared post on my wall and not the other way round? def account_view(request,*args, **kwargs): context = {} user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) try: post_list = Post.objects.filter(username=account) except Post.DoesNotExist: post_list = Post.object.prefetch_related('postimage_set').order_by("date_posted") posts = post_list.all() try: friend_list = FriendList.objects.get(user=account) except FriendList.DoesNotExist: friend_list = FriendList(user=account) friend_list.save() friends = friend_list.friends.all()