Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customize key name in json output of drf serializer based on the value
At first sorry for asking question that was asked a multiple of times before ( i'm pretty sure it was ). Let's say i have this model relationship: class Balance(models.Model): class Meta: verbose_name = u"Balance" verbose_name_plural = u"Balances" name = models.CharField(max_length=200, verbose_name=u"Currency", null=True, blank=True) count = models.FloatField(verbose_name=u"Count", null=True, blank=True) account = models.ForeignKey(Account, verbose_name='Account', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Account(Page): ... And those serializers class BalanceSerializer(serializers.ModelSerializer): class Meta: model = accounts.Balance fields = ('pk', 'name', 'count') class AccountSerializer(serializers.ModelSerializer): balance_set = BalanceSerializer(many=True, required=False) class Meta: model = accounts.Account fields = (... , balance_set ) So accounts serializer returns me json output like that: { *some account information* balance_set: { pk: 1 name: foo, count: bar }, ... } But i want it to return me balance_set like this: { *some account information* balance_set: { foo: bar, balanceName:balanceCount, } } I've googled and looked up in docs but wasn't able to understand how to do it. -
Django - how to control and filter related objects
I have two models Note : there are some code i have removed to make the question simple class Categories(models.Model): category_name = models.CharField(max_length=100, null=True) class Courses(models.Model): course_name = models.CharField(max_length=200) category = models.ForeignKey(Categories, on_delete = models.CASCADE,) if i have for example 3 categories (PHP ,Python,javascript) and each one of this categories have a courses related to it like this PHP = php_course1, php_course2, php_course3 Python = python_course1, python_course2, python_course3 javascript = javascript_course1, javascript_course2, javascript_course3 so what i want when someone click on any category it will take him to another page which have only courses related to this category. so this what i have done to make this happen views.py class CategoriesListView(ListView): model = Categories template_name = 'category_list.html' context_object_name = 'category_list' class CategoriesDetailView(DetailView): model = Categories template_name = 'category_detail.html' context_object_name = 'category_detail' first template 'category_list.html' {% for category in category_list %} <a href="{% url 'category' category.slug %}" class="btn">{{ category.category_name }}</a> {% endfor %} second template 'category_detail.html' {% for course in category_detail.courses_set.all %} <h1> {{ course.course_name }} </h1> {% ednfor %} this is work very well if i click on 'javascript category' for example it will show only 'javascript courses'. The problem is i want to filter the courses but because i … -
Error while attempting to run Django-admin dbshell no module named 'myprojectname'
I have been trying for hours to get this error to go away but I am truly at a loss. When I run try to set the settings environment it fails. I dont know what im doing wrong here. I dont know what it means to not be able to find the module. The settings file is clearly there. set DJANGO_SETTINGS_MODULE=Hyper_Web_App_Directory.settings Django-admin runserver results in this error (venv) C:\Users\unblo\PycharmProjects\Hyper_Web_App_Directory>set DJANGO_SETTINGS_MODULE=Hyper_Web_App_Directory.settings (venv) C:\Users\unblo\PycharmProjects\Hyper_Web_App_Directory>Django-Admin runserver Traceback (most recent call last): File "c:\users\unblo\pycharmprojects\hyper_web_app_directory\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\unblo\pycharmprojects\hyper_web_app_directory\venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "c:\users\unblo\pycharmprojects\hyper_web_app_directory\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "c:\users\unblo\pycharmprojects\hyper_web_app_directory\venv\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\unblo\pycharmprojects\hyper_web_app_directory\venv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "c:\users\unblo\pycharmprojects\hyper_web_app_directory\venv\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "c:\users\unblo\pycharmprojects\hyper_web_app_directory\venv\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\unblo\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked … -
Manually creating a table using migration in Django, unable to add foreign keys
I want to dynamically create some tables with different names but the same structure. I don't want to use SQL statements, so I tried to manually write some migrated code, but I got some error. I am using Django 2.2.3, python 3.6.6, I tried to remove the foreign key field and successfully generated a table, but after adding the foreign key field, I got the following error. This is the code that generated the table class DynamicModel(object): """动态模型""" def get_fields(suffix): print(suffix) if suffix == "_data_stores": return Fields.BaseFields + Fields.DataStores @staticmethod def create_tables(prefix=None, app_udid=None, suffix=None, app_label="apptutti"): """ 创建表 :param prefix: 前缀 :param app_udid: 游戏ID :param suffix: 后缀 :param app_label: 应用标识 :return:None """ if not all([prefix, app_udid, suffix]): return "表名参数错误" table_name = app_udid + suffix class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name=table_name, fields=DynamicModel.get_fields(suffix) ), ] executor = MigrationExecutor(connection) migration = Migration(table_name, app_label) with connection.schema_editor(atomic=True) as schema_editor: migration.apply(executor._create_project_state(), schema_editor) I can call it like this. app_udid = '2016021021523547311' # Blocky Cars Online prefix = 'apptutti' # Blocky Cars Online suffix = '_data_stores' # Blocky Cars Online DynamicModel.create_tables(prefix=prefix, app_udid=app_udid, suffix=suffix) In case of containing a foreign key field, I get the error message. Traceback (most recent call last): … -
how to fix this prepend www at the beginning of my url creating error?
urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^attendance/$', views.home, name='homepage'), url(r'^attendance/teacherlog/$', views.teareg, name="teareg"), url(r'login/logged', views.dash, name='dashboard'), url(r'^mrkatt/$', views.mrkatt, name='mrkatt'), url(r'^attsheet/$', views.dispatt, name='dispatt'), path('', include("django.contrib.auth.urls")), ] views.py def mrkatt(request): if request.method == "POST": form = Mrkatform(request.POST) if form.is_valid(): form.save() return redirect("login/logged") else: form = Mrkatform() return render(request, "teacher/mrkatt.html", {'form': form}) i expect the url to be "127.0.0.1:8000/mrkatt/" but it gives "http://www.127.0.0.1:8000/mrkatt/" showing this site cant be reached error. -
Maintain uniqueness on django-localized-fields
I'm trying to avoid having duplicate localized items stored in a Django-rest-framework app, django-localalized-fields packapge with a PostgreSQL database I can't find any way to make this work. (https://pypi.org/project/django-localized-fields/) I've tried writing custom duplicate detection logic in the Serializer, which works for create, but for update the localized fields become null (they are required fields, so I receive a not null constraint error). It seems to be django-localized-fields utility which is causing this problem. The serializer runs correctly (create/update) when I'm not overriding create/update in the serializer by defining them separately. I've also tried adding unique options to the database in the modal, which does not work - duplicates are still created. Using the standard unique methods, or the method in the django-localized-fields documentation (uniqueness=['en', 'ro']). I've also tried the UniqueTogetherValidator in Django, which also doesn't seem to support HStore/localizedfields. I'd appreciate some help in tracking down either how to fix the update in the serializer or place a unique constraint in the database. Since django-localized-fields uses hstore in PostgreSQL it must be a common enough problem for applications using hstore to maintain uniqueness. For those who aren't familiar, Hstore stores items as key/value pairs within a database. Here's an … -
Django test returns an AnonymousUser instance instead of the new user
Important info: Django ver 2.2.2, session and auth middleware activated, Custom User model is standart AbstractUser with added custom fields, nothing else is changed in AbstractUser. I am trying to implement a Django Test for my view, there's a view definition: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, Group from django.contrib.auth import login, logout, authenticate from .models import CustomUser def listreport(request): curuser = request.user print(curuser) return render(request, 'fettwa/inmin/listreport.html') The test code is this (I think I got the intendation wrong while copypasting here): from django.test import TestCase, Client from fettwa import models, forms, views from fettwa.models import CustomUser from django.contrib import auth from django.contrib.auth.models import User, Group class Auth_Test(TestCase): def test_client(self): self.user = CustomUser.objects.create_user(username='test_client', password='pass', role=0) user = Client().login(username='test_client', password='pass') print(self.user.password) print(self.user.username) if user: print("Client-like user successfully created and login") Client().get('/listreport') All that code gives me this output (AnonymousUser in view can be seen): Creating test database for alias 'default'... System check identified no issues (0 silenced). Client-like user successfully created and login AnonymousUser <HttpResponse status_code=200, "text/html; charset=utf-8"> . ---------------------------------------------------------------------- Ran 1 test in 0.721s OK Destroying test database for alias 'default'... -
My code doesn't run it says there is a circular import error I'm try to load the home view so that it redirects me
I am working on a django project, but it returns the included urlconf "myapp.urls"does not appear to have any patterns in it. I tried checking my views to ensure I imported everything correctly from django.contrib import admin from django.urls import path from .views import home from accounts.views import login_view urlpatterns = [ path('admin/', admin.site.urls), path('',home), path('accounts/login/', login_view), ] I expect the site to run and redirect me to the login page This is my views in the same directory with the urls.py @login_required def home(request): return render(request,"home.html") -
Is there a way to return the opposite of a custom Django QuerySet
I am looking for a way to return the exact opposite of a custom Django Manager queryset. I am working on a project that has some querysets already defined and I want to get the opposite of these. For simplicity I'll use the example from the docs. Suppose I had a Book model and a DahlManager that filtered the books by author='Roald Dahl'. Inside the DahlManager, let's suppose I have another method get_childrens_books that only returns his childrens books, something like is_for_children=True. Is there a way to get the opposite of this new method without writing a fully separate filter or method? I want something like Books.dahl_objects.get_childrens_books().exclude() or Books.dahl_objects.exclude(get_childrens_books), rather than adding another method to DahlManager. The motivation here is that I can see the potential for adding a lot of code that is repetative. I don't want to be writing a not_filter for every filter that I write. -
Django form wizard - redirect to first step after done based on a condition
I am pretty new to Django. Here is my problem. I have 5 step form wizard. At the end of 5th step, I need to process the data (by calling an API). If the result of the call is True, I need to redirect the user to a page that displays the data from all steps of the wizard (summarized). If the result is False, then I need to redirect the user to a page where a message will be shown...something like "API call failed, you need to re-enter the information again" and add a button that redirects the user to the first step of the wizard HAVING ALL PREVIOUSLY ENTERED DATA in it. I can show the summarized in a page when the result is TRUE. But I don't know how to show a page that allows user to go back to the step 1 of the form with previously entered data intact. forms.py -------- class Step1Form(forms.Form): def init(self, *args, **kwargs): super().init(*args, **kwargs) questions = Question.objects.filter(object_type_id=1) self = add_form_fields(self,questions) ##This is my method where I am adding fields based on some logic class Step2Form(forms.Form): def init(self, *args, **kwargs): super().init(*args, **kwargs) questions = Question.objects.filter(object_type_id=10) self = add_form_fields(self,questions) class Step3Form(forms.Form): def … -
Unable to use static files in production on heroku deployment but it works locally using django
I'm trying to deploy an initial "skeleton" django project using: https://www.youtube.com/watch?v=TgmeAN32Uvw&list=PLEsfXFp6DpzTgDieSvwKL3CakR8XyKkBk&index=7&frags=wn Locally the static files work properly but when trying to deploy to heroku the site then fails. -
How to Display Customer Error Message in Form Django
I would like for my modelform to show customer error messages when some value is entered improperly. For example: I have a field 'reference' which is set to be unique in the model. Currently, if the user enters the same value twice for this field, I just get a full error screen that reads "The view unit.views.add_order didn't return an HttpResponse object. It returned None instead." Instead I would like for the view to simply display an error message with the form still open that reads something like "that reference ID already exists!" Can anyone point me in the direction to make this possible? Forms.py class CreateOrderForm(forms.ModelForm): class Meta: model = Orders fields = ('reference', 'ultimate_consignee', 'ship_to'...) Models.py class Orders(models.Model): reference = models.CharField(max_length=50, unique=True, error_messages={'unique':"This reference id has already been used"}) ultimate_consignee = models.ForeignKey(Customers, blank=True) ship_to = models.CharField(max_length=500, blank=True) Views.py def add_order(request): if request.method == "POST": form = CreateOrderForm(request.POST) #objectlist = Customers.objects.all() if form.is_valid(): reference_id = form.cleaned_data.get('reference') form.save() return redirect('add_manifest', reference_id=reference_id) else: form = CreateOrderForm() #form2 = CreateManifestForm() objectlist = Customers.objects.all() context = { 'form': form, #'form2': form2, 'objectlist': objectlist, } return render(request, 'add_order.html', context) As you can see in the model - I tried to add a message for … -
Django - Initial values in a master-detail modelform using inlineformset_factory
I have the following models: models.py class RegistroPago(models.Model): fechaPago = models.DateField(default=timezone.now) contrato = models.ForeignKey(Contrato, on_delete=models.CASCADE) formapago = models.ForeignKey(FormaPago, on_delete=models.CASCADE) nota = models.CharField(max_length=255, blank=True) archivo = models.FileField(upload_to='images/', blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.pk) class RegistroPagoDato(models.Model): registropago = models.ForeignKey(RegistroPago, related_name='items',on_delete=models.CASCADE) # aqui el secreto fue este related_name = 'items' categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) concepto = models.CharField(max_length=150, verbose_name="Concepto") importe = models.DecimalField(max_digits=12, decimal_places=2, default=0) def __str__(self): # return self.cliente return str(self.pk) views.py class CrearRegistroPago(CreateView): model = RegistroPago template_name = 'registropago.html' form_class = RegistroPagoForm success_url = reverse_lazy('listado_pagos') def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) detalle_orden_registro_pago_formset = DetalleRegistroPagoFormSet() return self.render_to_response(self.get_context_data(form=form, detalle_registro_pago_form_set=detalle_orden_registro_pago_formset)) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) detalle_registro_pago_form_set = DetalleRegistroPagoFormSet( request.POST) if form.is_valid() and detalle_registro_pago_form_set.is_valid(): return self.form_valid(form, detalle_registro_pago_form_set) else: return self.form_invalid(form, detalle_registro_pago_form_set) def form_valid(self, form, detalle_registro_pago_form_set): form.instance.user = self.request.user self.object = form.save() detalle_registro_pago_form_set.instance = self.object detalle_registro_pago_form_set.save() return HttpResponseRedirect(self.success_url) def form_invalid(self, form, detalle_registro_pago_form_set): return self.render_to_response(self.get_context_data(form=form, detalle_registro_pago_form_set=detalle_registro_pago_form_set)) def get_form_kwargs(self): kwargs = super(CrearRegistroPago, self).get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs and in forms.py class RegistroPagoForm(forms.ModelForm): class Meta: model = RegistroPago labels = { "contrato": "Contrato / Nombre del Inquilino:", "fechaPago": "Fecha de Pago:", "formapago": "Forma de Pago:", "nota": "Agregar Nota:", } fields = ['fechaPago', 'contrato', 'formapago', … -
How to fix "The view PIMS.views.add_item didn't return an HttpResponse object. It returned None instead."
I am making a Database Management system and I have been using ModelForm. In views.py I am getting the error saying "The view PIMS.views.add_item didn't return an HttpResponse object. It returned None instead." views.py from django.shortcuts import render, redirect from .models import * from .forms import * from django.urls import reverse # Create your views here. def display_list(request): items=Gen_info.objects.all() context = { 'items' : items } return render(request,'index.html',context) def add_item(request): if request.method == "POST": form =Gen_info_form(request.POST) if form.is_valid(): form.save() return render(request,'index.html',{}) else: form = Gen_info_form() return render(request,'add_new.html',{'form':form}) enter image description here -
How to view all devices connected to my Django app?
I'm trying to view all devices connected to my Django app, along with some identifying information to determine uniqueness. I know that I can view all Users of my Django app, but if I'm trying to do something similar without making users login to the service, is there a way to view connections by device? Thanks! -
How to add Django statements to Javascript
I'm trying to implement some JS code in django so anytime i click a button, it returns the current year.. how do i do this I've tried using some JS events handler in my django based templates from datetime import datetime from django.template import Template, Context from django.http import HttpResponse as toHTML cont = Context({'dat':datetime.now()}) def say_year(request): htm = Template("click me") htm = htm.render(cont) return toHTML(htm) i'm expecting an alert box showing full datetime.now() methods -
Django filter table by foreign keys in related manager column
I have three models in my Django application: class MainData(models.Model): # bunch of fields class Label(models.Model): label = models.CharField(max_length=512, null=True, unique=True) class MapData(models.Model): labelMatch = models.ForeignKey(Label, on_delete=models.CASCADE) mainMatch = models.ForeignKey(MainData, on_delete=models.CASCADE) Through my application, I have the user enter a label in a search box. What I would like to do is return the MainData rows whos' MapData.label_match field is the entry in Label. For example, say the user enters the string 'main32' into the search box. My current thought is to first find Label rows that match 'main32', then use the RelatedManager labelmatch_set to get all of the MapData rows that MapData.mainMatch points to. So if there are 10 MapData rows whose labelMatch points to a Label entry with label='main32', I then want to retrieve all 10 MainData rows that the foreign key mainMatch points to. Hopefully I explained that ok. I have gotten to: matching_label_rows = Label.objects.filter(input) matching_main_data_rows = matching_label_rows.mainMatch_set.???? How can I retrieve the pointed to MainData rows from matching_label_rows.mainMatch_set? And can this operation be done as a one-liner? -
Prevent Django's JsonResponse to serialize my string
I have a JSON string that I compute from a Pandas dataframe aggr.aggregated.to_json(orient='values') I cannot directly provide aggr.aggregated to a standard Python JSON serializer because it would not follow the orient='values' rules and would do so differently. I want to serve my own JSON string as a response from a Django view: return JsonResponse(aggr.aggregated.to_json(orient='values')) However, in the code above, Django tried to serialize my JSON string. How can I use JsonResponse exclusively to set the Content-Type header to application/json but not to serialize a string that is already serialized? -
Django formset dynamic cant add forms
Im having problems with a dynamic formset in django I was watching this tutorial from which I took out the base code https://medium.com/all-about-django/adding-forms-dynamically-to-a-django-formset-375f1090c2b0 But it does not work as it should, since it does not let me add more forms I think the problem is in javascript, but not knowing much about it I can not fix it Image of how its the html, when i press the "+" button, nothing ocurr. If i change "extra" of formset to 5 for example, and then press the "-" button this work of i expect. forms.py OrdenCompraModelFormset = modelformset_factory( OrdenCompraProducto, fields=[ 'tipo_producto', 'cantidad', 'fecha_entrega', 'proveedor_surgerido', ], extra=1, widgets={ 'fecha_entrega': forms.DateInput(attrs= {'class': 'form-control', 'type': 'date'}), } ) views.py def formv_ordencompra(request): form=OrdenCompraForm, extra=1) if request.method == 'GET': print('0') formset = OrdenCompraModelFormset(queryset=OrdenCompraProducto.objects.none()) elif request.method == 'POST': print('1') formset = OrdenCompraModelFormset(request.POST) if formset.is_valid(): formset_obj = formset.save(commit=False) ordencompra = OrdenCompra.objects.create() for form_obj in formset_obj: form_obj.orden = ordencompra form_obj.save() messages.success(request, f'La orden fue cargada!') return redirect('.') else: print('2') formset = OrdenCompraModelFormset() return render(request, 'webapp/formularios/ordencompra.html', {'formset': formset}) ordencompra.html {% extends 'webapp/base.html' %} {% load crispy_forms_tags %} {% load static %} {% block content_principal %} <div class="container-fluid"> <h1 class="h3 mb-2 text-gray-800">Cargar "Orden de devolucion"</h1> <p class="mb-4">Esta orden define quien trae … -
Disabling Django's automatic assignment of backwards relations of unsaved objects
I have two instances of objects saved in the database: class Object: pass class Temporary: relation = OneToOneField(Object, related_name='temporary') obj = Object.objects.create() the_only_correct_temp = Temporary.objects.create(relation=obj) Now I want to perform some calculations using additional Temporary objects, which will never be saved to the db, yet are crucial for those calculations. So I create them: temp1 = Temporary(relation=obj) temp2 = Temporary(relation=obj) Please note that I never save them. Now, after executing the code above, obj.temporary is equal to temp2, even though it has a different object assigned in the database (the_only_correct_temp), and I never explicitly assigned temp2 to it. This is happening, because Django somehow follows the relation when creating temp2, and implicitly sets the attribute on obj. I know I can "restore" the correct state by calling obj = Object.objects.get(pk=obj.pk) But this is a performance hit. I could also pass the copy of obj when creating temp1 and temp2, but copying is expensive too. So the question is: how can I prevent Django (1.11) from assigning unsaved instances of Temporary to the obj.temporary field? -
Django template dictionary lookup with another dictionary lookup value
So basically I have 1 dictionary, lets call it a. a = {1: {'hero': 'Anti-Mage', 'vert': 'http://cdn.dota2.com/apps/dota2/images/heroes/antimage_vert.jpg', 'large': 'http://cdn.dota2.com/apps/dota2/images/heroes/antimage_lg.png'}, 2: ..... , 3: .... , 96: ....} I have another dictionary b. b = {'playername': 'Mind_Control', 'hero_id': 96, 'player_slot': 4, 'kills': 6, 'deaths': 2, 'assists': 4, 'level': 11}] I want to get a the 'vert' value from dictionary a using b['hero_id'] as the lookup. Hero_id corresponds to the number keys in dictionary a. So I tried {{a.{b.hero_id}.vert} but nothing came up. Im unsure how to search through this on a django template {{a.96.vert}} This gives me what I want but this is me manually typing it and that wont work because I'm doing alot of data. so I need something like above. -
How to filter django queryset for whole numbers (DecimalField)
I have a queryset with amount (DecimalField(decimal_places=2)) fields. I want to filter the queryset to exclude any rows with amounts that are not integer (whole number) values. Example valid values: 1.00, 125.00 Example invalid values: 0.99, 14.01 Is there any function that would allow me to do something like: qs = qs.filter(amount=floor(F('amount'))) -
what are some Django librarys useful for autocomplete?
So i have a model called partner which has a name. The name has a foreign key reference to it self. So when i create a second partner i can see the list of previous names i created. Those are potential parents. I want to either filter my parents so the user only sees the parents not all the names or i want to make a autocomplete feature that helps the user type it in. class Partner(TimeStampedModel, StatusModel): INVOICE_METHOD_CHOICE = ( ("PAPER", "Paper"), ('EMAIL', 'Email'), ) LEGAL_STRUCTURE_CHOICES = ( ('CORPORATION', 'Corporation'), ('LLC', 'LLC'), ('SOLE PROPRIETOR', 'Sole Proprietor'), ('PARTNERSHIP', 'Partnership'), ) PARTNER_OFFICE_CHOICES = ( ('HEADQUARTERS', 'Headquarters'), ('DIVISION', 'Division Office'), ('SITE', 'Site'), ('DC', 'Distribution Center'), ) ADDRESS_TYPES = ( ('Billing', 'Billing'), ('Shipping', 'Shipping'), ('Physical', 'Physical'), ) STATUS = Choices('Active', 'Inactive', 'Credit Hold',) name = models.CharField(blank=True, max_length=100, verbose_name='Account Name', ) parent = models.ForeignKey( 'self', blank=True, help_text="Parent Company name (if necessary)", null=True, on_delete=models.CASCADE, max_length=200 ) What are some good librarys for autocomplete in a form field? Also is there any good tutorials on how i can implement it? i tried django autocomplete but it seems like i can only get it to work on admin and not anywhere else. -
How to include urls.py from other app without route
In django 2.2, I have the main app urls.py as follow: urlpatterns = [ path('admin/', admin.site.urls), path("logout/", auth_views.LogoutView.as_view(), name="logout"), path('', HomeView.as_view()), ] And I have a different app, called it app2, which I want route/ to be routed into a view urlpatterns = [ path('route/', RouteMy.as_view()), ] How can I call urls.py from app2 into the main urls.py, properly, without having to do app2/route (so I can have clean URLs and code) -
Python Django dropdown form and trigger python script
Newbie with Django and Python. Creating a Nav bar with dropdown list (which being populate via form.py) Once the user select the item, Another dropdown list will display. After user selected the item from the list and hit submit, Like to trigger python script to fetch data and populate in table format Stuck executing python script Following code: views.py: class StatusLayoutPageView(FormView): template_name = "status_layout.html" form_class = SelectLocationForm def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. return super().form_valid(form) class DataView(FormView): ## This will contain the output template_name = "data.html" form_class = SelectLocationForm Here is the models.py LOCATIONS = ( ('DC1', 'DC1'), ('DC2', 'DC2'), ) class SelectLocationForm(forms.Form): error_css_class = 'error' location = forms.ChoiceField(choices=LOCATIONS, required=True) class Meta: model = SelectLocation Here is the template: <form method="post">{% csrf_token %} <select name="location"> <option selected>Select Location</option> {% for val in form.location %} <option value="{{ val }}"></option> {% endfor %} </select> <p> <button align="center" class="button execute" name="submit" value="submit">GO TO</button> </form> Issue running into is how to tell which value user selected base on that load the page. Also with the button onclick, like to pass the data to python script to run thru the …