Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should i have one django view that has lots of children or just lots of views
I have an api in django with a User class, this class has all CRUD operations and then I have children classes that inherit from this and on get or post requests they call x function e.g BaseUser(APIView): CRUD CreateUser(BaseUser): def post(self, request): BaseUser.create_user(request) then i have another for delete or get info etc but should these be this pattern where its one top user class and lots of children that inherit and call the CRUD operations or should these classes be broken out into their own thing e.g. one with all create logic then one with all delete logic for user. -
Template inheritance error in Django with TemplateDoesNotExist
base.html and child html file are in one directory app/templates/app: lead_list.html {% extends "leads/base.html" %} {% block content %} <a href="{% url 'leads:lead-create' %}">Create a new Lead</a> <hr /> <h1>This is all of our leads</h1> {% for lead in leads %} <div class="lead"> <a href="{% url 'leads:lead-detail' lead.pk %}">{{ lead.first_name }} {{ lead.last_name }}</a>. Age: {{ lead.age }} </div> {% endfor %} {% endblock %} base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DJCRM</title> <style> .lead { padding-top: 10px; padding-bottom: 10px; padding-left: 6px; padding-right: 6px; margin-top: 10px; background-color: #f6f6f6; width: 100%; } </style> </head> <body> {% block content %} {% endblock %} </body> </html> views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Lead, Agent from .forms import LeadForm, LeadModelForm def lead_list(request): leads = Lead.objects.all() context = { "leads": leads } return render(request, "lead_list.html", context) settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I am getting the error with django.template.exceptions.TemplateDoesNotExist: lead_list.html I think I have done everything right and compared with documentation but could not find my error. Thanks in advance! -
Google map integration for website through django
I'm using django(python) to code the page. is it possible to add a Google map feature, that specifically searches for nearby supermarkets based on user location? I see how changing the api adresss to change the search results in the Google document but in all the examples you need to have location as a latitude and longitude. can the webpage just prompt the user for location permissions and the code uses that location? I'm not exactly sure if I made the question clear but I will be grateful if anyone could point me in the right direction. -
What is the ideal way to store comments to a blog?
I am making a demo website using django and in the website you have blogs. What im trying to add is a way to add comments for every blog and what im trying to figure out is how to arrange the database. I thought about 3 options either you store with every blog a list of the comments or you store a list of all comments and the blog they belong to or you create a table for every blog with the comments. Which of these is the best in terms of how dificult it is to implement and how memory consuming it is? -
Instance continues to Fail Health check after python3 and Ubuntu 18.04 update (Django+Nginx+Uwsgi)
My Django + uwsgi + Nginx app has failed for days now and I am not sure what is happening. It seems that my Nginx health check seems to be okay and my Django App is functioning correctly. I am starting to have a feeling it is my uwsgi config. I have a shadow server running the exact same configuration and it started up perfectly. Any tips here? uwsgi.ini chdir = /opt/django/www/src module = my_site.wsgi:application master = true processes = 10 pidfile = /tmp/my_site.pid socket = /tmp/my_site.sock vacuum = true max-requets = 5000 daemonize = /var/log/django/uwsgi.log req-logger = file:/var/log/django/req.log logger = file:/var/log/django/err.log nginx.conf upstream django { server unix:///tmp/my_site.sock; # for a file socket } server { listen 443 ssl; ssl_certificate /opt/django/www/ssl/my_site.com.crt; ssl_certificate_key /opt/django/www/ssl/my_site.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; send_timeout 100s; proxy_read_timeout 500; # max upload size client_max_body_size 75M; # adjust to taste location /static { alias /opt/django/www/src/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { proxy_read_timeout 500; uwsgi_read_timeout 500; uwsgi_pass django; include /opt/django/www/src/uwsgi_params; # the uwsgi_params file you installed } } server { # the port your site will be served … -
I need to upgrade me code for DRY and easy refactoring in future
I need to move api/ prefix to main urls.py, cause it'll be easy to rename in one place later. Plus my reviewer ask me don't duplicate version in router, and write 'v1'once. my main urls: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('posts.urls')), ] if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT from django.urls import include, path from rest_framework.authtoken import views from rest_framework.routers import DefaultRouter from .views import CommentViewSet, PostViewSet router = DefaultRouter() router.register('v1/posts', PostViewSet) router.register(r'v1/posts/(?P<post_id>\d+)/comments', CommentViewSet, basename='Comment') urlpatterns = [ path('api/v1/api-token-auth/', views.obtain_auth_token), path('', include(router.urls)), ] i tried: router = DefaultRouter() router.register('posts', PostViewSet, basename='posts') router.register(r'posts/(?P<post_id>\d+)/comments', CommentViewSet, basename='comments') urlpatterns = [ path('api/v1/api-token-auth/', views.obtain_auth_token), path('api/v1/', include(router.urls)), but its wrong/ -
AttributeError on <module '__main__' when deploying app on Heroku via Gunicorn
I am new to Django/Heroku but am trying to launch my first project with these tools that includes a pre-trained SK model and custom Pipelines. I've got everything working fine locally but when I try to push to Heroku I keep receiving 500 errors and my log tail is posted below. I can't seem to solve it. My custom transformer pipeline that I wrote has a class called FeatureSelector as well as CategoricalTransformer, which I've pasted into the manage.py file (as someone suggested doing that, and I didn't know where else they might go). Heroku, or gunicorn, or something seems to have issues with this. AttributeError: Can't get attribute 'FeatureSelector' on <module '__main__' from '/app/.heroku/python/bin/gunicorn'> I've tried renaming the apps.py file, putting the pipeline in WSGI, moving the joblibs etc. but nothing seems to work for me. Thanks to anyone who's able to help out. Also I've posted the entire log file at the very bottom for anyone who needs it. File structure: project --app -- ml_models -- model.joblib -- transformer.joblib -- apps.py -- views.py apps.py from django.apps import AppConfig from django.conf import settings import os from joblib import load import warnings warnings.filterwarnings("ignore") class PredictorConfig(AppConfig): # create path to models … -
Using context name in django is not working Dataframe.to_html()
I have a problem following one tutorial on displaying dataframes in django web page my Views.py is as follows from django.shortcuts import render from products.models import Product import pandas as pd def chart_select_view(request): product_df = pd.DataFrame(Product.objects.all().values()) context = { 'Products': product_df, } return render(request, 'main.html', context) I have two errors the first is unable to import pandas as pd and I've already installed it in my venv the second is not important but here it is "object has no members" and I know it's a pylint error when I want to show Products in the main.html it displays error "Invalid block tag on line 9: 'Products', expected 'endblock'. Did you forget to register or load this tag?" the main.html is {% extends 'base.html' %} {% block title %} {% endblock title %} {% block content %} <h1>Hello World</h1> {% Products %} {% endblock content %} Can somebody help I'm following the tutorial perfectly but it shows an error to me when it's working fine in the video. -
Django: How to efficiently add objects to ManyToManyFields of multiple objects?
We have a student and class many to many relation, where a student can take multiple classes, and a class can be taken by multiple students. class Class(models.Model): name = models.CharField(null=False, max_length=128) class Student(models.Model): first_name = models.CharField(null=False, max_length=64) classes = ManyToManyField(Class) What is the fastest way to add some object or a whole QueryList (in our case: all classes with Biology in their name), to the ManyToManyField of each object in another QueryList (in our case: all students whose first name is Linus)? The current way I am doing it is: biology_classes = Class.objects.filter(name__contains='Biology') linuses = Student.object.filter(first_name='Linus') for linus in linuses: linus.classes.add(*biology_classes) Which I guess hits the db for each student. I wonder if there is maybe some way to do it all "at once". Maybe something that looks something like this: linuses.classes.add(*biology_classes) # (this does not work) -
I can't loop over my ids params, how can i receive and loop over
I'm working on a small project using Django and VueJS, i would like todo a bulk delete, i'm sending an array object of my IDs, using Axios in the body like that : [1,2,3] this is my code : getAPI({ method: 'DELETE', url: 'api/contact/delete/', data:{ ids: this.selected } }).then((response) => { console.log(response.data) }) how can i loop over my ids in django this is my function : @action(methods=['delete'], detail=False) def delete(self, request): for i in request.body: print(request[i]) -
Control of interaction with web system
I am creating a website with several dashboards to view the progress of their activities. But I must also create a profile where the administrator performs an access control per user through graphics. Example: • User lists • Number of accesses per user (daily) • Amount of download per user (pdf) • Interaction time per graph (Optional) • Interaction time with the app • Alerts when a user produces below average. • Assignment of roles • Assignment of equipment The language I am using is python, django and javascript. is there an example where it allows me to perform this control.? I would really apreciate it. Greetings. -
Showing error: "ModuleNotFoundError: No module named 'pip._internal.models.target_python'"
iM trying to install django frame work into a specific virtualenv(name=test) using 'pip install virtualenvwrapper-win' command, but the following error has occured: enter image description here #I checked my pip version and reinstalled it in every possible way to ensure it was installed properly #I tried adding scripts path way to environment variables BUT NO USE. NOW IM LOOKING FOR A SOLUTION.SEE THE PICTURE FOR INFO -
After deploying my django project to aws lambda, my static files don't work, why?
I create a django project and i used a bootstap and everything works well but after deploying my project to aws lambda using zappa, static files don't work anymore! I checked the settings and here it is: import os STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] also in the index.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <h3>store</h3> The static file location is in the same directory as the project folder and the application folder. when i go to 127.0.0.1 (local-host) the page is white with no color. (i changed the color using css) -
Django - CSRF cookie not set when logging using Ajax
I'm creating a separated Vue/Django app where Vue handles the whole frontend and communicates with Django using JSON, Vue is standalone and it's not rendered by Django. Since i don't want to lose the benefits of the built-in Django Session Authentication and keep using django-allauth (which supports AJAX), i'm setting up both backend and frontend and same server and on same port. Right now i'm trying from my dev environment to setup authentication, but i've been going in circles for the whole day without managing to do it. I keep getting the following error: [23/Mar/2021 17:46:55] "OPTIONS /accounts/login/ HTTP/1.1" 200 0 Forbidden (CSRF cookie not set.): /accounts/login/ Here is my Vue/Axios code: get_csrf() { axios.get('http://127.0.0.1:8000/get_csrf/') .then(response => { this.csrf_token = response['data']; }); }, authenticate() { this.get_csrf() axios.post('http://127.0.0.1:8000/accounts/login/', { username: 'root', password: 'test', }, { headers: { 'X-CSRFTOKEN': this.csrf_token //I also tried X-CSRFToken instead, same outcome.. }, }) .then(function (response) { console.log(response) }.bind(this)) }, The function get_csrf is used to retrieve a csrf cookie from a endpoint in my Django app. My Django settings.py code: CORS_ALLOW_HEADERS = list(default_headers) + [ 'xsrfheadername', 'xsrfcookiename', 'content-type', 'x-csrftoken', 'X-CSRFTOKEN', ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:8000", "http://127.0.0.1:8000", ] CSRF_TRUSTED_ORIGINS = [ "http://localhost:8080", … -
Prettify html page in django
So i was making this django website and it does just what i want. But now i need to output the html code with indentation to an html page. I have used bs4 `s .prettify() method but it only shows the indented code on console. This is my views.py main function from django.shortcuts import render import requests from bs4 import BeautifulSoup as soup from . forms import InForm def main(request): if request.method == 'POST': form = InForm(request.POST) if form.is_valid(): you = form.cleaned_data.get('you') htm = requests.get(you) dat = soup(htm.content, 'html.parser').prettify() print(dat) return render(request, 'main.html', {'dat':dat}) else: form = InForm() return render(request, 'main.html', {'form':form}) the output i get i`m using an android emulator for the project -
AttributeError: module 'courses.views' has no attribute 'search'
I hope you are doing good and safe. I am a beginner Django learner and working on an education site from a Youtube tutorial. My problem is I don't know where my error is, I know it is in views but I don't know where. I hope you can help me and save me from this desperation. Here are some codes of the project. [1]: https://i.stack.imgur.com/zY665.png [2]: https://i.stack.imgur.com/h2DGJ.png [3]: https://i.stack.imgur.com/2LgzE.png [4]: https://i.stack.imgur.com/DT6mG.png [5]: https://i.stack.imgur.com/YQU25.png [6]: https://i.stack.imgur.com/3mUAy.png -
Alguien que me pueda ayudar con este error
Soy nuevo y necesito que me ayuden con un error que tengo con ngx.editor, tengo un proyecto en el cual cuando escribo un nuevo foro, este cuadro de texto no me reconoce unas letras (p,j,k,n) y no entiendo cual sea el motivo. alguna sugerencia por favor -
Django bulk_update changes all values to first update index
def update_grid(df, database,report_name): report=eval(report_name) print(report) update=report.objects.using(database).all() for x in range(len(update)): update[x].brand=df[x]['brand'] print(update[2].brand)#prints 444 print(update[2000].brand)#prints 333 report.objects.using(database).bulk_update(update, ['brand']) return ('ProductData updated') The code above should convert some of the brand indexes into 444 or 333.However when I look in the database all brands are converted into 444 instead of only some being 444. -
Django: how to order a queryset by a related object if it exists and by a field if it doesn't?
I have two models: class Product(models.Model): name = models.CharField(max_length=200, blank=False) price = models.DecimalField(max_digits=100, decimal_places=2, blank=False) class Meta: verbose_name = 'product' verbose_name_plural = 'products' class PromotionPrice(models.Model): product = models.ForeignKey(Product, related_name='promotion_prices', on_delete=models.CASCADE, null=False) price = models.DecimalField(max_digits=100, decimal_places=2, blank=False) start_date = models.DateTimeField(blank=False) end_date = models.DateTimeField(blank=False) class Meta: verbose_name = 'promotion price' verbose_name_plural = 'promotion prices' I want an efficient way to order all the Product objects by the price, taking into account the promotion price if it exists. E.g. I have the following list of Product objects: [ { id: 1, name: "Apple", price: "5.00", promotion_prices: [] }, { id: 2, name: "Banana", price: "10.00", promotion_prices: [] }, { id: 3, name: "Orange", price: "15.00", promotion_prices: [ { product: 1, price: "9.00", start_date: "2021-03-20T00:00:00Z", end_date: "2021-03-20T00:00:00Z" } ] } ] I want the result of ordering to be "Apple", "Orange", "Banana", because "Orange" has a promotion price on it. I'm dealing with thousands of objects, so sorting using sorted() takes ages. -
Best way to save all actions in an application with Django
I would like to save all actions that my staff doing in my application. I could save a report when all function are called, however, I want to save all the actions that was doing in this function. For example, if you update one field in some form, I would like to save what forms are updated. What is the best way to do it? Manual? Is there some library that help me to do it? I did not find any. I read about Django Signals but I think that is not the way. I can save a report when my models are saved, but I do not know exactly if it is going to save all my requirements and to be honest, I do not know how it working correctly. class somemodel(admin.ModelAdmin): ........ def save(self, *args, **kwargs): super().save(*args, **kwargs) ...do whatever for save the actions... -
How to expand accordian with url in Django template
I'm adding some FAQs to our product pages with the use of a Bootstrap (v5) accordian. If asked a question by a potential client in an email, I want to be able to send them the URL that takes them directly to the answer and expands the accordian item. Each FAQ is loaded from a Django model. The ID from each FAQ is the variable I want to use for each accordian item. I've looked at some other answers on here but can't seem to figure out how to write the script needed for my specific use case. I know nothing about JQuery so haven't included scripts I've found while searching for the answer as they're likely unhelpful. This is my HTML: <section class="bg-white" style="padding: 3rem"> <div class="container"> {% if faqs %} {% for service in services %} {% with name=service.0 %} <h3>{{ name }}</h3> <hr> <!----------------------- ACCORDIAN ------------------------------------------------------------> <div class="accordion accordion-flush mb-3" id="accordionFaq-{{ name }}"> {% for q in faqs %} {% if q.related_service|lower == name|lower %} <div class="accordion-item"> <h3 class="accordion-header" id="faq-heading-{{ q.id }}"> <a class="accordion-button collapsed" data-bs-toggle="collapse" href="#faq-{{ q.id }}" aria-expanded="false" aria-controls="faq-{{ q.id }}"> {{ q.question }} {{ q.id }} </a> </h3> <div id="faq-{{ q.id }}" class="accordion-collapse collapse" … -
Django and Node.js integration
I'm trying to create a python/Django project and in that project, I want to integrate a video calling module. But I am just creating this project for my semester project, in short, using localhost. I have searched many API's but some of them require purchasing and others don't support the Django framework. However, I found one Node.js code, but I don't know how to integrate it with Django. Can anyone please help me out that how I can integrate video calling into my Django project? Most recently I found Twilio, but it has node js code. please let me know how can I integrate it in my Django project. Thank you. -
Django: How to make Id unique between 2 different model classes
Im working on a problem that requires 2 different models to have unique Ids. So that an instance of ModelA should never have the same id as a ModelB instance. For example, What would be the Django way of making sure these two model types wont have overlapping Ids? class Customer(models.Model): name = models.CharField(max_length=255) class OnlineCustomer(models.Model): name = models.CharField(max_length=255) -
Django Post error: 'User' object has no attribute 'profile' issue at views.py
I think this error message has been posted in stackoverflow before, but even looking at the other posts I still cannot see why I am still getting this error. I am really running out of ideas on how to solve this (I am a bit new to Django too) so if anyone can give me a helping hand it would be much appreciated! my code: models.py (this was properly indented in my IDE, I just cannot get this properly done in this post): class Helper(models.Model): user = models.OneToOneField(User, unique=True, related_name='profile',on_delete=models.CASCADE) phone_regex = RegexValidator(regex=r'^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$') phone = models.CharField(validators=[phone_regex], max_length=17) STATUS = ( ('Available', ('I am available to help.')), ('Not Available', ('Busy right now')), ) availability = models.CharField(choices=STATUS, default='Available', max_length=222) Verification = ( ('Yes', ('Verified.')), ('No', ('Not Verified')), ) verified = models.CharField(choices=Verification, default='No', max_length=222) def __str__(self): return f'Helper: {self.user.username}' def save(self, *args, **kwargs): super().save(*args,**kwargs) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Helper.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py: class UserCreateForm(UserCreationForm): class Meta: fields = ["username", "first_name", "last_name","email", "password1", "password2"] model = User class HelperCreateForm(forms.ModelForm): class Meta: model = Helper fields=('phone','availability') views.py (this was properly indented in my IDE, I just cannot get this properly done in this post): def … -
Django Migration - Migration missing some fields
This is an easy exercise, i'm a beginner about models and migration Models.py from django.db import models # Create your models here. class Flight(models.Model): origin = models.CharField(max_length=64), destination = models.CharField(max_length=64), duration = models.IntegerField() Then i'm going on my prompt and type python manage.py makemigrations and in migrations/0001_initial.py # Generated by Django 3.1.7 on 2021-03-23 16:19 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Flight', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('duration', models.IntegerField()), ], ), ] How u can see origin and destination don't migrate How can i fix it?