Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access unique field names
I want to access the field names when declared in Meta class : class Book(models.Model): name = CharField(...) author = CharField(...) class Meta: constraints = [ UniqueConstraint( # fields=['name', 'author'], # solution 1 Lower("name"), Lower("author"), # solution 2 name="unique__book_author", ), ] With solution 1, I access with Book._meta.constraints[0].fields => ('name', 'author'). With solution 2, Book._meta.constraints[0].fields is empty :'( Any idea ? See https://docs.djangoproject.com/en/4.1/ref/models/constraints/ -
How to pass object id to django view when handling multiple different models objects in the same view
I am trying to make web app which has dashboard on main page where user can add saved links, notes reminders and etc. I figured out how to use several forms in same view to create different model objects, but I'm not able to update those objects. What I am specificaly trying to do is to have one button form and when user click on that button (checkbox) reminder object status changes to closed. But I can't find a way to get that object ID or anything to query it in my view. I am very new to Django framework it might be something obvious, but I coudn't find any information that would help me and I tried a lot of variations to achieve this, but nothing worked so far. #models.py class Reminders(models.Model): person_id = models.ForeignKey(Person, related_name="reminder_about", null=True, blank=True, on_delete=models.CASCADE) date = models.DateTimeField(null=True) status = models.CharField(max_length=150, null=True, blank=True) note = models.CharField(max_length=150, null=True, blank=True) user_id = models.ForeignKey(Person, related_name="reminder_for", null=True, blank=True, on_delete=models.CASCADE) class Meta: verbose_name = 'Reminder' verbose_name_plural = 'Reminders' def __str__(self): return f"{self.status} {self.note}" #views.py @login_required def index(request): current_user = request.user person = Person.objects.get(user=current_user) scheduled_calls = ScheduledCalls.objects.filter(user_id=person.id).order_by("-date") reminders = Reminders.objects.filter(user_id=person.id).order_by("-date") notes = Notes.objects.filter(user_id=person.id).order_by("-date") links = SavedLinks.objects.filter(user_id = person.id) if request.method == … -
Devappserver: Attempted RPC call without active security ticket
We're in the migration process from webapp2 to the latest version of Django. We want to keep using legacy services like Appengine NDB for now before we move to the latest technologies. For running the development environment locally I am using devappserver inside a docker environment because devappserver doesn't work with python3 according to Google. My Google Cloud SDK version is: 424.0.0 The server runs, but I keep getting this error whenever I try to access a View that uses some sort of legacy service: google.appengine.runtime.apiproxy_errors.RPCFailedError: Attempted RPC call without active security ticket Complete log: The app.yaml (for deployment looks like this): runtime: python38 instance_class: F2 app_engine_apis: 'True' entrypoint: bash -c 'python3 manage.py migrate --settings=conf.settings.dev --noinput && gunicorn -b :$PORT main:app' handlers: - url: /static static_dir: static/ - url: /.* script: auto secure: always redirect_http_response_code: 301 builtins: - deferred: on env_variables: DEBUG: 'False' DB_HOST: '/cloudsql/arrivy-sandbox:us-central1:arrivy-db' DB_PORT: 5432 DB_NAME: arrivy DB_USER: postgres DB_PASSWORD: FcnJLx3tjfQM4RZVqvC9BSAUerTpsbz2aKwN8kPHdGWY7uhmDX DJANGO_SETTINGS_MODULE: conf.settings.dev main.py: from conf.wsgi import application from google.appengine.api import wrap_wsgi_app app = wrap_wsgi_app(application, use_legacy_context_mode=True, use_deferred=False) The django app works as expected when deployed to AppEngine Standard Environment. There is no error when running services inside the docker containers locally. I have tried these approaches and failed … -
How could I get metadata from my Python-Django project to implement the SSO?
I have a Python-Django project and I'm trying to integrate with a C#/.NET existing website SAML authentication, using their idp. About I absolutely need to generate a metadata file to give to whoever manages the IdP (C#/.NET website). I've been around the Internet for days but can't find anything; I tried with all libraries (pysaml2, djangosaml2, python3-saml, django-saml2-auth, etc.) but it didn't work! How can I implement it? -
django-allatuh login automatic on "/"
I have a program in DJango. I have a second program called "users". Inside I have implemented login and login with microsoft authentication. I have done this using the "allauth" library. Now I want you when accessing the page, (without having to access the "/login" page) check if you have a microsoft account. That is, when I enter the main page: "/", it takes me to the page to choose a microsoft account in the event that it has one. Without having to press any buttons. That's possible? That it automatically connects if I am connected to a Microsoft account. This is my view: def home(request): if not request.user.is_authenticated: user = authenticate(request, auth_entry='microsoft') if user is not None: login(request, user) return redirect('main_page') else: microsoft_account = SocialAccount.objects.filter(user=request.user, provider='microsoft') if microsoft_account.exists(): return redirect('main_page') return render(request, 'home.html') As you can see, the problem is that I firt see if the user is authenticated. But if it the first time the user enters, it is imposible to be autheticated. I don't know if I explained myself correctly, I want the Microsoft authentication to be automatic -
django.db.migrations.exceptions.InconsistentMigrationHistory:
I am getting this error when trying to make migrations. Migration test_1.0001_initial is applied before its dependency test_2.0016_boolean on database 'default'. I've tried python manage.py makemigrations --merge I have also tried. python manage.py migrate --fake -
Getting this error when tried to install using pip install anymail
ERROR: Could not find a version that satisfies the requirement anymail (from versions: none) ERROR: No matching distribution found for anymail Can anyone help me with this -
Django Python view function for virtual assistant app
I have done the code for a virtual assistant using openai, speech_recognition, PyAudio. Its working fine on terminal. Now I'm trying to add the UI for it using Django. Does anyone have an example of how the view function should look like ? Thanks I want to add a UI for text option as well as speech option on it. -
In Reactjs Getting an error .map() is not a function
when i try to fetch response from api i got map is not a function error .but i declared state as array. Here's the code: function VendorListScreen(){ const [vendorsList,setVendorsList]=useState([]); const getVendors =()=>{ axios.get('http://127.0.0.1:8000/api/vendors/').then((res)=>{ setVendorsList(res.data) }) } <h1>Vendor</h1> <button onClick={getVendors}>get</button> {vendorsList.map(vendor=>{ return <p>{vendor.name}</p> })} -
nameError in django model.py
i made a class named Airport in models.py, but when i am feeding data through shell its giving me nameError: name 'Airport' is not defined from django.db import models # Create your models here. class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport, on_delete =models.CASCADE, related_name="departures") destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals") duration = models.IntegerField() def __str__(self): return f"{self.id}: {self.origin} to {self.destination}" -
How to make a reference in adminpanel to another entity that is a relationship
How to make it so that when you click on, for example, a payment number it takes you to its page. Order and payment are in Onetoonefield relationship. admin.py @admin.register(Order) class OrderAdmin(admin.ModelAdmin): ordering = ('pk',) list_display = ['pk', 'user', 'order_date', 'deadline', 'status', 'payment', 'total', 'debt', 'shipping'] list_filter = ['status', 'if_extended'] exclude = ['order_date', 'deadline', 'return_date', 'total', 'payment', 'shipping', 'if_extended', 'number_of_extensions'] search_fields = ('pk',) inlines = [ItemInline] -
Maintaining the task creation time in Django
I have a Django web application that has a superuser who can see all the tasks of other users that have been entered since the past days. When I applied this filter to the superuser, it did not display any tasks for the superuser. That filter is It used to be that the super user could only see the tasks of the current month, that is, from the first of the month until now, and if it was the first of the month, he could access the tasks of the previous month. I am editing my code like This but that is not working!!! class Task(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) posted_time = models.DateTimeField(auto_now_add=True, auto_now=False, blank=False,editable=False) def save(self, *args, **kwargs): if self.pk: kwargs['update_fields'] = [f.name for f in self._meta.fields if f.name not in ['posted_time', 'id']] -
Test Django settings with pytest
I am trying to set some environment variables that drive the configuration of a Django project in some tests so that I can mock some of the values and make assertions easier and explicit. I want to set an environment variable with the name of a file which stores some configuration which is loaded if the variable is set and the file exists. i.e: # proj.settings.py CONFIG = None if _filename := os.environ.get('FILE_PATH', None): with open(_filename) as f: CONFIG = json.load(f) I have tried a fixture that sets an environment variable (see set_env), so my tests look like this: # some_app.tests.test_settings.py import os @fixture def data_raw(): return dict( foo="bar" ) @fixture def data_file(data_raw): with NamedTemporaryFile(mode="w+") as f: json.dump(data_raw, f) yield f.name @fixture def set_env(data_file): os.environ['FILE_PATH'] = data_file def test_it_loads_data(set_env, data_raw, settings): assert settings.CONFIG == data_raw But set_env doesn't execute before Django's configuration, so CONFIG is never set. -
Django pytest APIView: How to create test for an api
I have an api endpoint which is passed client_id, and token Using the client_id and token, it gets an email_id. Using the email_id it creates a user and then creates a jwt token for the user and sends back in response The below is my view from rest_framework.views import APIView from rest_framework.response import Response from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth.hashers import make_password from django.contrib.auth.models import BaseUserManager from rest_framework import status from google.oauth2 import id_token from google.auth.transport import requests class GoogleView(APIView): def post(self, request): # (Receive CLIENT_ID and token by HTTPS POST) CLIENT_ID = request.data['client_id'] token = request.data['token'] try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) email_d = idinfo['email'] try: user = User.objects.get(email=idinfo['email']) except User.DoesNotExist: user = User() user.email = idinfo['email'] # provider random default password user.password = make_password(BaseUserManager().make_random_password()) user.save() token = RefreshToken.for_user(user) # generate token without username & password response = {} response['email'] = user.email response['access_token'] = str(token.access_token) response['refresh_token'] = str(token) return Response(response) except ValueError: response = {} response['message'] = "Not a valid google oauth tokens" return Response(response, status=status.HTTP_406_NOT_ACCEPTABLE) the urls: path('google/', views.GoogleView.as_view(), name='google'), I am asked to write test cases for this api using pytest. I am not sure what all to be tested in this case. Can someone help what … -
apache seems to be adding a trailing slash to static files so 404 but python manage.py runserver works fine
I am new to django and apache and am trying to serve a project on Debian 9 with django 1.9 over apache 2.4 server. For some reason when I try to run django project with python manage.py runserver 0.0.0.0:8000 and access it from local web browser using server ip:8000 it works fine but when I try to serve it through apache 2.4 for some reason it seems like apache is adding a trailing slash to static files paths and I get a 404 error django project path: /var/gnats django settings path: /var/gnats/gnats/settings.py DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'compressor', 'taggit', 'modelcluster', 'wagtail.wagtailcore', 'wagtail.wagtailadmin', 'wagtail.wagtaildocs', 'wagtail.wagtailsnippets', 'wagtail.wagtailusers', 'wagtail.wagtailimages', 'wagtail.wagtailembeds', 'wagtail.wagtailsearch', 'wagtail.wagtailsites', 'wagtail.wagtailredirects', 'wagtail.wagtailforms', 'djrill', 'mail_templated', 'password_reset', 'pages', 'account', 'siteconfig', 'api' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware', ) STATIC_ROOT = '/var/gnats/pages/static' STATIC_URL = '/static/' templates format <link href="/static/css/bootstrap.css" rel="stylesheet"> <link href="/static/font/stylesheet.css" rel="stylesheet" > <link href="/static/css/font-awesome.css" rel="stylesheet" > <link href="/static/css/screen.css" rel="stylesheet" > log when using python manage.py runserver 0.0.0.0:8000 (no issues) [30/Mar/2023 04:56:45] "GET / HTTP/1.1" 200 12779 [30/Mar/2023 04:56:45] "GET /static/css/bootstrap.css HTTP/1.1" 304 0 [30/Mar/2023 04:56:45] "GET /static/font/stylesheet.css HTTP/1.1" 304 … -
Why is my django-crontab cronjob not working?
I have a django-project with an app called app that has a file called cron.py with a function called my_job(). I want the my_job() function to be called every minute. In my django-project/django-project/settings.py I have this: INSTALLED_APPS = [ 'django_crontab', ... ] ... CRONJOBS = [ ('*/5 * * * *', 'app.cron.my_job') ] My django-project/app/cron.py looks like this: from .models import TestModel def my_job(): TestModel.objects.create(number=100) return True Of course I ran : python3 manage.py crontab add And the terminal printed: adding cronjob: (62dd7536ac2c985925ee33743a070a4c) -> ('*/5 * * * *', 'app.cron.my_job') To be safe I run: python3 manage.py crontab show And the terminal prints: Project/ccc_nema -> ('*/5 * * * *', 'app.cron.my_job') To check if evrything works I run: python3 manage.py crontab run someHash Traceback (most recent call last): File "/home/anik/Workplace/Office Project/ccc_nema v2/core/manage.py", line 22, in <module> main() File "/home/anik/Workplace/Office Project/ccc_nema v2/core/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django_crontab/management/commands/crontab.py", line 29, in handle Crontab().run_job(options['jobhash']) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django_crontab/crontab.py", line … -
Combining two models into one in django
Is it possible to combine two models into one in django so that I can show all details of both table in django admin panel in one table. class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=12) username = models.CharField(max_length=150, null=True) company_name = models.CharField(max_length=255, null=True, blank=True) gst_no = models.CharField(max_length=150, blank=True, null=True) class Address(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='address') street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) country = CountryField(multiple=False) state = models.CharField(max_length=100,) city = models.CharField(max_length=100) zip = models.CharField(max_length=100) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) used_in_orders = models.BooleanField(default=False) display = models.BooleanField(default=True) def gst_no(self): return self.user.gst_no if self.user.gst_no else None I know there is Inline method but I don't. want that I want to show all details of both models into one separate table -
How to remove duplicates in a django request
Remove duplicates in a Django query Image SQL duplicate. I used select_related and reduced the number of requests from 90 to 18, but if the database grows, then this will not save me. How can the query be improved? views.py def index(request): snj = ScheduleNotJob.objects.select_related() form = SNJ() return render(request,"index.html",{'snj': snj, 'form':form}) models.py class Office(models.Model): title = models.CharField(max_length=150, db_index=True) def __str__(self): return self.title class Post(models.Model): office = models.ForeignKey(Office, on_delete=models.CASCADE) title = models.CharField(max_length=150, db_index=True) def __str__(self): return self.title class Human(models.Model): office = models.ForeignKey(Office, on_delete=models.CASCADE) post = ChainedForeignKey( Post, chained_field="office", chained_model_field="office", show_all=False, ) initials = models.CharField(max_length=150, db_index=True) def __str__(self): return self.initials class Reason(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Shift(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class ScheduleNotJob(models.Model): shift = models.ForeignKey(Shift, on_delete=models.CASCADE) office = models.ForeignKey(Office, on_delete=models.CASCADE) post = GroupedForeignKey(Post, "office") human = GroupedForeignKey(Human, "post") reason = models.ForeignKey(Reason, on_delete=models.CASCADE) comment = models.CharField(max_length=300, blank=True, null=True) length_time = models.IntegerField(blank=True, null=True) date_start = models.DateField(blank=True, null=True) date_end = models.DateField(blank=True, null=True) index.html {% for elem in snj %} <tr class="mySelect"> <td>{{ elem.id }}</td> <td>{{ elem.shift }}</td> <td>{{ elem.office }}</td> <td>{{ elem.post }}</td> <td>{{ elem.human }}</td> <td>{{ elem.reason }}</td> <td>{{ elem.comment }}</td> {% endfor %} I used select_related and reduced the number of requests from 90 … -
Django password reset with mailtrap.io return error for DateTimeField classes
I am trying to create a forget_password function and I am using the following: @api_view(['POST']) def forgot_password(request): data = request.data user = get_object_or_404(User, email=data['email']) token = get_random_string(40) now = datetime.now() expire_date = now + timedelta(minutes=30) user.profile.reset_password_token = token user.profile.reset_password_expire = expire_date user.profile.save() host = get_current_host(request) link = '{host}/api/reset_password/{token}'.format(host=host, token=token) # Here is the message. body = 'Your password reset link is: {link}'.format(link=link) # Sending email send_mail( 'Password reset for DicoAPI', body, 'noreply@dicoapi.com', [data['email']] ) return Response({ 'message': 'Password reset email sent to: {email}'.format(email=data['email']) }) I use the following field in the model I have created: reset_password = models.DateTimeField(null=True, blank=True) Now when trying to use the endpoing everything works fine in the console: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' But when I try: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I got the following error with the DateTimeField RuntimeWarning: DateTimeField Profile.reset_password_expire received a naive datetime (2023-03-29 22:29:24.744400) while time zone support is active. By the way, I am using mailtrap for email testing Email testing configuration with: https://mailtrap.io/ EMAIL_HOST=config('EMAIL_HOST') EMAIL_HOST_USER=config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD=config('EMAIL_HOST_PASSWORD') EMAIL_PORT=config('EMAIL_PORT') EMAIL_USE_TLS=config('EMAIL_USE_TLS') -
How do I replace the text in an element?
Hello I'm trying to replace this h2 element with an AJAX response. I think it goes something like this? but it doesn't seem to work. <h2 class="b-0" class="d-inline categoryname">Food</h2> These are the things I've tried $(`.categoryname`).text(`${response['category_name']}`); $(`.categoryname`).replaceWith(`${response['category_name']}`); $(`.categoryname`).text().replace(`${response['category_name']}`); $(`.categoryname`).html(`${response['category_name']}`); None of em seem to work! Does anyone know what to use? -
forms.ValidationError aren't being displayed on form
i'm trying to show an error message bellow the input on my register form, although it isn't being showed. On my tests the form is considered invalid by django on the if respostas_form.is_valid(): condition, but the message that was suposed to be displayed is not apearing. ( the name of variables and funcs of the codes are in portuguese cz i'm brazilian ) html: {% for field in cadastro.visible_fields %} <div class="inputContainer"> <label class="forms__label" for="{{field.id_for_label}}" class="inputText">{{field.label}}</label> {{field}} {% for error in field.errors %} <div class="alert alert-danger"> {{error}} </div> {% endfor %} </div> {% endfor %} forms.py class CadastroForm(forms.Form): email = forms.EmailField( max_length=100, required=True, label='Email', widget=forms.TextInput({ "class": 'forms__input', "placeholder": "exemplo@gmail.com", }) ) nome_de_usuario = forms.CharField( max_length=100, required=True, label="Nome de usuário", widget=forms.TextInput({ "class": 'forms__input', "placeholder": "Ex.: Jóse Dávila", }) ) senha = forms.CharField( max_length=70, required=True, label="Senha", widget=forms.PasswordInput({ "id": "userPasswordInput", "class": 'forms__input', "placeholder": "Exemplo1234+", }) ) senha2 = forms.CharField( max_length=70, required=True, label="Confirme sua senha", widget=forms.PasswordInput({ "id": "userPasswordInput", "class": 'forms__input', "placeholder": "Exemplo1234+", }) ) def clean_senha2(self): senha = self.cleaned_data.get('senha') senha2 = self.cleaned_data.get('senha2') if senha and senha2: if senha != senha2: raise forms.ValidationError('Senhas não são iguais') else: return senha2 views.py def cadastrar(request): if request.user.is_authenticated: return redirect('inicio') cadastro_form = forms.CadastroForm() if request.method == 'POST' and request.POST: … -
Paypal order details won't show on paypal invoice for unauthenticated users
I have successfully integrated a paypal checkout for orders. When a user registers and makes and order the paypal invoice shows all details I have requested. When the use is anonymous no details are shown other than the amount paid. I hope I have given enough code for some one to help me figure this out. JS from checkout page: <script> document.cookie = "cookie_name=value; SameSite=None; Secure"; var total = '{{order.get_cart_total}}'; var order_id = '{{ order.id }}'; var order_items = []; {% for item in order.orderitem_set.all %} order_items.push({ name: '{{ item.product.title }}', quantity: '{{ item.quantity }}', unit_amount: { currency_code: 'GBP', value: '{{ item.product.price }}' }, title: '{{ item.product.title }}' }); {% endfor %} // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { color: 'blue', shape: 'rect', }, // Set up the transaction createOrder: function(data, actions) { var purchase_units = [{ amount: { value: parseFloat(total).toFixed(2), breakdown: { item_total: { currency_code: "GBP", value: parseFloat(total).toFixed(2) } } }, description: "Order ID: {{order.id}}", items: order_items }]; return actions.order.create({ purchase_units: purchase_units }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(JSON.stringify(details)); submitFormData() }); } }).render('#paypal-button-container'); </script> <script type="text/javascript"> if (user != 'AnonymousUser'){ document.getElementById('customer-info').innerHTML = '' } if (user != 'AnonymousUser'){ document.getElementById('customer-info').classList.add('hidden'); … -
How can I combine two Django views into one?
I am tring to combine two Django views into one. The goal is to be able to render a Django form and a folium map on the same page. Below is my best attempt at combining the views into a Combined view. Please let me know where I went wrong. import folium from django.shortcuts import render from django.views import View from django.views.generic import FormView from .models import StLouisCityLandTax from .forms import StLouisCityLandTaxForm class formView(FormView): form = StLouisCityLandTaxForm template_name = 'maps/partials/_form.html' def get(self, request): form = StLouisCityLandTaxForm() return render(request, 'maps/partials/_form.html', {"form": form}) def folium_map(request): properties = StLouisCityLandTax.objects.all() # create a Folium map centered on St Louis m = folium.Map(location=[38.627003, -90.199402], zoom_start=11) # add markers to the map for each station for i in properties: coordinates = (i.point_y, i.point_x) folium.Marker(coordinates).add_to(m) context = {'map': m._repr_html_()} return render(request, 'maps/partials/_map.html', context) class CombinedView(View): def get(self, request): context = { 'form': form, 'map': m._repr_html_(), } return render(request, 'maps/StLouisCityLandTaxSale.html', context) I tried the code listed above. -
Django: Fields from Parent class don't include in the child class table
I have three django models. A parent class and a two childs class. What I am missing to get the parent class fields appear in the childs class tables class Parent(models.Model): advertiser = models.CharField('Advertiser', max_length=100) insertion_order = models.ForeignKey(UserInsertionOrder, on_delete=models.CASCADE) strategy = models.CharField('Strategy Name', max_length=300) creative = models.CharField('Creative Name', max_length=400) def __str__(self): return "%s" % self.insertion_order class Meta: db_table = 'InserstionOrders' # abstract = True class Child1(Parent): dsp = models.CharField('DV360', max_length=25) class Child2(Parent): dsp = models.CharField('Xandr', max_length=25) In my pgadmin, I don't see variables comming from Parent class. I even got an error when I add abstract=True in the Parent class -
How to find which code is changing the settings of the Decimal context in a long-running process?
After scratching my head for days over a bizarre and intermittent problem in a Django app I'm responsible for, I eventually determined that the problem was that the configuration of the default Decimal context (the precision setting, in particular) is being altered without being altered back. I've worked around this, but still haven't determined where or why it's happening. It doesn't seem to be occurring in my code, so I suspect that it must be some 3rd-party package or other, and I'd like to determine which one so I can file a report with the vendor. So, what are some techniques I could use to track down the code (or at least the package, but the more granular the better) that's modifying the settings of the Decimal context, without spending a ton of time auditing source code? Python 3.8.5, Django 4.1.