Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django RF - login/logut API views problem
I have a problem with logging in / logging out using the API. I created two views: class SignIn(APIView): def post(self, request): user = authenticate( request, username=request.data['username'], password=request.data['password'] ) if user is not None: login(request, user) return Response( {'username': request.user.username, 'logged': True}, status=status.HTTP_202_ACCEPTED ) else: if User.objects.filter(username=request.data['username']).exists(): return Response( {'init_data_problem': 'wrong_password', 'logged': False}, status=status.HTTP_409_CONFLICT ) else: return Response( {'init_data_problem': 'user_not_exists', 'logged': False}, status=status.HTTP_404_NOT_FOUND ) class SignOut(APIView): def get(self, request): if request.user.is_authenticated: logout(request) return Response( {'logged_out': True}, status=status.HTTP_200_OK ) else: return Response( {'logged_out': False}, status=status.HTTP_400_BAD_REQUEST ) Login seems to be working correctly: http POST http://127.0.0.1:8000/signin username="MyUser" password="mypassword" Response: { "logged": true, "username": "MyUser" } But using logout immediately afterwards gives the response: http http://127.0.0.1:8000/signout Response: { "logged_out": false } Why do I get a positive response about logging in, but the user is not "permanently" logged in? What am I doing wrong? -
Problem in calling items from the database django
I am trying to create a music streaming website.I have created a base template and extended it to two other templates.One is song_list.html and musicplayer.html. I have coded the views and urls to get absolute url. my song_list.html: {% extends "home.html" %} {% block content %} <div class="container"> {% for post in posts %} <a href="{{ post.get_absolute_url }}">{{post.song_title}} by {{post.artist}} from {{post.album}}</a><br> {% endfor %} </div> <div class="container"> {% include "pagination.html" with page=page_obj %} </div> {% endblock %} I want to render songs from the database in the musicplayer page after clicking the anchor tag. my msicplayer.html: {% extends "home.html" %} {% load i18n %} {% block content %} <div class="container"> <form class="" action="mediaplayer.html" method="get"> <div class="data-content"> <div class="container"> <div id="img-1" class="tabcontent"> <div class="blog-content"> <div class="row"> <div class="col-sm"> <div class="card" style="width: 18rem;"> <div class="img"> <img class="img-thumbnail" src="{{ post.img.url }}" alt=""> </div> <div class="card-body"> <div class="title"> <p>{% trans 'Artist:' %} {{post.artist}} </p><br> <p>{% trans 'Title:' %} {{post.song_title}}</p><br> <p>{% trans 'Album:' %} {{post.album}}</p><br> <p>{% trans 'Duration' %} {{post.song_duration}}</p><br> </div> <audio controls> <source src='{{ post.song.url }}' type="audio/mpeg"> Your browser does not support the audio element. </audio> </div> </div> </div> </div> </div> </div> </div> </div> {% endblock %} My app views: from django.shortcuts import … -
how do i manually authenticate and log in a user in django?
if request.method=='POST': try: email=request.POST['email'] password = request.POST['password'] if StudentUser.objects.filter(email=email).exists(): user = StudentUser.objects.get(email=email) if user.check_password(password): user = auth.authenticate(email=email) if user is not None: auth.login(request,user) messages.success(request,'Successfully Loggedin') return redirect('/') else: messages.warning(request,'Password does not match') return redirect('login') else: messages.error(request,'No Account registered with this mail') return redirect('login') except Exception as problem: messages.error(request,problem) return redirect('login') return render(request,'login.html') This above code i am trying to authenticate the user manually, but it is not working. i want to authenticate a user by manually checking the password. How can i do it? ** when I am passing the password in auth.authenticate function it is showing password does not match error -
Django dynamic show images from folders
I'm new in Django and I want to build a site that dynamically shows images from a folder that is not located in the project directory, these images are create each 10 minutes. I don't know if this is possible to do with Django or if there is another way of doing this. the structure of the folder is like this: Folder_img/month/day/images.tif -
How to perform some tasks with an incoming request before saving it or responding with django rest framework?
I'm quite new to django, i'm trying to migrate and old API built in express to Django Rest Framework, brief story: The API is meant to receive different kind of payplods from different device, in example { "device": "device001", "deviceType": "temperature_device", "deviceTs": timestamp, "payload": { "airTemp": X, "airHum": Y, } } the payload wouldn't be always the same, so other devices (different type) will bring different key - value pairs in the "payload" field. I'm using Django Rest Framework, alongside model serializers and and GenericViewSet, but the problem is that before storing the data to the DB and returning the HTTP Response, I need to perform a data validation (minimum, and maximum values) and in some cases, the device sends some "corrupted" data (In example: Negatives number comes with the following syntax: 1.-5 instead of -1.5), I need to fix these values and so on, finally, I need to perform two HTTP request to an external API with the fixed payload and and API Key (that should be stored in the device details model in my database) so, in short how can I perform any kind of -previous work- to a request BEFORE storing the data into the DB and … -
How get request in bootstrap-modal-forms in django?
I have problem with bootstrap-modal-forms for django. I installed packed with instructions from https://github.com/trco/django-bootstrap-modal-forms. It's work but I don't know how to get to options form in views.py. I must set client_id for form like initial in normal functions (form_add = IncomeForm(client_id=client_id, data=request.POST). How to use request in class BookCreateView? Any idea? models.py class BankAccount(models.Model): name = models.CharField(max_length=128) client_id = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True, null=True) start_value = models.DecimalField(decimal_places=2, max_digits=10, default=0) forms.py from bootstrap_modal_forms.forms import BSModalForm class BankAccountForm3(BSModalForm): class Meta: model = BankAccount fields = ['name', 'start_value', 'client_id'] views.py from bootstrap_modal_forms.generic import (BSModalCreateView) class BookCreateView(BSModalCreateView): template_name = '1.html' form_class = BankAccountForm3 success_message = 'Success: Book was created.' success_url = reverse_lazy('website:ustawienia') Here is modal form: https://finaen.pl/test -
add a show password button inside of input field - crispy forms
I want to add a show password button inside of the password input field. I am using crispy forms for styling so I am a little bit stuck on the best practice here. Currently I have a seperate checkbox field which is showing the password on check. Js is working fine here. I'd like to change de checkbox to a eye icon which is inside of the input field. I've managed to add the eye icon to the input field via css background: url(path-to-icon). I can't figure out how to change the icon to a button (1) and add my js to it (2). My form: class CustomSignupForm(SignupForm): user_group = forms.ModelChoiceField(queryset=Group.objects.exclude(name='admin').exclude(name='personeel').exclude(name='onderhoud'), widget=forms.RadioSelect(attrs={'placeholder': 'Soort klant:'}), initial=('particulier'), label='Soort klant' ) first_name = forms.CharField(max_length=30, label='Voornaam', widget=forms.TextInput(attrs={'placeholder': 'Voornaam'}),) last_name = forms.CharField(max_length=30, label='Achternaam', widget=forms.TextInput(attrs={'placeholder': 'Achternaam'}),) My HTML : <div class="form-row"> <div class="form-group col-md-6 mb-0"> <a>{{ form.password1 | as_crispy_field}}</a> </div> <div class="form-group col-md-6 mb-0"> <a>{{ form.password2 | as_crispy_field}}</a> </div> </div> <div class="form-row"> <div class="form-group col-md-12 mb-0"> <input class="ml-2" type="checkbox" onclick="ShowPassword()"> show password </div> </div> My css: #id_password1 { background: url("http://127.0.0.1:8000/static/user/media/eye_icon.png") no-repeat; background-size: 20px 20px; background-position: right; background-position-x: 97%; } #id_password2 { background: url("http://127.0.0.1:8000/static/user/media/eye_icon.png") no-repeat; background-size: 20px 20px; background-position: right 10px; background-position-x: 97%; } My js : … -
Django url regex termination $ not matching route
I have this rule that it is not matching the current route and I don't know why: path(r'api/user/connections/worker/<str:identifier>/$', views.connections.Detail.as_view()), The current url is: localhost:8000/api/user/connections/worker/test/ but it gives a 404. Without the dollar sign at the end it works but this would turn it into a catch-all rule for other routes that might share the same path and I'm trying to avoid it. Any ideas? -
Which database is better for an API project?
Which database is better for a restful API project that provides API for an android application? I designed about 20 tables in entity and relation forms for that and this application may have 100000 users so some tables may have 100000*100 records or much more. I want to do this project by python language and django framework so I found Mysql and Postgresql better for that but any one of them have some strengths and weaknesses. Which database can be better for this project? Are there any preferences? -
Django - Membership matching query does not exist
I'm trying to create a subscription style service on Django (using Django3) Basically, I had it working..ish, but my stripe customer keys weren't being added in, so I fiddled around to get that sorted. Now I'm getting this error - Membership matching query does not exist. this is whenever I'm trying to create an account, login or login to the admin of my Django project. I can't really figure out what the issue is, as I've reverted the changes I made to get the cust-Id (any tips here would be appreciated! lol) working again, but it's still throwing it up at me. Here's my code in my models, I can't even pinpoint where this issue is coming from if I'm honest. (I got this mostly from the JustDjango tutorial btw!) The debug thing is saying it's to do with the free_membership variable in the post_save_usermembership_create method though. So far I just have models.py and admin.py done to get this up & running - from django.conf import settings from django.db import models from django.db.models.signals import post_save from datetime import datetime import stripe stripe.api_key = settings.STRIPE_SECRET_KEY MEMBERSHIP_CHOICES = ( ('Regular', 'reg'), ('Premium', 'premium'), ('Free', 'free') ) class Membership(models.Model): slug = models.SlugField() membership_type … -
Why django app isn't scraping after deployment?
I started app on ubuntu server and everything worked properly on my machine also. After full deployment using apache2 one functionality isn't working. Scraping image, and title isn't working. If i add one manually then it appears, function is deleting that one as it's supposed to when i click on button. Permissions should be ok. There is no even title scapred and no error. apache2 conf Alias /static /home/matms/django_project/static <Directory /home/matms/django_project/static> Require all granted </Directory> Alias /media /home/matms/django_project/media <Directory /home/matms/django_project/media> Require all granted </Directory> <Directory /home/matms/django_project/dashboard> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/matms/django_project/dashboard/wsgi.py WSGIDaemonProcess django_app python-path=/home/matms/django_project python-home=/home/matms/django_project/venv WSGIProcessGroup django_app views.py filelist = glob.glob(os.path.join("/home/matms/django_project/media/", "*.jpg")) try: for f in filelist: os.remove(f) except Exception: pass old_articles = Headline.objects.all() old_articles.delete() session = requests.Session() session.headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0"} url = 'https://www.onet.pl/' content = session.get(url, verify=False).content soup = BeautifulSoup(content, "html.parser") posts = soup.find_all('div', {'class': 'sectionLine'}) for post in posts: try: title = post.find('span', {'class': 'title'}).get_text() link = post.find("a")['href'] image_source = post.find('img')['src'] image_source_solved = "https:{}".format(image_source) media = '/home/matms/django_project/media/' if not image_source_solved.startswith(("data:image", "javascript")): exists = 1 if exists == 2: pass else: local_filename = image_source_solved.split('/')[-1].split("?")[0]+".jpg" r = session.get(image_source_solved, stream=True, verify=False) with open(local_filename, 'wb') as f: for … -
Django add custom function to DetailView
I'm learning Django and just finished the tutorial. Now, I'm using Django's generic.DetailView to display the properties of one of my models. I'd like to add a button to the detail template that, when clicked, changes some attributes of the model. I know how to add a button, but I can't figure out how to add a custom function to my class DetailView(generic.DetailView and then to call it from the template. Just adding another function to the class didn't work. Overwriting get_object to make the attribute changes works but applies the changes whenever the page is loaded - not just when the button is clicked. Do I have to add a separate function outside the class and a separate URL to call the function? -
Django login by email or username
I wrote my own user model and auth backend. models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Utilities from utils.models import PyrtyModel class User(PyrtyModel, AbstractUser): """User model. Extend from Django's AbstractUser. Change the username field to email field and add some extra fields. """ email = models.EmailField( 'email address', unique=True, error_messages={ 'unique': 'That email is already taken.' } ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): """Return username.""" return self.username It has more fields but they don't matter right now. backends.py: from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend # Pyrty UserModel = get_user_model() class UserBackend(ModelBackend): """Auth against settings.USER_AUTH_MODEL. Override the authentication method in order to be able to authenticate with email or username. """ def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: try: pdb.set_trace() user = UserModel._default_manager.get(username=username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user If you check the line where I put the set_trace(), it is not getting my user objects by … -
Django - hide "This field is required." for BooleanField
I only want to display a checkbox the user has to click in order to confirm that notice has been taken: class CheckForm(forms.Form): confirmed = forms.BooleanField(required=True) def __init__(self, *args, **kwargs): super(CheckForm, self).__init__(*args, **kwargs) self.fields['confirmed'].label = 'I confirm that I have taken notice' The problem now is that my form shows the following label: "This field is required." at the template output. This is also making sense as I call the form like so at my views.py: form = CheckForm(request.POST) Is there any workaround to only hide the mentioned label at my template and keep required=True? Simply doing required=False at forms.py or removing request.POST from views.py is not a solution as this Field is per definition required and "if form.is_valid():" does not validate if request.POST is missing -
Restrict pages a anonymous user can view in Django
I am creating a website that has a flow that consists of about 7 pages. The user can only navigate to page1 of the flow if they have a specific url which looks like.. domain.com/flow/home/uid=123 The UID gets checked in my models to see if it exists and if it does, they get to view the correct page1. If it does not exist then they get redirected to another page. I want to make sure that they can navigate to page2 but only if they are allowed. I have 2 ideas which not sure if is the correct way or if another better way exists. Set a request variable to 'allowed' and check it on every page. If it isn't set then redirect them back to home. Pass the uid in the URL and make sure it is valid on every page. I am leaning towards option 1 as it is easier/cleaner but I wanted to check if any other solutions exist. -
social share links with django
In my django blog i want to share the post to facebook but its only gives me the url name. I want to share the post with images. i tried: <div class="p-2"> <a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}& og.image={{ posts.parent.image.url }}">facebook</a> </div> Now its only shares the cuurent url not the image i have it on the post. A help would be grateful. Thank you. -
django: import model mail field to a form resulting in SMTPRecipientsRefused error
I am trying to automatically send an email from a form in my django app. I need to access the email field from the following model: class Client(TenantMixin): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, default='') email = models.EmailField(default='') username = models.CharField(max_length=100, default='') ###### username password = models.CharField(max_length=100, default='') created_on = models.DateField(auto_now_add=True) auto_drop_schema = True I need to use this field to use in the email function in the following form: from django.core.mail import send_mail from customers.models import Client class etl(forms.Form): .... def process_data(self, url, *args, **kwargs): .... sender_email = 'my_email@gmail.com' recipient_email = Client.email email_message = 'allez la test' subject = 'alerts' print(recipient_email) send_mail(subject, email_message, sender_email, [recipient_email]) this gives me the error: SMTPRecipientsRefused at /upload.html {'"django.db.models.query_utils.DeferredAttribute object at 0x7f11bdf4ada0"': (501, b'Invalid RCPT TO address provided')} here is attached also my settings.py related to the issue EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'amazon-email' EMAIL_PORT ='465' EMAIL_HOST_USER = 'meItheuser' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = 'myemail@gmail.com' EMAIL_USE_SSL = True I am struggling with this error, I don't understand what could this be, when I hard write an email address it works fine and there is an email in the db to be access. Would someone has a clue of what I am doing wrong? -
Filtering ManyToMany Field in Django not working as expected
I'm using the Django docs here as well as some previous StackOverflow questions to figure this out but I can't seem to get it working. My goal is to be able to filter models based on a ManyToManyField. I followed the Mozilla Django tutorial to get this far but it didn't filter by ManyToManyField (in my case, category), so I wanted to add that. models.py from django.conf import settings from django.db import models from django.utils import timezone class Category(models.Model): name = models.CharField(max_length=200, help_text='Enter a category') def __str__(self): return self.name class BakingPost(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(max_length=1000) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) notes = models.TextField(max_length=1000, blank=True, null=True) ingredients = models.TextField(max_length=1000, blank=True, null=True) instructions = models.TextField(max_length=1000, blank=True, null=True) category = models.ManyToManyField(Category, help_text='Select a category') def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def display_category(self): return ', '.join(category.name for category in self.category.all()) display_category.short_description = "Category" admin.py from django.contrib import admin from .models import BakingPost, Category # admin.site.register(BakingPost) # admin.site.register(Category) @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): pass @admin.register(BakingPost) class BakingPostAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'created_date', 'published_date', 'display_category') list_filter = ('created_date', 'published_date') # i want to be able to filter by category here too def formfield_for_manytomany(self, db_field, request, **kwargs): … -
Could not parse the remainder: '('-date_posted')' from 'post.answers_set.all.order_by('-date_posted')'
{% for answer in post.answers_set.all.order_by('-date_posted') %} I am using this line to retrieve all Answers linked to this question in models.py. when I was working in django shell it works fine, but in django template it is showing weird error "Could not parse the remainder: '('-date_posted')' from 'post.answers_set.all.order_by('-date_posted')'". Is there any alternative, plz suggest. Thanks for your help in advance. -
Django Forms - 'add_order' forms.form ChoiceField from database table
I'm struggling for the last 3 days to create a form the right way in the submit & validation part - my goal is to submit validated order form, manipulating the data, adding to order to the database Model.py have Orders (typical orders db) with: client,product and sold_by as ForeignKey In the form I want to display all the client, product, and sold_by options, also sale_type options that I will set in the model level as (SALE_TYPE_CHOICES) The add_order.html is a raw form - attached below How can I Add select field list with clients & products list? What's the right way to add (SALE_TYPE_CHOICES)? How should I add them to the HTML? Thank you! model.py class Orders(models.Model): created_date = models.DateTimeField(auto_now_add=True) client_id = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='client') product_id = models.ForeignKey(Products, on_delete=models.CASCADE, related_name='product') sold_by = models.ForeignKey(Employees, on_delete=models.CASCADE, related_name='employee') sale_type = models.CharField(max_length=20, blank=True, null=True) ... my form class AddOrderForm(forms.Form): sold_by = forms.CharField(max_length=20) client_name = forms.CharField(max_length=20) sale_type = forms.CharField(max_length=20) product_name = forms.CharField(max_length=20) units_to_buy = forms.IntegerField() views.py - the beginning: def add_order_view(request): if request.method == 'POST': form = models.AddOrderForm(request.POST) if form.is_valid(): client_name = request.POST.get('client_name') product_name = request.POST.get('product_name') sold_by = request.POST.get('sold_by') sale_type = request.POST.get('sale_type') units_to_buy = request.POST.get('units_to_buy') add_order.html .... <form action="{% url 'adolim:add_order' %}" method="post"> <div … -
Cannot start Gunicorn, ModuleNotFoundError: No module named 'myproject.wsgi'
Here's my folder structure: ~/myprojectdir manage.py myprojectenv/ bin/ activate gunicorn pip3 python3 ... lib/ python3.6 ... fishercoder/ fishercoder/ asgi.py urls.py settings.py wsgi.py __init__.py ... blog/ views.py urls.py models.py admin.py apps.py templates/ ... catalog/ views.py urls.py models.py admin.py apps.py templates/ ... I have run source myprojectenv/bin/activate Here's my /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/myprojectdir ExecStart=/home/ubuntu/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target I've replaced this line: myproject.wsgi:application with this fishercoder.wsgi:application or this wsgi:application following the suggestion from this question Restarted Gunicorn. No luck in either. My ~/myprojectdir/fishercoder/wsgi.py looks like this: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fishercoder.settings') application = get_wsgi_application() Any one could shed any light on this would be greatly appreciated! -
Is it possible to pass Ajax response as template context variable in Django?
I sent an Ajax request to server to get some filtered data and here is a sample I receive from server: (3) [{…}, {…}, {…}] 0: {id: 1, title: "12 Rue Longueil", slug: "12-rue-longueil", latitude: null, longitude: null, …} 1: {id: 2, title: "15 Rue Sherbrooke LM", slug: "15-rue-sherbrooke-lm", latitude: null, longitude: null, …} 2: {id: 3, title: "Cycle Neron", slug: "cycle-neron", latitude: "-73.5987000000000000", longitude: "45.4799000000000000", …} length: 3 __proto__: Array(0) above data is logged from console. I want to display these data in HTMl tags within cards below. but for that I need to use that received data and create children using JavaScript e.g. document.createElement('DIV'). and then place these data. $(document).on('submit', "#filterform", function (e) { e.preventDefault(); $.ajax({ type: 'GET', url: "{% url 'listing:search' %}", data: { listing_for: $('#listing_for').val(), // cutted }, success: function (response) { const listings = eval(response); const content = document.getElementById('content'); for (let i = 0; i < listings.length; i++) { const div = document.createElement('div'); div.className = 'listing mgb-1'; div.innerHTML = data[i].title; content.appendChild(div); // have to create, add lots of divs and classes } } }) }) I was wondering if there is a way to sent Ajax request data as template variable? Or do I have … -
Trying to run python script on pressing a html button
I am trying to run a python script on pressing an HTML button. The script takes in a command-line argument and then prints the results based on the entered sentence. I am not sure why it is not working. The script that I want to run on entering text and pressing the HTML button is called WebOutputTest.py. I am not sure why nothing is happening when I enter the text and press the button. code snippet from index.html <form action="/external/" method="post"> {% csrf_token %} Input Text: <input type="text" name="param" required> <br><br> {{data_external}}<br><br> {{data}} <br><br> <input type="submit" value="Check tweet"> </form> code snippet from views.py def external(request): inp = request.POST.get('param') out= run([sys.executable,'//Users//yaminhimani//Desktop//tweetybird//WebOutputTest.py',inp],shell=False,stdout=PIPE) print(out) return render(request,'index.html',{'data': out.stdout}) code snippet from urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.noreq), #shows the html template for the website path('external',views.external), ] this is the python file I want to run after entering the text in the box and pressing the html button db = DatabaseInteractor.DatabaseInteractor() txt = WebOutput.WebOutput(sys.argv[1]) db.match_tweet_for_website(txt) -
how to calculate frequency of pairs in queryset
I have two models in Django: class Pair(models.Model): pass class Person(models.Model): pair = models.ForeignKey(to=Pair, related_name='mates') city = models.ForeignKey(to=City) So I need to calculate a frequency of pairs from different cities: city_a<->city_b: 100 city_a<->city_a: 80 city_b<->city_c: 200 ... for each person I can get the other guy's city via: person.pair.mates.exclude(id=person.id).first() or something like that so theoretically I can just loop through all instances of Person and then calculate the frequencies but apparantly that will be super inefficient. but I can't figure out how to get this info via standard queryset (if there is a way). Any hints would be welcome -
Can we extend templates from reusable apps without adding to the installed apps settings in django
I'm finding myself tough in understanding the below lines from django-docs, I thought the re-usable apps can be used in the project without adding them to the INSTALLED_APPS by wiring them in the URLS and in templates. But, they are not working.. !! Projects and applications Applications include some combination of models, views, templates, template tags, static files, URLs, middleware, etc. They’re generally wired into projects with the INSTALLED_APPS setting and optionally with other mechanisms such as URLconfs, the MIDDLEWARE setting, or template inheritance. I have created app1 and app2 in the project sample. I'm using the below view in the app1 urls.py which is returning the HttpResponse. URL Wiring: def test_home(request): return HttpResponse('Testing') But, when I'm using the template to be rendered by the same view it's throwing an error that template doesn't exist def test_home(request): # return HttpResponse('Testing') return render(request, 'app1/home.html') If I'm adding app1 to the sample project settings, I'm getting the response Template Wiring/Inheritance In this scenario I have created a base template in the app2 directory and I have tried extending that in the app1 template home.html which is throwing an error as base.html doesn't exist. But, it's working when I'm adding app2 to the …