Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calking a python script in docker container from another docker container holding django app
I am completely new to containers and docker. I build a simple django app for handling api service. Now there are two main algorithm running which provide the results. Right now the algorithms resides in the single container which is a django app. Now with the view to ease the scaling, upgrade I am thinking to separate the two algo in a two different containers. So three containers two for algo and one for handling django rest service. First of all i want to understand if my approach is right. Now how the communication will take place between the container. The algo is just pure python script. At present i just call the function and the result is passed as api response. Do I need to wrap my algo too in an api. I dont want to this actually since i want a single point to serve all api request which is the django app. So how I would call my python scripts running on a container from another container holding django app. -
Cannot run server in virtualenv on Gitbash "Couldn't import Django. Are you sure it's installed and
I am trying to run the django server locally on my gitbash. I started with the following command lines: virtualenv env pip install -r requirements.txt pip install django django-admin --version 3.0.7 pip --version 19.2.3 python --version 2.7.6 Variable PATH: C:\Users\circulating\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\circulating\AppData\Local\Programs\Python\Python37\;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Python27;C:\Users\circulating\AppData\Local\atom\bin;C:\Users\circulating\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Users\circulating\AppData\Roaming\npm;C:\Program Files\heroku\bin;C:\Program Files\nodejs;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem Error $ python manage.py runserver 0:8000 Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 13, in main "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Based off the error I need to: install Django(which is since i checked the version) Add to PYTHONPATH environment variable(not sure if or how to do this) Activate a virtual environment(activated in beginning) I am not sure if the problem is with my gitbash running on python2.7 as oppose to 3.7. The Django docs say Django(3.0) -> Python(3.6, 3.7, 3.8). However, I have both python 2.7 and 3.7 installed and in my PATH variable -
How do I do nested loops in Django?
I'm trying to output to a Django template one row that has four DIVs: I need to have two nested For Loops so that each time the fourth DIV is outputted, it will create a new row. In Java, it would be like this: for(int i = 0; i < object_list.length; i++){ <div class="row"> for(int j = 0; j < 4; j++){ <div class="col-md-3"> } } The code I'm using in the template is: {% for object in object_list %} {% with object|search as search_results %} {% if search_results == 'Post' %} [need to fill in appropriate HTML] {% endif %} {% endwith %} {% endfor %} How can I accomplish this? -
Django 3.0. Is there a way to update let say multiple users in a single page with a form?
What I'd like to do is that I want to show users and want to update them in a single page. The page looks like below user 1 user-name: <input> user-age: <input> user-gender: <input> user-birthday: <input> user 2 user-name: <input> user-age: <input> user-gender: <input> user-birthday: <input> <submit button> -
Get the current refresh token in backend in Django simple-jwt token authentication
I would like to received the refresh token in backend side to blacklist the token. I am getting the access token in request.header as user pass it in order to call the API, is there any way to get the refresh token while user is not passing in header. -
Django Render HTML via AJAX - Missing Context Variable Data
In my Django web app, I'm trying to dynamically update only a certain section of my page via AJAX, but doing so by returning/replacing HTML in a child template ({% include 'keywords.html' %}). I understand that I can (and maybe should) return a JsonResponse (and I have done so successfully), but I'd like to try and get the below implementation working (as others seem to have). The view successfully returns the HTML to the AJAX response, but lacking the data contained in the keywords context variable. templates/index.html ... <div id="keywords"> {% include 'keywords.html' %} </div> ... templates/keywords.html <div id="keywords"> {% if keywords %} {% for keyword in keywords %} <p>{{keyword.word}}</p> {% endfor %} {% endif %} </div> views.py def add_keyword(request): if request.method == 'POST': form = KeywordForm(request.POST) if form.is_valid(): ... keywords = Keywords.objects.values()... print(keywords) # this works, contains a queryset with data context = { keywords: keywords, } return render(request, 'keywords.html', context)) index.js // i've also tried jquery .load() $.ajax({ url: data.url, type: "POST", data: { keyword: keyword, csrfmiddlewaretoken: data.csrf_token }, success: function(data) { $("#keywords").html(data); } }); AJAX Response data: <div id="keywords"> </div> What might I be missing, or doing wrong? -
Django-registration-redux with postgresql
Does django-registration-redux work with postgresql? It's working fine with sqlite3, but throwing errors with postges. Have followed the documentation thoroughly. When I tried to migrate the error appears. -
Function field in model django
I have a model with a json field: from django.contrib.postgres.fields import JSONField data = JSONField(default=dict) I want each item in the model table to have its own way to interact with the json data field. For example: item 1: prints each element in the json item 2: print each element that is a list in the json item 3: print each element with a key that starts with "j" Thus, each item would need to store some data about how to do what is listed above. How could I achieve this in django with a postgres db? Thanks!! -
Implementing typeahead search with Django and React
I have a web app using Django for the backend and React for the frontend. I want to have a search option where the user can select what university they attend, and I already have a University table in my database. When the user types something in the search bar, it should bring up the matching entries from the University table (ex: user types in "S" and "Stanford" and "Swarthmore" show up). Are there any guides/tutorials that will help me with this? Is the best way for the frontend to request all colleges from the API endpoint in the beginning, then when the user types anything, it will get the relevant results from the data returned by the API endpoint? -
drf-yasg Customize SwaggerUIRenderer
I'd like to customize the style (font, colors, logo, etc) of drf_yasg generated docs. I see that I can extend drf_yasg/swagger-ui.html with the blocks extra_head, extra_styles, extra_body, extra_scripts, and can even overwrite the other blocks if I need to. What I am not clear on is how I point to my template that extends swagger-ui.html. I started with class MyCustomSwaggerUIRenderer(SwaggerUIRenderer): template = 'api/custom-swagger-ui.html' I want to replace SwaggerUIRenderer with MyCustomSwaggerUIRenderer in get_schema_view but do not understand how/where to do it without explicitly trying to enumerate all the other Renderers required too in some subclass of rest_framework.views.APIView and that seems convoluted. Pointers to docs or examples are appreciated. I've already read https://drf-yasg.readthedocs.io/ without success. -
What is the best way to import postgreDB into Django? [duplicate]
I'm developing Django web apps, and I already have a database created by PostgreSQL. Since dumped sql file can not directly import into Django, what is the best way to import? -
How to call the function in the class model when the field changes?
in this class when i add post I want to call category_change When the category field changes... how can i do that!? class Post(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey('Category', on_delete=models.CASCADE,null=True,blank=True,editable=False) image = models.ImageField(default='default.jpg', null=True, blank=True) series = models.ForeignKey('Series', on_delete=models.CASCADE,null=True,blank=True,editable=False) tags = models.ManyToManyField('FilmTags', related_name='post') content = models.TextField() watch = models.TextField(null=True, default='') download_url = models.CharField(max_length=300, null=True, default="#") created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) publish = models.BooleanField(default=True) views = models.IntegerField(default=0) def category_change(self): if category.title == "series": self.image.editable = True self.series.editable = True self.image = self.series.image else: self.image.editable = True -
how to convert large csv to json in action django-admin with celery?
I am trying to convert large csv in django-admin to be converted to json, through a django action that uses celery in the background. So that the user does not have to wait to finish for use the system. I have some errors, could your help? models.py class DataExtraction(models.Model): dataset = JSONField(blank=True, null=True) def __str__(self): return str(self.pk)class Extraction(models.Model): class Extraction(models.Model): name = models.CharField(max_length=100, blank=False, default=None) lawsuits = models.FileField(blank=True, null=False) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Extraction, DataExtraction from web.core.tasks import convert_data import csv def spider(modeladmin, request, queryset): for extraction in queryset: csv_file_path = extraction.lawsuits.path convert_data(csv_file_path).delay() spider.short_description = "Apply Spider" class ExtractionAdmin(admin.ModelAdmin): list_display = ['name'] actions = [spider] admin.site.register(Extraction, ExtractionAdmin) admin.site.register(DataExtraction) tasks.py: from celery import shared_task from web.celery import app from web.core.models import Tasks, DataExtraction, Extraction import csv def read_data_csv(path): with open(path) as csv_file: reader = csv.DictReader(csv_file, delimiter=',') csv_data = [line for line in reader] return csv_data @shared_task() def convert_data(path): dataset = read_data_csv(path) aux = [] for data in dataset: obj = DataExtraction(dataset=data) aux.append(obj) DataExtraction.objects.bulk_create(aux) print('finished!') Errors: (1) celery_1 | File "/code/web/core/tasks.py", line 17, in name celery_1 | def convert_data(path): celery_1 | AttributeError: 'FileDescriptor' object has no attribute 'path' (2) web_1 | File "/code/web/core/admin.py", line … -
Django-admin custom command don't store cache value
I've an unexpected behavior while using django command. I'm using the standard Django cache system. My settings : CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', 'TIMEOUT': 0, } } This is my command code : #coding: utf-8 import os import sys import time from django.core.management.base import BaseCommand from django.core.cache import cache class Command(BaseCommand): def handle(self, *args, **options): print(cache.get("mykey")) print(cache.set("mykey", "TEST", 300)) When I run it twice within the same minute I get the following output : (venv_crypto_bot) macbook-pro:project dauzon$ python manage.py generate_data None None (venv_crypto_bot) macbook-pro:project dauzon$ python manage.py generate_data None None I'm on the dev server. Clearly, Django don't store value in cache when I using a command. I don't know if it's due to I run the development server. Cache runs correctly when I visiting the webpages of my dev server. There are no details about the disabled cache (on command) in the Django documentation. How can I store cache value within a Django custom command ? -
Building a website using Python and Django
I am trying to build a website using Python and Django but I am not even able to print Hello World! I am able to get to the part where it says Django successfully installed though. It's what comes after is troubling me. I have been following many tutorials in youtube but to no avail I keep getting stuck at the same point. Can someone please guide me through this issue? I have attached screenshots of my progress. I am not able to understand the error either. Please help me out with this issue. [enter image description here] [enter image description here][1] [enter image description here][2] [enter image description here][3] [enter image description here][4] [enter image description here] [enter image description here][5] [enter image description here][6] Thanks and Stay Safe -
Getting a NameError while following django poll app tutorial
I am following django tutorial but i am getting a nameError. name Question is not defined from django.http import HttpResponse from django.http import HttpResponse def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) -
Access super model in Base Model django
I have a base model defined as follows: class BaseModel(models.Model): date_created = models.DateTimeField(editable=False) date_modified = models.DateTimeField(blank=True) id = models.CharField( max_length=11, unique=True, primary_key=True, blank=True, ) class Meta: abstract = True Now, I want to add a save method and in the save I want to filter through the super models table as follows: SUPER_MODEL.objects.filter(id=id) Where super model is the model that extends BaseModel. How would I access this super model? Does this make sense? Thanks! -
extending existing model with new fields
I have a django project, where I use a third-party extension that inserts its own models (something like ExtensionApp.Model1 and ExtensionApp.Model2). I need to make some adjustments (specifically add a couple new fields there). Right now what I do is OneToOne field in my own app model to ExtensionApp.Model1, and there I can add what I need. I just don't want to touch the core of this extension app. But I think whether it is the right way to do? Is there a way to add new fields to existing models of third-party app? I know there are proxy models (https://docs.djangoproject.com/en/3.0/topics/db/models/#proxy-models) but these allow to add new methods, not fields. -
How to create an app in a directory with the same name?
I would like to create a django app in a directory with the same name for example: ./manage.py startapp offer_place ./x/offer_place instead of creating the apps files into /x/offer_place destination. It treats offer_place as a python module an produces that error: CommandError: 'offer_place' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. I also tried to delete offer_place foler, but it gave me an error that the folder does not exist! -
how to use django signals using singnals.py
the django signal is not working when am using signals.py but it works if i use the normal models.py accounts/signals.py from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from .models import Profile def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) print("profile created") post_save.connect(create_profile, sender=User) def update_profile(sender, instance, created, **kwargs): if created == False: instance.profile.save() print('profile updated') post_save.connect(update_profile, sender=User) accounts/app.py from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' def ready(self): import accounts.signals accounts/settings.py INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', ] -
How to order_by calculated fields based on some other model? (Django)
For eg: Model Company has fields: companyName and stock_price Model Products has fields: product_price and company_name I want to do something like: Company.objects.order_by( stock_price / [divided by] Products.objects.filter(company_name = Company__companyName).aggregate(Sum('product_price')).get('product_price__sum')) Essentially, what I want to do is divide the stock price of company X by the aggregate of product_price of the products of company X and use the resulting calculation to order all the objects of Company. I just want to know if doing such a thing is possible in Django. Thanks! -
How to deal with sensitive user data in Django?
I am working on a project in django that collects sensitive data (medical data) about its users. I want to store this data and collect it to get stats on it. I want to know what precautions I need to take from a legal standpoint. Do I need to collect data with two databases: One that is used to display content on the website And anonymous version that I can use for stats Or do I not need to worry about anonymizing the data before I see it? Does this make sense? Thanks! -
inline formset only save the last form
i tried many ways and searched alot(googled) but no one worked for me . whenever i save my inlineformset it only save the last form , my models.py class Book(models.Model): book = models.CharField(max_length=20,unique=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) class Author(models.Model): author = models.CharField(max_length=30,unique=True) count = models.IntegerField() this is my forms.py class AuthorForm(ModelForm): class Meta: model = Author fields = ['author','count'] class BookForm(ModelForm): class Meta: model = Book fields = ['book'] inlineformset_author = inlineformset_factory(Author,Book,form=AuthorForm,extra=1) this is my template class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Author form_class = AuthorForm def get_context_data(self,*args,**kwargs): context = super(CreateBookView,self).get_context_data(*args,**kwargs) if self.request.POST: context['book'] = inlineformset_author(self.request.POST) context['book'] = inlineformset_author() return context def form_valid(self,form): context = self.get_context_data() context = context['book'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateBookView,self).form_valid(form) and this is my template <form method="POST">{% csrf_token %} {{book.management_form}} {{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}} <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> <div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"> <h5 class="modal-title" id="my-modal-title">BOOK</h5> <p class="close" data-dismiss="modal" aria-label="Close"> <div class="modal-body"> <button type="submit" class="btn btn-success">save</button></dic> </div> <div class='modal-footer'></form> <script> $(document).ready(function(){ $('#BOOKBTN').on('click',function () { let allValue=[]; let numberOfInput=$('#count').val(); let allContent=''; let justforName=0; let numOfContent=$('.modal-body input').length; for(let j=0;j<numOfContent;j++){ justforName=j+1; allValue.push($('input[name="BOOK'+justforName+'"').val()); } if(numOfContent!=numberOfInput){ … -
Load excel file to selected table name
Learning django and this might be a very basic question.. please excuse.. I have created a dropdown in my django app linked to a database model column that has list of table names in my database. I want to allow the user to select the table name in the drop down and then browse to an xlsx file and load the data to the table. Need your expert advise on the below.. Is it possible to create a view that can load excel data dynamically to the model based on table name selecred? Is it possible to validate the colmn names first before performing data load to avoid issues? Is it possible to perform truncate and load vs append data by allowing the user to choose the action. Thank you very much for your guidance and also appreciate if you can put me in the right direction with some samples, examples or documentation. Thank you. -
how to implement ajax into my django project
I currently have a takeout website that does everything I need it to do. However, whenever I add an item or change its quantitiy it refreshes the page causing the user to scroll back to wherever they were before if they wanted to add more items. I realize that this project requires an AJAX implementation to update the cart without refreshing the entire page. I've been trying my best to piece together everything I needed to get it running but im lacking the general direction of how to change my django code into something ajax could use. A snippet of my views.py where it handles adding a new item to the cart if latest_order.filter(order_name=menu_name): order_instance = latest_order.get(order_name=menu_name) order_instance.order_quantity = F('order_quantity') + 1 order_instance.order_individual_price = F('order_default_price') * order_instance.order_quantity order_instance.save() return redirect('shop-ordering') A snippet of my html that shows the menu and a "add to cart" button {% for menu_items in menu %} <tbody> <tr> {% if menu_items.Menu_name == 'KOREAN COFFEE' or menu_items.Menu_name == 'CITRON TEA' or menu_items.Menu_name == 'GINSENG TEA' or menu_items.Menu_name == 'PLUM TEA'%} <!--========================== HOT DRINKS ============================--> {% if menu_items.Menu_name == 'KOREAN COFFEE' %} <thead> <tr> <th></th> <th> <h1 class='one-line'>HOT DRINKS</h1> </th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> {% …