Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to Pass model data to Javascript in django?
Im creating a site where I have to show different markers on the map like this i have saved the latitude,longitude,city_name and country_name in the model called City now what i want is to access this model data in javascript to add markers i have tried converting the python data to json but i couldn't cuz i have to idea how to do this. I have looked for the solutions but they all are very confusing as i have no idea of converting python data to json and serializers. {% extends "map/base.html"%} {% block content%} <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: 30.3753, lng: 69.3451}, zoom: 6 }); //declare marker call it 'i' var marker, i; //declare infowindow var infowindow = new google.maps.InfoWindow(); //add marker to each locations var locations = {{marker}} for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map, icon: locations[i][3] }); //click function to marker, pops up infowindow google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } } //initmap end google.maps.event.addDomListener(window, 'load', initialize); </script> {% endblock%} from django.shortcuts import render from .models import … -
Django FormView with dynamic forms
I created the FormView below that will dynamically return a form class based on what step in the process that the user is in. I'm having trouble with the get_form method. It returns the correct form class in a get request, but the post request isn't working. tournament_form_dict = { '1':TournamentCreationForm, '2':TournamentDateForm, '3':TournamentTimeForm, '4':TournamentLocationForm, '5':TournamentRestrictionForm, '6':TournamentSectionForm, '7':TournamentSectionRestrictionForm, '8':TournamentSectionRoundForm,} class CreateTournament(FormView): template_name = 'events/create_tournament_step.html' def __init__(self, *args, **kwargs): form_class = self.get_form() success_url = self.get_success_url() super(CreateTournament, self).__init__(*args, **kwargs) def get_form(self, **kwargs): if 'step' not in kwargs: step = '1' else: step = kwargs['step'] return tournament_form_dict[step] def get_success_url(self, **kwargs): if 'step' not in kwargs: step = 1 else: step = int(kwargs['step']) step += 1 if 'record_id' not in kwargs: record_id = 0 else: record_id = int(kwargs['record_id']) return 'events/tournaments/create/%d/%d/' % (record_id, step) The post request fails at the django\views\generic\edit.py at the get_form line, which I realize is because I've overwritten it in my FormView: def post(self, request, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ form = self.get_form() if form.is_valid(): … return self.form_valid(form) else: return self.form_invalid(form) However, when I change the name of my custom get_form method to say gen_form, … -
How to extract string from CharField in class level?
Because I want the Charfield string to save my Image at specific folder. I want to transfer or extract the string from CharField in Django I have tried the to_python method it doesn't work in class level. class Project(models.Model): filename = models.CharField(max_length=150) cata = models.CharField(max_length=150) image = models.ImageField(max_length=100, upload_to= 'ourwork/image/' + str(cata) + '/' + str(filename) , default='ourwork/default/default.png', verbose_name='图片') def __str__(self): return self.filename I want to see the image I uploaded at Django Admin console to show at 'ourwork/project/image' folder -
Is there a way to delete directory content when close or exit a Django project?
I want to delete all content of a directory "/media/" at the moment that user closes or finishes a Django project, this means by closing browser tab, or closing browser itself. I found this code to erase files ended in some extension, but I don't know how to uses it and in what file of my project. import os filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ] for f in filelist: os.remove(os.path.join(mydir, f)) -
showing error after deploying a django app
Fellas, I need help with heroku. After i have deployed the application, It says application has crashed. This is new to me and i can't spot it on the log file 2019-05-02T16:27:20.431826+00:00 heroku[web.1]: State changed from crashed to starting 2019-05-02T16:27:26.819416+00:00 heroku[web.1]: Starting process with command gunicorn basecodetech.wsgi --log-file - 2019-05-02T16:27:29.189527+00:00 heroku[web.1]: State changed from starting to crashed 2019-05-02T16:27:29.199192+00:00 heroku[web.1]: State changed from crashed to starting 2019-05-02T16:27:28.956745+00:00 app[web.1]: [2019-05-02 16:27:28 +0000] [4] [INFO] Starting gunicorn 19.6.0 2019-05-02T16:27:28.957547+00:00 app[web.1]: [2019-05-02 16:27:28 +0000] [4] [INFO] Listening at: http://0.0.0.0:12998 (4) 2019-05-02T16:27:28.957699+00:00 app[web.1]: [2019-05-02 16:27:28 +0000] [4] [INFO] Using worker: sync 2019-05-02T16:27:28.964747+00:00 app[web.1]: [2019-05-02 16:27:28 +0000] [10] [INFO] Booting worker with pid: 10 2019-05-02T16:27:28.972116+00:00 app[web.1]: [2019-05-02 16:27:28 +0000] [10] [ERROR] Exception in worker process 2019-05-02T16:27:28.972119+00:00 app[web.1]: Traceback (most recent call last): 2019-05-02T16:27:28.972133+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker 2019-05-02T16:27:28.972135+00:00 app[web.1]: worker.init_process() 2019-05-02T16:27:28.972137+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 126, in init_process 2019-05-02T16:27:28.972138+00:00 app[web.1]: self.load_wsgi() 2019-05-02T16:27:28.972140+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi 2019-05-02T16:27:28.972142+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2019-05-02T16:27:28.972148+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2019-05-02T16:27:28.972150+00:00 app[web.1]: self.callable = self.load() 2019-05-02T16:27:28.972152+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2019-05-02T16:27:28.972153+00:00 app[web.1]: return self.load_wsgiapp() 2019-05-02T16:27:28.972155+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2019-05-02T16:27:28.972156+00:00 app[web.1]: return util.import_app(self.app_uri) 2019-05-02T16:27:28.972158+00:00 app[web.1]: … -
Custom widget for DateTime picking doesn't appear in my django admin page
I'm currently making some tests in Django and i'm currently looking to override the native django's datetime picker. I try to use Tempus Dominus Bootstrap 4 following these instructions, some more ressources i found here and here. So i have a simple app with only this model: class DatesAndDates(models.Model): time_1 = models.TimeField() date_1 = models.DateField() date_time_1 = models.DateTimeField() a widget.py file at the same level as my models.py: from django.forms import DateTimeInput class BootstrapDateTimePickerInput(DateTimeInput): template_name = 'widgets/bootstrap_datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = 'datetimepicker_{name}'.format(name=name) if attrs is None: attrs = dict() attrs['data-target'] = '#{id}'.format(id=datetimepicker_id) attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context in the templates directory of the app i have widgets/bootstrap_datetimepicker.html: <div class="input-group date" id="{{ widget.datetimepicker_id }}" data-target-input="nearest"> {% include "django/forms/widgets/input.html" %} <div class="input-group-append" data-target="#{{ widget.datetimepicker_id }}" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <script> $(function () { $("#{{ widget.datetimepicker_id }}").datetimepicker({ format: 'DD/MM/YYYY HH:mm', }); }); </script> here is forms.py: from django.forms import ModelForm from.widgets import BootstrapDateTimePickerInput from .models import DatesAndDates class DatesAdminForm(ModelForm): class Meta: model = DatesAndDates fields = '__all__' widgets = { 'date_time_1': BootstrapDateTimePickerInput() } and finaly admin.py: @admin.register(DatesAndDates) class DatesAndDatesAdmin(admin.ModelAdmin): form = DatesAdminForm So when i go to the … -
How to add dynamic search filters with django-taggit
I want to add dynamic search filters to my django-taggit tags using checkboxes next to my search form, so that a user can enter a query, select one or multiple checkboxes and get the result of any product that contains the selected value(s). How can I achieve this? My Models.py looks like this: class Product(models.Model): title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.title and my search_form.html : <form class="search-form-container" action="/search/" method="get"> <div class="form-group"> <div class="icon-addon addon-lg"> <input type="text" placeholder="Search for good..." class="form-control" name="q" id="q" autocomplete="off"> <div id="selction-ajax"></div> </div> </div> <div class="col-md-3"> <!-- Tags section --> <div> <input class="facet" id="" type="checkbox" name="ptags" value="Solo" data-toggle="toggle" /> Solo </div> <div> <input class="btn btn-info btn-sm pull-right" type="submit" value="apply filter" /> </div> </div> </form> I'm currently using Django-Haystack and elasticsearch for my search functionalities so I use a custom Forms.py like this: from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() return sqs And not sure if this … -
Exclude instance when updating Recursive Foreign Key in Django
I have the following model and modelform for an Employee: models.py class Employee(models.Model): reports_to = models.ForeignKey( 'self', on_delete=models.SET_NULL, null=True, blank=True) forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee The idea is that the boss of an Employee is themselves an Employee. The problem is that, when I'm updating the instance, the respective form field created is a dropdown with all Employees, including the object I'm updating itself. Is there an easy way to remove the instance itself from the dropdown options so that no employee has him/herself as their own boss? PS.: I'm not looking for a solution that validates the form field after submitting a form, but rather removing the option from the form dropdown altogether. Thanks! -
How to return url specific url [duplicate]
This question already has an answer here: Django: Redirect to same page after POST method using class based views 4 answers I have an url with form, which looks like this: path('trip/<int:pk>/discussion/', MyListView.as_view(), name='trip-detail-discussion'), When I send a post by submit I would like to return to this same page, how can I obtain that? Kind regards -
How to render a form as dropdown menu
In Django I cant get a form to appear on the html page despite several attempted solutions. The goal is to creat a simple dropdown menu from a database content. I have tried several solutions mentionned in several posts but none of them worked models.py class Set(models.Model): cruise = models.IntegerField(verbose_name=_("cruise")) set = models.IntegerField(verbose_name=_("set")) def __str__(self): return self.name forms.py class SetChoiceField(forms.Form): set = forms.ModelChoiceField( queryset = Set.objects.values_list("set_number", flat=True).distinct(), empty_label = None ) views.py def index(request): query_results = Set.objects.all() set_list = SetChoiceField() context = { 'query_results': query_results, 'set_list': set_list, } return render(request,'base.html', context) base.html <h2>Set drop down menu</h2> <form method="post" novalidate> {% csrf_token %} <table> {{ set_list.as_table }} </table> <button type="submit">Save</button> </form> The expected result is to have a dropdown menu with the list of all the sets contained in the database (1-20) -
Returning 401 on Invalid Grant in django-oauth-toolkit
I am using Django and django-oauth-toolkit==1.2.0. Whenever I try to refresh a token twice, I get (as it should) an invalid_grant response. This is a 400 BAD REQUEST response. I would like this to be a 401 UNAUTHORIZED response. How can I change this in the toolkit? Invalid grant: The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client. -
Why doesn't all-auth provide adapters for OpenID based providers?
I have a django app on the server side providing REST APIs to the client. I want to enable a user to connect his Steam and Facebook accounts to his django account. For Facebook connect, it is straightforward, I used Django-Rest-Auth for this. from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter class FacebookConnect(SocialConnectView): adapter_class = FacebookOAuth2Adapter But there is no adapter for Steam or any other OpenID based provider. How can I create a REST API for client to be able to connect user's Steam account -
How can I get the logined in user details in django 2 models?
Sorry, I am still in a very beginning stage of Django. I have created a model for task scheduling. The model is registered it in admin.py. The Tasks will be assigned manually to some assignee from the main list of operators (users). Now I would like to track the change of the task form in the Django admin. I managed to track the time of change but I would like to get the login user first and last names and assign them to this method below instead of the "assignee.first_name & assignee.last_name" def str(self): return "%s last edit at %s by %s %s" % (self.title, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), self.assignee.first_name, self.assignee.last_name,) Here is my model: '''''''' class Operator(User): # full_name=User.get_full_name class Meta: ordering = ('first_name', ) proxy = True class Task( models.Model): # assignee = User.first_name + ' ' + User.last_name assignee = models.ForeignKey(User, on_delete=models.PROTECT, null=True, related_name="assigned_tasks", related_query_name="assigned_task", ) creation_datetime = models.DateTimeField(default=datetime.now().strftime('%Y-%m-%d %H:%M:%S')) title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() def __str__(self): return "%s last edit at %s by %s %s" % (self.title, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), self.assignee.first_name, self.assignee.last_name,) '''''''' -
how to prefetch parents of a child on mptt tree with django prefetch_related?
Say, I've got a product instance. Product instance linked to 4th level child category. If I only want to get root category and 4th level child category the query below is enough to fetch data with minimum database queries: Product.objects.filter(active=True).prefetch_related('category__root', 'category') If I have to reach parents of this product's category and using get_ancestors() method for this, nearly three times mode database query happening. If I write query like below instead using get_ancestors() method, database queries stays low. Product.objects.filter(active=True).prefetch_related( 'category__root', 'category', 'category__parent', 'category__parent__parent', 'category__parent__parent__parent', 'category__parent__parent__parent__parent') But this query is not effective when level of depth is unknown. Is there a way to prefetch parents dynamically in the query above? -
AJAX-driven forms in Bootstrap modals and Django Allauth
I've found a great looking package which integrates Django with AJAX-driven forms in Bootstrap 4 modals, but I'm struggling to get it to work with allauth. One example in the modal package documentation uses the default django signup form, which you can see at the live demo here: https://github.com/trco/django-bootstrap-modal-forms I've tried to copy the package's signup example by substituting out the default signup form with allauth's signup form, but with no luck. I thought the issue must be in part because the default signup form is a ModelForm, while allauth's isn't. So I had a go at turning the django allauth signup form into a ModelForm and then figuring out if there's a way to override the allauth signup form save method but, again, no luck. Here's some of my code plus the package's mixin and the allauth signup form save method - any ideas how allauth could be integrated with this package, if at all? forms.py from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin from allauth.account.forms import SignupForm class CustomSignupForm(PopRequestMixin, CreateUpdateAjaxMixin, SignupForm, forms.ModelForm): class Meta: model = CustomUser fields = ('username', 'email') views.py from bootstrap_modal_forms.generic import BSModalCreateView class signup(BSModalCreateView): form_class = CustomSignupForm template_name = 'users/signup2.html' success_message = 'Success: Sign up succeeded. You … -
images not being uploaded in AWS S3 with django
I want to upload image and load that uploaded images back to my webapp , previously loaded image in S3 bucket(which i uploaded manually) is rendering fine in the page but i am facing problem in uploading image in S3. below is my settings.py config INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', ] AWS_ACCESS_KEY_ID = "given id" AWS_SECRET_ACCESS_KEY = "given secret key" AWS_STORAGE_BUCKET_NAME = "young-minds-files" AWS_S3_REGION_NAME = "us-west-2" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" views.py class PostCreateView(LoginRequiredMixin,CreateView): model = Post fields = ["title","content","image1","image2","image3"] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models.py class Post(models.Model): title = models.CharField(max_length=100) category = models.CharField(max_length=100, default='Others') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image1 = models.ImageField(default='default_content.jpg', upload_to='content_pic') image2 = models.ImageField(default='default_content.jpg', upload_to='content_pic') image3 = models.ImageField(default='default_content.jpg', upload_to='content_pic') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) template {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} {% load static %} <section class="site-section"> <div class="container"> <div class="row mb-4"> <div class="col-md-6"> </div> </div> <div class="row blog-entries"> <div class="col-md-12 col-lg-8 main-content"> <form method="post" enctype="multipart/form-data"> <fieldset class="form-group"> <legend class="border-bottom mb-4"> Create Your Blog</legend> {% csrf_token %} {{ form|crispy }} </fieldset> <div class="row"> <div class="col-md-6 form-group"> <button type="submit" … -
logic of saving a notification object django websockets
I am having a hard time wrapping my head around how to save notifications when a message is received from another other_user in a 2-person Django Channels websockets chat application. Right now I have a function def create_notification that is called after def create_chat_message. def create_chat_message creates a new ChatMessage object each time a new message is sent in the Thread. It takes args thread=thread_obj, user=me, message=msg So obviously each individual message is saved with the user than sent it. def create_notification takes the last object by id in ChatMessage and creates a new Notification object. created_notification = Notification.objects.create(notification_user=user, notification_chat=last_chat) So essentially, the person who sends the message is associated with the notification_user field in the Notification model and saved along with the ChatMessage id. But if I send a message to Tom, my sent message should only be associated with a notification for Tom, not for myself. When I go to render out the notification objects, I get a list of all of them, including notifications for messages I've sent obviously. How can I render out all notifications for each thread I am in with various users? Am I saving these wrong? Should I configure the save notification function … -
Django tries to INSERT instead of UPDATE on save()
I have a model class Device(models.Model): dev_id = models.AutoField(db_column='dev_id', primary_key=True) ... A view locates an object: device = DeviceAdmin.objects.get(uuid=uuid) then it makes some changes (or maybe not) if (...): device.os_type = 'windows' ... then it tries to save any changes: device.save() Here's where Django attempts to insert anther row instead of updating, causing a DB error django.db.utils.IntegrityError: duplicate key value violates unique constraint There's a kind of similar question with solution: Once I set the primary_key field to an AutoField, the issue went away. However, my primary key is already an AutoField. So I stepped through django code with debugger, and fund this in file ...site-packages\django\models\base.py: # If possible, try an UPDATE. If that doesn't update anything, do an INSERT. if pk_set and not force_insert: base_qs = cls._base_manager.using(using) values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False))) for f in non_pks] forced_update = update_fields or force_update updated = self._do_update(base_qs, using, pk_val, values, update_fields, forced_update) if force_update and not updated: raise DatabaseError("Forced update did not affect any rows.") if update_fields and not updated: raise DatabaseError("Save with update_fields did not affect any rows.") if not updated: if meta.order_with_respect_to: # If this is a model with an order_with_respect_to # autopopulate the … -
A way to retrieve data in a survey form
Is there a way to retrieve a specific step in a survey wizard knowing that i'm using session to link steps in the survey and i don't store user id in the database.The idea is that a user that stopped in a step in the wizard will get an email sometime later with an URL that will redirect him to where he left on the survey...I don't know how he will get back where he left since the session is already expired .. i think i need to generate a session_key for every session created and add it in the URL but i don't know if that possible since in the documentation it says **The Django sessions framework is entirely, and solely, cookie-based. It does not fall back to putting session IDs in URLs as a last resort, as PHP does. ** -
how to format django models?
I'm having trouble understanding the formatting of django, my project is this, can anyone help me ?? I would like the Admin to have the function of the user inserting the images there. Thank you. HOME: {% for picture in photos %} <div><img> src="{{picture.pic}}"</img></div> {% endfor %} MODELS: class Photos(models.Model): pic = models.ImageField(upload_to='images') def __str__ (self): return self.pic VIEWS: ... picture = Photos.objects.all() return render(request, 'home.html', {'photos':picture}) -
Aggregation along with extra values
I'm trying to get the aggregate along with its id. I have a model called Index. class Index(Model): correlation = DecimalField() company = CharField() ------------------------------ | id | correlation | company | ------------------------------ | 1 | 0.99 | A | | 2 | 0.43 | A | | 3 | 0.67 | B | | 4 | 0.94 | B | | 5 | 0.23 | C | ------------------------------ I need my query to return [ { 'id': 1, 'correlation': 0.99, 'company': 'A' }, { 'id': 4, 'correlation': 0.94, 'company': 'B' }, { 'id': 5, 'correlation': 0.23, 'company': 'C' } ] Explanation: Since Company A has a Maximum correlation of 0.99 at id 1 it is returned. So Basically I need to retrieve id of max correlation for all the companies. I tried Index.objects.values('company').annotate(correlation_max = Max('correlation')). Index.objects.values('company', 'id').annotate(correlation_max = Max('correlation')). None of them are working. I couldn't able to get the id. I checked this. but I need id as well. -
What does the '--noinput' option do when collecting static files using django?
So I was having issues collecting my static files using the 'python manage.py collectstatic' command. it returned "CommandError: Collecting static files cancelled." I was searching and found the solution reading this post Django collecstatic with crontab It's now working and successfully collected my new static files. Could someone enlighten me on what the '--noinput' option is actually doing? -
Django development server shutdown on error
I am running a dev server on localhost to test a django app. About a week ago the dev server started exiting on error- which is not ideal. To give you an instance, imagine I want to create a new view, I make my template, then I add the following in urls: urlpatterns = [ ... path('forgotten-password', ForgottenPassword.as_view(), name='forgotten_password'), ] I haven't yet created the ForgottenPassword class based view yet, so rightly the server throws the error: File "/code/accounts/urls.py", line 19, in <module> path('forgotten-password', ForgottenPassword.as_view(), name='forgotten_password'), NameError: name 'ForgottenPassword' is not defined The server then quits however. This is not the desired behavior. I expect the server to remain in an error state until i fix the error (this happened up to about a week ago). What causes this to happen, and how can i ensure that the dev server stays live on an error to avoid having to relaunch the entire app? NB. It was around the same time that we upgraded from django 2.1 to 2.2, is this a desired behaviour in 2.2? NB. II I am aware of this question in which a very similar problem is outlined, but I am running the dev server on ubuntu, … -
Why my angular HTTP request can't GET on local Django server?
I made an Angular application able use an online api to get a json and do stuff. But, although the json is the same, if I try to change only the url of the json by setting a local url of a server written in django, angular would seem not to connect anymore ... My question is, why if with an online cloud server works, with a local one wouldn't? I tried making this server "on cloud" opening the router's port, also setting up a ddns, and using postman or a browser it seems to work, but when i try to connect with angular it still doesn't get the data... I am sure 100% that the server answer, with the right json data, because django prints on console that he received a HTTP GET request : http://i.imgur.com/TIQnIcR.png I remind you that the HTTP angular request worked with another api, but i will still show up some code : export class ProdottoService { private prodotti: Array<ProdottoModel>; constructor(private httpClient: HttpClient) { this.prodotti = new Array<ProdottoModel>(); var url:string = "https://gist.githubusercontent.com/saniyusuf/406b843afdfb9c6a86e25753fe2761f4/raw/523c324c7fcc36efab8224f9ebb7556c09b69a14/Film.JSON"; var local_url:string = "http://127.0.0.1:8000/films/?format=json"; httpClient.get(local_url) .subscribe((films : Array<Object> ) => { films.forEach((film => { this.prodotti.push(new ProdottoModel(film)); })); } ); } getProdotti(): Array<ProdottoModel> { … -
How do I implement autocomplete in my django chatbot?
I have implemented a chatbot based on this tutorial (https://github.com/vaisaghvt/django-bot-server-tutorial/tree/websockets). I would like to implement an autocomplete functionality, so that as I type, options are displayed. An example usage is the bot asking the user "What city do you live in?". I should be able to type "Be" and the bot suggests "Berlin". I understand that I should be able to use "autocomplete-light" for this but unsure about the implementation.