Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error on execute import django in python3 shell and script
when i want do an import django i get an error ubuntu 18.04 with a reverse proxy (nginx) and uwsgi (mode emperor actived) in virtual env with python 3.6.3 and latest django 2.2.5 test.py : import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") import django print("test") when i run python3 test.py i get : (venv) :~/testproject/testproject/testproject$ python3.6 test.py Traceback (most recent call last): File "test.py", line 3, in from django.http import HttpResponse File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/init.py", line 1, in from django.utils.version import get_version File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/utils/version.py", line 4, in import subprocess File "/usr/lib/python3.6/subprocess.py", line 140, in import threading File "/usr/lib/python3.6/threading.py", line 7, in from traceback import format_exc as _format_exc File "/usr/lib/python3.6/traceback.py", line 5, in import linecache File "/home/lukas/testproject/venv/lib/python3.6/linecache.py", line 11, in import tokenize File "/home/lukas/testproject/venv/lib/python3.6/tokenize.py", line 35, in from token import * File "/home/lukas/testproject/testproject/testproject/token.py", line 1, in from django.contrib.auth.tokens import PasswordResetTokenGenerator File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/contrib/auth/init.py", line 4, in from django.apps import apps as django_apps File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/apps/init.py", line 2, in from .registry import apps File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/apps/registry.py", line 426, in apps = Apps(installed_apps=None) File "/home/lukas/testproject/venv/lib/python3.6/site-packages/django/apps/registry.py", line 46, in init self.ready_event = threading.Event() AttributeError: module 'threading' has no attribute 'Event' i have the same error on python3 shell when i do "import django" whereas django have been installed with pip3 install and … -
Django Custom Validation
I am new bie in Django, I used MultiModelForm in my application and change selectbox field as textbox. When I try to save form, I am getting validation error (Select a valid choice. That choice is not one of the available choices.) because validation requires equipment_id instead of equipment_tagname. Please help me to find the way Models.py from django.db import models from core.models import MyUser from django.db.models import Max from datetime import datetime class System(models.Model): system_tagname = models.CharField(max_length=20, blank=False, verbose_name="Etiket", unique=True) system_content = models.CharField(max_length=50, blank=False, verbose_name="Açıklama", unique=True) def __str__(self): return "%s %s" % (self.system_tagname, self.system_content) class SubSystem(models.Model): system = models.ForeignKey(System, on_delete=models.CASCADE, verbose_name="Ana Sistem", related_name="systems") subsystem_tagname = models.CharField(max_length=20, blank=False, verbose_name="Etiket", unique=True) subsystem_content = models.CharField(max_length=50, blank=False, verbose_name="Açıklama", unique=True) def __str__(self): return "%s %s" % (self.subsystem_tagname, self.subsystem_content) class Equipment(models.Model): subsystem = models.ForeignKey(SubSystem, on_delete=models.CASCADE, verbose_name="Alt Sistem", related_name="equipments") equipment_tagname = models.CharField(max_length=20, blank=False, verbose_name="Etiket", unique=True) equipment_content = models.CharField(max_length=50, blank=False, verbose_name="Açıklama", unique=True) def __str__(self): return "%s" % (self.equipment_tagname) class WorkStatus(models.Model): status_name = models.CharField(max_length=20) class WorkRequest(models.Model): work = models.CharField(max_length=200, blank=False, verbose_name="Açıklama") equipment = models.ForeignKey(Equipment, on_delete=models.SET_NULL, null=True, verbose_name="Ekipman", blank=False, related_name="equipment", ) reported_user = models.ForeignKey(MyUser, on_delete=models.SET_NULL, null=True, verbose_name="Raporlayan", related_name="reported_users", blank=True) created_date = models.DateTimeField(auto_now_add=True, verbose_name="Açılma Tarihi") modified_date = models.DateTimeField(auto_now=True, verbose_name="Son Güncelleme") closing_comment = models.CharField(max_length=300, verbose_name="Kapanış Yorumu", blank=True) status=models.ForeignKey(WorkStatus,on_delete=models.SET_NULL,null=True, blank=True, verbose_name="İşin Durumu",related_name="status") … -
How do I add an image file from windows to a WSL django project directory?
I have a jpeg image on windows and I would like to use it in my Django project. I am using WSL Ubuntu and when I drop the image into my project directory it does not work. I'm having the same issue with a pdf file I'm trying to drop into the directory. If anyone can help that would be great. Thanks, T -
Django running long sql process in background
I have a web page where I need to run a long sql process (up to 20 mins or so) when the user clicks on a certain button. The script runs, but the user is then unable to continue browsing the rest of the website. I would like to have it so that when the button is clicked, it goes into a queue that runs in the background. I have looked inth django-background-tasks, but the problem is that it does not seem to be possible to start the queued tasks without running python manage.py process_tasks. I have heard of Celery, but I am using a Windows system and it does not seem to be suitable. I am new to django and website infrastructures, and am not sure if this is feasible. I have also seen in older response that the threading package can work to do this, but I am unsure if it is outdated. -
How to Configure django_plotly_dash to serve assets from custom url
I have an hybrid app with most pages being on vuejs but some legacy code pages are still being served through dash-django app. previously it was wholly a dash app. on the production environment this is being served through an nginx with dedicated static directory and a reverse proxy. The app is being served on a subdomain. So the url looks like : abd.com/subdom/route_to_app_endpoints where abd.com is set to serve nginx files from base directory and abd.com/subdom is reverse proxy to serve files from port 8000 on which the django application is running. The problem I'm facing is when the app loads the base url i tries to load the components and the layout from is hitting the root directory : eg for abd.com/.django_plotly_dash/app/FileUpload/_dash-layout and it gives 404 not found. This is what it tries by default . whereas if i request abd.com/subdom/django_plotly_dash/app/FileUpload/_dash-layout my browser gives a nice output .. I tried setting : PLOTLY_DASH = { "requests_pathname_prefix" :"/subdom/" } in the settings.py but still it is unable to route properly. -
Django and the moment of instance creation
I was a bit surprised by this bit of code: class DeliveryItem(models.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._original_product = self.product ... def save(): print(self.product) print(self._original_product) super().save(*args, **kwargs) The purpose of this code was to see, whenever a change to the related product was made. The output is as follows: On creation of a DeliveryItem instance with the name "unicorn" --> unicorn --> unicorn On update of a DeliveryItem instance with the name "unicorn" to "voldemort"* --> unicorn --> voldemort This confused me ... the expected behaviour would be: On creation of a DeliveryItem instance with the name "unicorn" --> None(!) --> unicorn On update of a DeliveryItem instance with the name "unicorn" to "voldemort"* --> unicorn --> voldemort Why is the instance created before the save() method is executed? -
Django Template - Bootstrap table numbers in accounting format
I am using Django templates for populating following bootstrap table in UI. I want numbers in the table to be more readable (by using ',' between digits) - for example: if a number is one million, then it should be shown as 1,000,000 and not 1000000 (notice commas ',' between digits). Code <tr id="port_row_{{row.stock}}_{{index}}"> {% if row.stock == 'TOTAL'%} <td> {{row.stock}}</td> {% else %} <td> <a target="_blank" style="color:blue;" href="https://www.google.com/finance?q=NSE:{{ row.stock }}">{{row.stock}}</a></td> {% endif %} <td>{{row.name}}</td> <td>{{row.monday_open_price}}</td> <td>{{row.previous_close}}</td> <td> {% if row.price >= row.previous_close %} <div style="color:green"> {{row.price}} </div> {% else %} <div style="color:red"> {{row.price}} </div> {% endif %} </td> <td>{{row.investment_amount}}</td> <td> {% if row.weekly_gain >= 0 %} <div style="color:green"> +{{row.weekly_gain}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.weekly_gain}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> <td> {% if row.daily_gain >= 0 %} <div style="color:green"> +{{row.daily_gain}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.daily_gain}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> </tr> -
Django yarn collected files 404 error on server
I used yarn to collect several libraries used in my Django project and yarn put them in the node-modules folder. Before pushing to the server, I used python manage.py collectstatic command to collect all my custom css, js and these libraries into the public folder which works fine locally on my computer. but when I try to open my project on the server it gives my 404 error on every file collected using yarn. Console errors screenshot These files are not loaded but I see them with the correct path in my public folder The last two errors were due to jquery not loaded my base.html includes these: {% block stylesheets %} <!-- BootStrap CSS --> <link rel="stylesheet" type="text/css" href="{% static "bootstrap/dist/css/bootstrap.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "@fortawesome/fontawesome-free/css/all.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "academicons/css/academicons.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "fullpage.js/dist/fullpage.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "resume/css/global.css" %}"> {% endblock %} and in my public folder: public folder my settings.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'public') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "node_modules"), os.path.join(BASE_DIR, "media"), ] What I have tried so far: delete the STATIC_ROOT setting, didn't work. Change permission on public folder with chmod … -
Can't submit a post request using Django rest framework ("detail": "CSRF Failed: CSRF token missing or incorrect.")
I am into a weird situation I am login into site and when try to send a post request I didnt get user. its anonymous user instead. And if I use permission_classes = [AllowAny] or isAuthenticate classes I get error CSRF Failed: CSRF token missing or incorrect . And if I use like this in class serializer_class = ReviewSerializer authentication_classes = (BasicAuthentication,) It gives a popup to enter password and user name . My full class is like class AddReview(APIView): serializer_class = ReviewSerializer authentication_classes = (BasicAuthentication,) def post(self, request): rest = request.POST.get('restaurant') dish = request.POST.get('dish') And my settings.py is REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', # 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', # django-oauth-toolkit >= 1.0.0 # 'rest_framework_social_oauth2.authentication.SocialAuthentication', ), } I just want to submit a post custom form to submit data. Any help or suggestion to make question good would be highly appericiated. -
How do I structure my view for sending an api get request in Django?
I am sending a get request in my view and then using the response to fill my database and I need some confirmation on the following: should i make an api call inside of a view? what should that view response be? if i have done it wrong then what would be the right way to send get requests in Django? my_app/views.py class api(APIView): template_name = 'payment/api.html' def get(self, request): #I SEND THE GET REQUEST HERE config = configparser.ConfigParser() config.read('config.ini') r = requests.get(config['DEFAULT']['api']) response = r.json() #HERE I FILTER THE RESPONSE AND PUT IN A DB for item in response: if 'Covered Recipient Physician' in item.values(): person, _ = models.Person.objects.get_or_create( profile_id = int(item['physician_profile_id']), first_name = item['physician_first_name'].lower(), last_name = item['physician_last_name'].lower() ) address, _ = models.Address.objects.get_or_create( business_street = item['recipient_primary_business_street_address_line1'].lower(), city = item['recipient_city'].lower(), state = item['recipient_state'].lower(), country = item['recipient_country'].lower() ) business, _ = models.Business.objects.get_or_create( business = item['submitting_applicable_manufacturer_or_applicable_gpo_name'].lower(), ) business_address_link = models.Business_address_link.objects.create( business = business, address = address ) business_address_link.save() payment = models.Payment.objects.create( record_id = int(item['record_id']), amount = float(item['total_amount_of_payment_usdollars']), date = item['date_of_payment'], number_of_payments = int(item['number_of_payments_included_in_total_amount']), payment_form = item['form_of_payment_or_transfer_of_value'], nature_of_payment = item['nature_of_payment_or_transfer_of_value'] ) payment.save() person_payment_information = models.Person_payment_information.objects.create( person = person, business_address_link = business_address_link, payment = payment ) person_payment_information.save() -
GeoDjango options on bootstrapform multipolygon creation map?
I'm trying to display a form to create a multipolyon field htroug a webpage, I'm trying boostrapforms, but a black window is displayed on the geometry field, how can I state options for the map to be displayed? html {% extends 'base-dom.html' %} {% load bootstrap %} {% block content %} <head> {{ form.media }} </head> {% if error %} <br/> {{ error }} <br/> {% endif %} <br/> <h3>registry</h3> <br/> <div class="col-md-7"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class='form-group'> {{ form|bootstrap }} </fieldset> <input type="submit" class="btn btn-primary" value="Registrar"> </form> </div> {% endblock %} thanks -
Django: OneToOneField relation on UUID with auto creation
I am aware of similar questions such as this or this but I could not get to work none of the answers. I have two models in one models.py file: class Vehicle(models.Model): token = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) class Model(models.Model) token = models.OneToOneField(Users, on_delete=models.CASCADE, primary_key=True) color = models.CharField(max_length=10, blank=True) I want to upon adding a new Vehicle in django admin panel, a new record of Model also gets created and automatically bind the two on the same token which is in newly created Vehicle. I know that I should set the default value of OneToOneField in Model class but I do not know how to get the token of newly created Vehicle. -
Django: Accessing request.user in models.py
I'm trying to access the current user in models.py to make limit_choices_to equal to it I want the user to make transactions and I want him/her to choose from one of his/her salesmans class Salesman(models.Model): dealing_with = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'salesmans') name = models.CharField(max_length = 24) email = models.EmailField() phone_number = models.CharField(max_length = 16) class StockHistory(models.Model): stock = models.ForeignKey(Stock, on_delete = models.CASCADE, related_name = 'history') transaction_type = models.CharField(max_length = 4) item = models.CharField(max_length = 64) count = models.PositiveIntegerField() price = models.DecimalField(max_digits = 16, decimal_places = 4) salesman = models.ForeignKey(Salesman, on_delete = models.SET_NULL, null = True, related_name = 'transaction', limit_choices_to = {'dealing_with': user}) dt = models.DateTimeField(auto_now_add = True) However if I ignore that the user will able to choose any salesman even if he/she didn't create before -
Django Model designing in OneToOneField and ManyToManyField
I am writing a Django app movie Seat Booking, I am going through trouble designing a simple model. at first here you go for my current models: from django.db import models from django.contrib.auth import get_user_model class Seats(models.Model): seat_choice = ( ('AA', 'AA'), ('AB', 'AB'), ('BA', 'BA'), ('BB', 'BB'), ('CA', 'CA'), ('CB', 'CB') ) name = models.CharField(choices=seat_choice, max_length=2) def __str__(self): return self.name class Booking(models.Model): hall = models.OneToOneField(Seats) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) I want a user can buy/book one or more than one seats but the same user or other user cant buy a seat that already booked by someone or himself But the problem is, my current models, not working like what I want... Currently, it is working like if a user buys any ticket, the same user cant buys the ticket that bought by himself already! but the problem is, now another user can buy the ticket that already booked by someone and I don't want this at all. I want if a seat booked already by anyone, no one can book it again later but it can be unbooked by the user who booked! Can anyone please help me to achieve this? -
How to load an Image in a modal on a button click?
I'm using cropper.js to get the cropping coordinates but I want the users to be able to crop existing images not images they upload I already made the view and the url which takes the pk of the image but my problem is how to preview the images in the modal. I used this code to load the uploaded images in the modal /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#button{{image.pk}}").change(function () { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#image").attr("src", e.target.result); $("#modalCrop{{image.pk}}").modal("show"); } reader.readAsDataURL(this.files[0]); } }); I don't have a very good knowledge with js this is why i can't really figure it out. Thanks for the help I really appreciate it. -
Python not resolving host (timed out) when running with Gunicorn inside a Docker container (weasyprint needs to do that)
I have a Django app running in a docker container, which serves the app using Gunicorn. This app uses Weasyprint to generate a PDF, which loads a CSS dynamically. This CSS is served by the app, and it works fine (and loads instantly): host_pointing_to_that_same_machine.com/dynamic_css_path.css (it's NOT a static file, it's actually a path defined in the django URLs that outputs CSS) That's the weasyprint code: css = weasyprint.CSS(url=request.build_absolute_uri(reverse('dynamic_css_path'))) response = HttpResponse(pdf.write_pdf(stylesheets=[css]), content_type='application/pdf') This creates that URL correctly, and everything works good if instead of gunicorn I use the django built-in server (python manage.py runserver), both in my development machine and at the remote server inside the docker and so. But when I serve the app via gunicorn: gunicorn project.wsgi:application --bind 0.0.0.0:8000 Then python is unable to resolve the host name, which I proved by doing: 1) Entering the docker's app console and trying it: docker exec -it container_name /bin/ash # ping host_pointing_to_that_same_machine.com # ping any_other_host_pointing_an_external_machine.com Everything is fine. 2) Entering Django's console inside the docker container: # python manage.py shell >>> import urllib >>> r = urllib.request.urlopen(url='http://host_pointing_to_that_same_machine.com', timeout=10) >>> print('status: '+str(r.status)) Returns 200; everything OK. 3) Entering python's shell inside the docker container: # python >>> from urllib import request … -
Sending data from React form to Django Rest Framework
I am trying to send some data from my React frontend to my Django REST backend. The React data are the fields of a form. When the user click the button "next", I want this data to be sent to the back. My React functions handleSubmit(event){ event.preventDefault() fetch("/myapi/getreactinfotwitter",{ method:"POST", headers:{ 'Accept':'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ 'data_options': { 'partnerName': this.state.firmName, 'timeframes': this.state.timeframes, 'numberOfResults': this.state.numberOfResults, } }) }) I am not sure how I can "GET" this data using Django Rest Framework. I created a path in urls.py: path('getreactinfotwitter/', SendInfoFromReactTwitter.as_view(), name="getreactinfotwitter") Now I have to modify my views.py and serializers.py such that the data of the form are "grabbed" and I can manipulate them in the back. However, I am struggling to understand how I can do so. -
What should database store if blank=True in Django?
What should database store if i give no input to input form and blank=True i.e., models.CharField(max_length=20, blank=True) in Django ? hobby = models.CharField(max_length=20, blank=True) -
Edit update all schedules except primary key in Django Rest Framework
I wanna change all fields of a json object except 'pk' in DRF. I just need to keep one json data. When adding a new data ,this one should override existing data. Is there a way to do it with django ? my models.py class ClientUser2(models.Model): phone_number = models.CharField(max_length=20,unique=True) name = models.CharField(max_length=100,blank=True) status = models.IntegerField(default=1) class ClientNameSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ClientUser2 fields = ('url','phone_number','name','status','pk') my views.py class ClientViewSet(viewsets.ModelViewSet): """ API endpoint that allows messages to be viewed or edited. """ queryset = ClientUser2.objects.all() serializer_class = ClientNameSerializer and it's my api root api_root -
How to link a css file in python
I'm sending a message with HTML via Python. Now, I'd like to style it, I've tried to write the style code into the html but there are problems because curling braces {}. Can I link the css file in Python? ''' html = f''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Lato:400,900i&display=swap" rel="stylesheet"> <link rel='stylesheet' href="css/message_style.css"> #I've a static folder </head> <body> ''' -
I got ImportError and cannot import name Httpresponse from django
I am trying to build a website and I got this error: ImportError: cannot import name 'Httpresponse' from 'django.http' (C:\Users\vivek\Envs\asvc\lib\site-packages\django\http\__init__.py) I even tried from django.http -
Django Unit Testing 'else' statement in a View to achieve coverage
I'm running django test coverage for my interface app. The view below calls a WelcomeMessage model and basically says if there are no messages in that queryset it defaults to the "Welcome.." and if there are more than 1 "active" it will show the most recent one. Basically, how do I test the else line, when there there are more than 1 active messages? I've tried creating two different instances of WelcomeMessage with one being more recent, but when I run coverage it still highlights the else segment as red. Running coverage with: coverage run --source='.' manage.py test interface view: def index(request): msg = WelcomeMessage.objects.filter(active=True).order_by('-modified_at') if len(msg) == 0: msg = "Welcome message" else: msg = msg[0] # -- Need test coverage here -- context = {'msg': msg} return render(request, 'interface/index.html', context) unittest: def test_indexWelcomeMessage(self): welcome1 = WelcomeMessage.objects.create( created_at=datetime(2019, 1, 1), modified_at=datetime(2019, 1, 1), active=True, msg="Welcome message" ) welcome2 = WelcomeMessage.objects.create( created_at=datetime.now(), modified_at=datetime.now(), active=True, msg="Recent welcome message" ) messages = WelcomeMessage.objects.filter( active=True).order_by('-modified_at') if len(messages) == 0: msg = "testing this message" else: msg = messages[0] recentMsgVal = getattr(welcome2, 'msg') msg = messages[0] expectedMsgVal = messages.values_list('msg', flat=True).first() self.assertNotEqual(len(messages), 0) self.assertEqual(recentMsgVal, expectedMsgVal) # These asserts pass, but no coverage. WelcomeMessage model: class … -
MultiValueDictKeyError at / 'start_date'
Actually when i want to change calender date in django template it must run first code and if i dont it run else par but i am getting multivalue error def homepage(request): if request.method == 'GET': start_date = request.GET['start_date'] end_date = request.GET['end_date'] start = parser.parse(start_date) end = parser.parse(end_date) _start = json.dumps({"year":start.year, "month":start.month, "day":start.day}) _end = json.dumps({"year":end.year, "month":end.month, "day":end.day}) url="https://backend.makerobos.com/admin_apis/?key=g223p25HE23fdg2hHJBhU545HuhI&start={}&end={}".format(_start, _end) response=requests.get(url).json() return render(request,'robosapiapp/robos.html',{'data':response}) else: url="https://backend.makerobos.com/admin_apis/?key=g223p25HE23fdg2hHJBhU545HuhI&start={%22year%22:2019,%22month%22:2,%22day%22:11}&end={%22year%22:2019,%22month%22:3,%22day%22:1}" response=requests.get(url).json() return render(request,'robosapiapp/robos.html',{'data':response}) and this is my form page <form method="GET"> <label>From:<input id="start_date" type="date" name="start_date"></label> &nbsp; <label>To:<input id="end_date" type="date" name="end_date"></label> &nbsp; <input type="submit" name="search" id="search" value="Submit"> </form> -
Disablling cache in Django 1.8
I am having a weird bug that seems related to Djangos caching. I have a 3-step registration process: insert personal data insert company data summary view and submit all data for registration If person A walks through the process to the summary part but does not submit the form and person B does the same, person B gets the data of person A in the summary view. The data gets stored in a Storage object which carries the data through each step. Every new registration instanciates a new Storage object (at least it should). While debugging I've found that Django does not call any method in the corresponding views when the cache is already warmed up (by another running registration) and I guess that's why there is no new Storage instance. Hence the cross-polution of data. Now I'm perfectly aware that I can decorate the method with @never_cache() (which it already was) but that doesn't do the trick. I've also found that the @never_cache decorator does not work properly prior to Django 1.9(?) as it misses some headers. One solution that I've found was to set these headers myself with @cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True). But that also doesn't work. So … -
Django 2.2: Creating models for multiple databases
I am new to Django 2.2 and I am building a small project that includes 2 databases not managed by Django. One is new and the other is legacy. I added them to the database list DATABASES = { 'default': { 'ENGINE' :'django.db.backends.mysql', 'NAME': 'petshows', 'USER':'somecoolusername', 'PASSWORD': 'somesecurepassword', 'HOST': 'localhost', 'PORT':'3306' }, 'pets': { 'ENGINE' :'django.db.backends.mysql', 'NAME': 'pets', 'USER':'mysecureusers', 'PASSWORD': 'somecoolpassword', 'HOST': 'localhost', 'PORT':'3306' } } I created models for petshows which seem to work fine. But I need to add some models so I can read foreign keys from the second database 'pets'. My models.py class ShowPets(models.Model): sp_id = models.IntegerField(primary_key=True) pet_id = models.IntegerField(blank=True, null=True) show_id = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'show_pets' class Shows(models.Model): show_id = models.AutoField(primary_key=True) show_name = models.CharField(max_length=145, blank=True, null=True) show_date = models.DateField(blank=True, null=True) location_id = models.IntegerField(blank=True, null=True) org_id = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) def show_date_pretty(self): return self.show_date.strftime('%b %e %Y') class Meta: managed = False db_table = 'shows' I would like to create a model for Pets, pets table in the pets database, but I cannot figure out from the documentation how to be able to access the second …