Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python3 bot.py django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I have a telegram bot witch depends on a Django app, I'm trying to deploy it on Heroku but I get this error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when it runs python3 main/bot.py in Heroku here is my Procfile: web: gunicorn telega.wsgi worker: python main/bot.py main/bot.py: import telebot import traceback from decimal import Decimal, ROUND_FLOOR import requests import json from django.conf import settings from preferences import preferences from main.markups import * from main.tools import * config = preferences.Config TOKEN = config.bot_token from main.models import * from telebot.types import LabeledPrice # # # if settings.DEBUG: TOKEN = 'mybottoken' # # # bot = telebot.TeleBot(TOKEN) admins = config.admin_list.split('\n') admin_list = list(map(int, admins)) @bot.message_handler(commands=['start']) def start(message): user = get_user(message) lang = preferences.Language clear_user(user) if user.user_id in admin_list: bot.send_message(user.user_id, text=clear_text(lang.start_greetings_message), reply_markup=main_admin_markup(), parse_mode='html') else: bot.send_message(user.user_id, text=clear_text(lang.start_greetings_message), reply_markup=main_menu_markup(), parse_mode='html') @bot.message_handler(func=lambda message: message.text == preferences.Language.porfolio_button) def porfolio_button(message): .... ... and my settings.py: """ Django settings for telega project. Generated by 'django-admin startproject' using Django 2.2.7. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import django_heroku import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - … -
Can't install virtualenvwrapper when setting up vagrant box
I'm trying to follow the video series from the London App Developer series called 'Build a Backend REST API with Python & Django' After setting up the vagrant file, when running the vagrant ssh command I get an error saying: '-bash: /usr/local/bin/virtualenvwrapper.sh: No such file or directory'. My vagrant file has the following code: sudo pip install virtualenvwrapper --user if ! grep -q VIRTUALENV_ALREADY_ADDED /home/vagrant/.bashrc; then echo "# VIRTUALENV_ALREADY_ADDED" >> /home/vagrant/.bashrc echo "WORKON_HOME=~/.virtualenvs" >> /home/vagrant/.bashrc echo "PROJECT_HOME=/vagrant" >> /home/vagrant/.bashrc echo "source /usr/local/bin/virtualenvwrapper.sh" >> /home/vagrant/.bashrc fi SHELL end I found this post but couldn't make it work : "mkvirtualenv command not found" within vagrantbox Thank you very much! -
Problen with generating token in login
Hello I would like help I have been trying to learn how to create token with django rest framework and pyjwt But whenever I do it when I am going to use login it gives me an error I would like to know if it is due to the code since I have seen several videos and I have the same code or it is due to something on my computer and if so, how could I solve it, the error is the next Internal Server Error: /api/login Traceback (most recent call last): File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\Users\ferna\Documents\Cursos\Youtube\auth\users\views.py", line 37, in post token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8') AttributeError: 'str' object has no attribute 'decode' [07/May/2021 21:18:23] ←[35;1m"POST /api/login HTTP/1.1" 500 96900←[0m the code for view it's from rest_framework.views import … -
How would I go about rendering Developer's name in DevelopmentTeam for each bot?
I'm using the 'through' argument to connect Bot to Developer through Development team, in my html page (home.html), how would I render Developer's name in DevelopmentTeam? Also, I've tried to simply render the DevelopmentTeam name and was unsuccessful as well. I would greatly appreciate if someone could guide me in the right direction as I've read documentation everywhere and the issue persists. thanks all in advance! home.html {% for bot in bot_list_slice|slice:":5" %} <div class="col"> <a href="{% url 'bot_detail' bot.slug %}" class="text-decoration-none"> <div class="row-inside-content"> <div class="container"> <img src="#"> <h6 class="text-dark">{{ bot.bot_name|title }}</h6> </div> <div class="container"> <span class="badge bg-light text-dark">Software</span> </div> <div class="container"> <p>{{ bot.team_members.name **<here>** }}</p> </div> </div> </a> </div> {% endfor %} Models.py class Developer(models.Model): name = models.CharField(max_length=20, blank=False) profile = models.ImageField(blank=True,null=True) job_choices = [ ('Backend Developer', 'Backend Developer'), ('Frontend Developer', 'Frontend Developer'), ('Lead Developer', 'Lead Developer'), ('Team Developer', 'Team Developer'), ('Designer', 'Designer'), ] job = models.CharField(choices=job_choices, max_length=20) team = models.ManyToManyField('DevelopmentTeam', blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Developer, self).save(*args, **kwargs) def __str__(self): return '{}'.format(self.name) class DevelopmentTeam (models.Model): team_name = models.CharField(max_length=20, null=True) members = models.ForeignKey(Developer,on_delete=models.CASCADE, null=True) bot = models.ForeignKey("Bot", on_delete=models.CASCADE, null=True) def __str__(self): return '{} '.format(self.team_name, self.members, self.bot) class Bot(models.Model): bot_name = models.CharField(max_length=20, blank=False, null=True) company_logo = models.ImageField(blank=True, … -
CSFR Exempt inside view?
I want to call a csfr protected class view inside other view in django, but this is giving me a CSFR not set error. I tried to disable it with the csfr_exempt function (Reference), but it did not work at all: from django.contrib.auth import views as django_auth_views from django.views.decorators.csrf import csrf_exempt def my_view(request): response = csrf_exempt( django_auth_views.PasswordResetView.as_view() )(request) It keeps giving me the same error. Is there anyway I can do it? Thanks. -
Django Queries with many2many & 'through'
I'm quite new to Django and I have some troubles to understand how to fetch data in my database. I think however that my problem is not so complex : I have music works and instruments. To be performed, each work need various instruments in a certain quantity. Here are my models : class Instrument(models.Model): name = models.CharField() class MusicWork(models.Model): name = models.CharField() performers = models.ManyToManyField(Instrument, through='MusicWorkInstrument') class MusicWorkInstrument(models.Model): work = models.ForeignKey(MusicWork, on_delete=models.CASCADE) instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE) quantity = models.IntegerField() Now that I have my database structure, I want to perform some queries. For example, I play the piano and I want to play with my friend who is a violonist. How can I ask for all works composed exactly 1 piano and 1 violin? Let's say we didn't find something interesting, so let's try to find some arrangements: How can I get all works with 1 piano and 1 other instrument ? We changed our mind, and now we would like to find a new fellow musician: We need to search for all works with 1 piano, 1 violin, and any other instrument except the bassoon (sorry but it doesn't fit with the violin :( ) I've been trying … -
Pros and Cons of using function iter() for fetching
I would like to know the pros and cons of using function iter() for fetching QuerySet in Django. In order to optimize the performance of fetching Data with Django ORM, I found that using iter() is one of the approaches. I would be happy if you can tell me the pros and cons of using iter(). Thanks. -
How to integrate Gatsby on Django?
Most of my experience is using Django but I recently built a site using Gatsby and want to have it as the section of my site. I am aware that React Gatsby is greater for static sites and has lots of benefits for SEO. So I purchased a Gatsby template and modified it to suit my needs. However, I don't have much experience in Node or other JavaScript backend frameworks. The site displays all the basic information from the company and has a blog that will eventually require being rendered based on an API. However, I plan to have several micro-sites on it which would require heavy use of an API and dynamic routing. Most URL could run from the gatsby site such as /home /about-us etc But I would like to have a section of the site /dynamic-url-tracking be a site of its own quality user authentication and dynamic routing with actions Meaning that when a user loaded /dynamic-url-tracking// (/dynamic-url-tracking/01/123) it would call a view that would modify a field inside of a model (url-track) and then redirect the user to an external url. This would allow me to track which url has been opened and when. How can … -
Deploying django channels on heroku
I have created a standard django application with startproject, startapp, etc. and I want to deploy it on heroku. When I was using gunicorn I solved the directory issue like so: web: gunicorn --pythonpath enigma enigma.wsgi with the --pythonpath option. But now I am using django channels and so it is daphne. Is there an equivalent? I have tried everything but for the life of me I can't get the project to start. I always get issues with the settings file, apps not loaded or another assortment of cwd-related issues. -
Import CSV with several foreign keys
Trying to import csv data into my django's application models I suffer...I tried with a script and via django-import-export. I'll detail only the later to avoid running all over the space. My Painting model has few foreign-keys which I cannot map to my model as I also import them in the CSV file, i.e. they aren't yet created. How can I overcome it? That is how I can map the Painting instance to a the foreign-key name rather than it's not yet created ID? To test I then created manually some entries for eht foreign keys and added their ID integers into my CSV. I notice that I can import only the first foreign hey values. the others don't appear, exemple the painter Id is displayed in the preview and the final import, but the category isn't. Here's my second question: How can I import several foreign keys from the same CSV file? here's my code: class Painter(models.Model): """Model representing a painter.""" first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('died', null=True, blank=True) def __str__(self): """String for representing the Model object.""" return f'{self.last_name}, {self.first_name}' class Painting(models.Model): '''Model representing a painting''' title = models.CharField(max_length=200) painter = models.ForeignKey('Painter', … -
how can i send a list of numbers from views.py to a chartjs file im using for the front?
what excatly i am trying to do is to send csv data from views.py in my django app to a chart.js file i am using in the front this is chartjs file : // comboBarLineChart var ctx_combo_bar = document.getElementById("comboBarLineChart").getContext('2d'); var comboBarLineChart = new Chart(ctx_combo_bar, { type: 'bar', data: { labels: ["a", "b", "c", "d", "e", "f", "j"], datasets: [{ type: 'bar', label: 'Followers', backgroundColor: '#FF6B8A', data: {{ lf }}, borderColor: 'white', borderWidth: 0 }, { type: 'bar', label: 'Likes', backgroundColor: '#059BFF', data: {{ ll }}, }], borderWidth: 1 }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); im trying to get the lists of number lf and ll but in my console its showing an error i couldn't figure it out : enter image description here and here is my views.py function: context={} file_directory = 'media/fl.csv' readfile(file_directory) dashboard = [] dashboard1 = [] for x in data['likes']: dashboard.append(x) my_dashboard = dict(Counter(dashboard)) print(my_dashboard) values = my_dashboard.keys() print(values) listlikes = [] for x in values: listlikes.append(x) print(listlikes) for x in data['followers']: dashboard1.append(x) my_dashboard1 = dict(Counter(dashboard1)) # {'A121': 282, 'A122': 232, 'A124': 154, 'A123': 332} values1 = my_dashboard1.keys() print(values1) listfollowers = [] for x in values1: listfollowers.append(x) … -
How to display "0" when using 'pluralize' in Django templates?
How do I make pluralize to display 0? In the database are 2 book listings ('books'), 6 physical copies ('book_instances'), and 0 available for borrowing ('bookinstance_available'). In the code below, the first two display correctly: 2 and 6. The third line should display 0, but nothing appears. Is there anything I need to do for it to show 0 without writing special code (which seems to be the case when I searched)? There are {{ num_books }} book{{ num_books|pluralize }} in the library catalog. <br> There are {{num_bookinstance}} book{{num_bookinstance|pluralize}} in the collection. <br> There are {{num_bookinstance_available}} book{{num_bookinstance_available|pluralize}} available for borrowing. By the way, I'm working through the Mozilla Django tutorial. -
How to fix Python circular import error (top level)?
I read about solution for the error (write import instead of from ...) but it doesn't work I think because I have a complex folder structure. quiz.models import apps.courses.models as courses_models courses_models.Lesson # some actions with that class class Quiz: pass courses.models import apps.quiz.models as quiz_models quiz_models.Quiz # some actions with that class class Lesson: pass Error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/code/apps/carts/models.py", line 5, in <module> from ..courses.models import Course File "/code/apps/courses/models.py", line 12, in <module> import apps.quiz.models as quiz_models File "/code/apps/quiz/models.py", line 12, in <module> class Quiz(TimestampedModel): File "/code/apps/quiz/models.py", line 15, in Quiz courses_models.Lesson, … -
How do i get objects by ForeignKey in Django 3.2
I am building menu items for Irvine class and want to categorize them by Category models.py class Irvine(models.Model): objects = None name = models.CharField(max_length=50, verbose_name='Irvine Item') description = models.TextField(null=True, blank=True) size = models.FloatField(null=True, blank=True) price = models.FloatField(null=True, blank=True) published = models.DateTimeField(auto_now_add=True, db_index=True) category = models.ForeignKey('Category', null=True, on_delete=models.PROTECT, verbose_name='Category') def __str__(self): return self.name class Meta: verbose_name_plural = 'Irvine' verbose_name = 'Irvine Item' ordering = ['-published'] class Category(models.Model): objects = None name = models.CharField(max_length=30, db_index=True, verbose_name="Category") published = models.DateTimeField(auto_now_add=True, db_index=True) def __str__(self): return self.name class Meta: verbose_name_plural = '* Categories' verbose_name = 'Category' ordering = ['name'] view.py def irvine(request): irvine = Irvine.objects.all() context = {'irvine': irvine} return render(request, 'cafe/irvine.html', context) def by_category(request, category_id): santaanna = SantaAnna.objects.filter(category=category_id) costamesa = CostaMesa.objects.filter(category=category_id) irvine = Irvine.objects.filter(category=category_id) categories = Category.objects.all() current_category = Category.objects.get(pk=category_id) context = {'santaanna': santaanna, 'categories': categories, 'costamesa': costamesa, 'irvine': irvine, 'current_category': current_category} return render(request, 'cafe/by_category.html', context) urls.py urlpatterns = [ path('add/', ItemsCreateView.as_view(), name='add'), path('<int:category_id>/', by_category, name='by_category'), path('', index, name='index'), path('irvine', irvine), with {% for i in irvine %} {} <tr class="danger"> <th scope="row" width="20%">{{ i.name }}</th> <td width="60%">{{ i.description }}</td> <td width="10%">{{ i.size }}</td> <td width="10%">{{ i.price }}</td> </tr> {% endfor %} I can grab all items from class Irvine, but how do i … -
Django-tenants with VueJS how to login using auth token ( end point )
I'm working on a small project using Django Rest Framework / Django-tenants i would like to know what is the end point for the login to get the token, it seems like the django-tenants middleware block my request or some thing like that this is my code : My installed apps : 'django_tenants', 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth', 'rest_auth.registration', My Urls : path('api-auth/', include('rest_framework.urls')), path('api/rest-auth/', include('rest_auth.urls')), When i send a post request to : http://localhost:5555/api-auth/login/ I get an error message : 404 Not found No tenant for hostname "localhost" -
Authentication between React and Django, when both are on different servers
I am developing a web app, In which I'm gonna use React as Front-end and Django as the back-end. But the thing is that my front-end part is on a different server and the Back-end part is on a different server. and wanna communicate between them through the API. I want to know how I can Authenticate users and get authenticated Users from the backend to the front-end. I was thinking about the mentioned options -> should I Use Token authentication -> should I use session authentication -> should I use JWT authentication I am confused because there is also a problem, where I will store the auth token in React.? also a problem,Does session authentication really works between 2 different server? -
Does Elasticbeanstalk application ever goes to sleep?
I'm developing iOS app with backend made by Django. The Django app is deployed using Elasticbeanstalk. It often happens that when I hit api from the iOS app it just does not respond but soon after that apis start responding and return responses. It only happens when I hit the apis after a while like an hour or hours after last I hit the apis. I wonder if my django app on AWS went to sleep. Does Elasticbeanstalk app ever goes to sleep? -
Django having a disabled form as the default selected one
I have the following code currently. In my forms.py from django import forms from django.forms.widgets import Select class SelectWithDisabled(Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): disabled = False if isinstance(label, dict): label, disabled = label['label'], label['disabled'] option_dict = super(SelectWithDisabled, self).create_option(name, value, label, selected, index, subindex=subindex, attrs=attrs) if disabled: option_dict['attrs']['disabled'] = 'disabled' return option_dict GAME_PHASES = [ ('default', {'label': 'Choose an option', 'disabled': True}), ('opening', 'Opening'), ('midgame', 'Midgame'), ('endgame', 'Endgame'), ] class SettingsForm(forms.Form): game_phases = forms.ChoiceField(label='Phase of the Game:', choices=GAME_PHASES, required=True, widget=SelectWithDisabled) To clarify in pure HTML code I would want my code to do the following: <label for="phase">Phase of the Game:</label><br> <select name="phase" id="phase" required> <option selected disabled>Choose an option</option> <option value="opening">Opening</option> <option value="midgame">Midgame</option> <option value="endgame">Endgame</option> </select> However, the Choose an option line does not yet work as intended. Basically, I want my Django forms code to do the exact same thing as the pure HTML code. However, in Django the tags disabled / selected seem to conflict. While in HTML when I set a disabled field as selected it begins on that option and simply never lets the user return to the disabled option after switching. Is there a way to get this done? Default the … -
How to set a default queryset for DateFromToRangeFilter in django-filter?
I have a filter on which I've set a date range filter. class UtenteActivityFilter(django_filters.FilterSet): date = django_filters.DateFromToRangeFilter(widget=RangeWidget(attrs={"class": "form-control"})) class Meta: model = Activity fields = ['date'] I am using this filter to populate a table. class UtenteDetail(LoginRequiredMixin, DetailView): model = Utente template_name = 'users/utente_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) f = UtenteActivityFilter(self.request.GET, queryset=Activity.objects.filter(author=self.object)) context['filter'] = f return context Now my table is populated by all the data from the queryset when I load the page without any date set in the filter. How do I set the initial state of the filter to a defined value (or queryset)? I wish my table to show just activities from "today" when the page is ofirst opened, but to still be able to filter among all the models. I already defined a qs of activities for "today": # context['today_activities'] = Activity.objects.filter(created__gte=timezone.now().replace(hour=0,minute=0,second=0)) but setting it as a queryset restrict the filtering to that only -
Why django does not validate email in CustomUser model?
I had the following custom user model: class CustomUser(AbstractUser): """User model.""" username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() I was under the impression that I would at least get some errors if I tried to create a CustomUser with an invalid email. However, I have the following line it my unit tests: CustomUser.objects.create_user(email='dave') # creates user! Shouldn't the above make django throw an error, since 'dave' is clearly not an email? I know I can write a validator, but shouldn't there be already no need to do so? Here's the UserManager: class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) -
How can I run a Scrapy spider from a django view?
I have a scrapy django project and I have a spider that already works and saves items to the database. I tried running it like is shown down below but I get an error that says that the signal only works in the main thread of the interpreter. views.py from django.shortcuts import render from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from scraper.scraper.spiders.mercadoLibre import MercadoLibreCrawler # Create your views here. def get_products(request): process = CrawlerProcess(get_project_settings()) process.crawl(MercadoLibreCrawler) process.start() return render(request, 'products/get_products.html') I also tried making a django command but I get the same error. Does anyone know how to implement this? Thanks in advance. -
How can I reject a queryset object while serializing the data using a Django Rest ModelSerializer?
I have a queryset that I'm trying to serialize with my CasePartySerializer which inherits the Django REST Framework ModelSerializer class. Here is how I instantiate it. queryset = CaseParty.objects.all() serial = CasePartySerializer( list( queryset[ self.offset:self.offset + self.limit ] ), many=True, context={ 'tracked': self.tracked.value, 'request': self.request } ) Simple Enough, but what if I want to conditionally pass over and reject objects so they are not included in the finalized serial.data. In this example I realize it's easier to filter the queryset before serialization, but what about when the conditions are found in the field of a nested serializer? Filtering beforehand would not be a viable option. I'm sure there is probably some exception I can raise that would pass over this database object, but I'm unsure what that would be. I looked through the documentation without any luck; it's something that surprised me considering the quality of the REST Framework documentation. I'm probably missing something simple. Here is my CasePartySerializer so you can see my conditionals. In this example I want to check my CaseTrack model using the object as the foreignkey to see if it exists and return the tracked date if it's active or false if inactive. If … -
How to implement the ability to get data in real-time using websocket for my existing Django Rest Framework App
I have my API build with Django Rest Framework, I have read the docs (https://channels.readthedocs.io/en/stable/tutorial/index.html) but I am having troubles to implement for Rest Framework, so I need some human interaction. My app is an existing one so I must implement this with the existing "architecture" model-serializer-view. Is there any possibility to implement this real-time(using websockets in front-end) like using my views as consumers or something like this? -
I'm trying to build a user recommender system for my website. But my system is not working properly can anyone help me? I am using Django framework
I am trying to create a user recommender system for my website. It should recommend properties for my customers. But system is not working properly. Firstly I created a csv file and I converted it to a pickle file. I also attached my csv file bellow. This my views.py file. from django.shortcuts import render from django.http import HttpResponse # Create your views here. import os import pickle import random def models(request): filename=os.path.dirname(os.path.abspath(__file__))+'/dict.pickle' with open(filename,'rb') as f: model=pickle.load(f) return model def home(request): model=models(request) location=[] s=model.index.size for i in range(12): r=random.randint(1,s) location.append(model.index[r]) return render(request,'home.html',{'locations':location}) def detail(request): model=models(request) location=request.GET['location'] if location in model.index: return render(request,'detail.html',{'location':location}) else: return render(request,'detail.html',{'location':location,'message':'Ad Not found'}) This is my urls.py file """movieR URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from blog import … -
What backend framework is the best one for me? [closed]
I am a beginner in web development. I have been learning React for a few months now. I like React and feel pretty comfortable with it. Now I would like to start learning the backend more because one of my goals is to become a full-stack freelancer. I have 2 goals that I would like to achieve: I would like to do full-stack freelance web development for businesses. (Creating small e-commerce shops, landing pages, small web apps,...) In the future, when I am experienced enough, I would like to create SaaS product(s) and web apps. I have already been playing around with Django and Node.js but I am still not sure if either one of those is the best option for me and so I would love to hear your opinions. Also, I know there might be some people saying that any framework is good and I should just go with what I am the most comfortable with but I would really like to hear the specific comparisons and which do you think is the best for me. Thank you.