Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
graphene mutation returns 400 - won't pass id field properly
I have been using graphene in django with graphql and a React frontend. I can get a create mutation to work, but an edit one won't - even tho the query without $ variables works in graphiQL My gql const in React is: export const EDIT_PERSON = gql` mutation personEdit($id: id, $input: PersonInputType!) { personEdit(id: id, input: $input) { person { id } } } `; id is set from a handler and the submit function in the form looks like: <form autoComplete="off" onSubmit={e => { e.preventDefault(); editPerson({ variables: { id: id, input: { firstName: firstName, lastName: lastName, address: address } } }); }} > My PersonEdit mutation in django looks like: class PersonEdit(Mutation): class Arguments: id = ID(required=True) input = PersonEditInputType(required=True) person = Field(PersonType) @classmethod def mutate(cls, root, info, **data): serializer = PersonSerializer(data=data.get('input')) serializer.is_valid(raise_exception=True) person = Person.objects.get(id=data.get('id')) print("PERSON", serializer.data) person.first_name = serializer.data['first_name'] person.last_name = serializer.data['last_name'] person.address = serializer.data['address'] return PersonEdit(person=person.save()) Why will editing not work? -
What is inverse operation of Javascript's CryptoJS.enc.base64.stringify(data) in Python3/Dja?
I'm trying to encrypt in Javascript and decrypt the same data in Python/Django. Disclaimer: Not Production level code, but to learn concept I generate a key through Diffie Hellman (Ajax using jQuery), which I pass to the encrypt function below. Input is generally an ID and Password in JSON format. This is how the encryption takes place. {Found the code somewhere.} function toWordArray(str){ return CryptoJS.enc.Utf8.parse(str); } function toString(words){ return CryptoJS.enc.Utf8.stringify(words); } function toBase64String(words){ return CryptoJS.enc.Base64.stringify(words); } function encrypt(input, key){ console.log("Input: " + input); var PROTOCOL_AES256 = 2; var secret_key = CryptoJS.SHA256(key); var header = toWordArray("AMAZON" + String.fromCharCode(PROTOCOL_AES256)); var iv = CryptoJS.lib.WordArray.random(16); var body = CryptoJS.AES.encrypt(input, secret_key, {iv: iv}); // construct the packet // HEADER + IV + BODY header.concat(iv); header.concat(body.ciphertext); console.log("Bytes before Base64 encoding: " + header); //Line 1 // encode in base64 return toBase64String(header); } The output I get is as follows: final key: 47 signin:119:33 Input: {"name":"Buzz","password":"lightyear"} signin:55:25 Bytes before Base64 encoding: 414d415a4f4e02e8ec9b8a949eb754e305acfbe5207f1ebe75272c18146bca57ce399928c0ffd7e506d90e11b011da42b1bd8d2393ec59cc926cef33c2121da3f48dfd59925138 signin:67:25 Payload: QU1BWk9OAujsm4qUnrdU4wWs++Ugfx6+dScsGBRrylfOOZkowP/X5QbZDhGwEdpCsb2NI5PsWcySbO8zwhIdo/SN/VmSUTg= signin:137:37 XHRGEThttp://127.0.0.1:8000/Shenzen/actsignin/?encrypted_string=QU1BWk9OAujsm4qUnrdU4wWs%2B%2BUgfx6%2BdScsGBRrylfOOZkowP%2FX5QbZDhGwEdpCsb2NI5PsWcySbO8zwhIdo%2FSN%2FVmSUTg%3D [HTTP/1.1 500 Internal Server Error 24ms] AES failed. Now I decode it in python as follows: encrypted_string = request.GET['encrypted_string'] print("Encrypted string decoded: ",base64.b64decode(encrypted_string)) #Line 2 print("----") sha256_key = SHA256.new(data=bytes(key)) cipher = AES.new(sha256_key.digest(),AES.MODE_CBC) print(cipher.decrypt(base64.b64decode(encrypted_string))) [12/Oct/2019 18:39:41] "GET /Shenzen/dh/?step=calcval&level1=37 HTTP/1.1" 200 16 … -
can we convert models.Timefield to datetime in django
I have a models.timefield as breakfast_start_time = models.TimeField(default=time(7, 30)) I want to add one more field automatically by overriding save method whose name is breakfast_attendence_start_time and value 15 minutes less than the user input in breakfast_start_time. How can I achieve that. datetime.timedelta(minutes=15) is not working with models.Timefield and I dont want to use Datetimefield. please help me with this code. -
NoReverseMatch error when adding link to go back to category
I am making a forum site with Django and have set up categories, each with different topics that can be commented on. On the specific topic page, I am able to add {{ topic }} but when I try and add {{ category }} above that it does not show up. I am also trying to make the {{ category }} a link so they can go back to that category's main page. I have tried adding this in the topic.html but nothing shows up. <p> <a href="{% url 'speak_space:category' category.id %}">{{ category }}</a> </p> This is the error I receive when that code is included: NoReverseMatch at /topics/3/ Reverse for 'category' with arguments '('',)' not found. 1 pattern(s) tried: ['categories/(?P<category_id>[0-9]+)/$'] Here's my full topic.html page (I added a back button for a temporary fix): {% extends 'speak_space/base.html' %} {% block content %} <form> <input type="button" value="<< go back" onclick="history.back()"> </form> <p>Topic: {{ topic }}</p> <p> <a href="{% url 'speak_space:new_entry' topic.id %}">Join the convo!</a> </p> <p>Responses:</p> <ul> {% for entry in entries %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> <p> <a href="{% url 'speak_space:edit_entry' entry.id %}">Edit</a> </p> </li> {% empty %} <li>Nobody has added to this … -
Is it a Good Practice to use Hybrid mysql and MongoDb in Django Application?
I am using Django rest framework as my backend, and using Django's default user model and my custom files model to store files uploaded by specific user. Now the process is to read the uploaded excel file and store the json formatted data back in the database for later use. So I am planning to use Mysql for user and files models and MongoDB to store all the meta data which will be in json format. Please guide if this a correct way to handle this or not. Also would like to know if there is any other best possible way for the same. Thanks !! -
how to properly redirect from one app to another app in django
i am a beginner to Django and i am unable to properly handle redirects from one app to another. I have 2 apps Accounts, Dashboard. Accounts Handles login and registration of AuthUser. Dashboard handles other functionality like Fileupload So far, I have successfully using reverse() method have redirected from /accounts/login to my upload page but it redirects from /accounts/login to /accounts/upload instead of /dashboard/upload . Project URLS urlpatterns = [ path('dashboard/', include('Dashboard.urls')), path('accounts/', include('Accounts.urls')), path('admin/', admin.site.urls), ] Account urls.py urlpatterns = [ url('upload',DashboardViews.upload, name='upload'), path('login', views.login, name='Login'), path('register', views.register, name='Register'), path('logout', views.logout, name='logout') ] Account views.py def login(request): if request.method == 'GET': return render(request, 'login.html') if request.method == 'POST': user_name = request.POST.get("username") password = request.POST.get("password") user = auth.authenticate(username=user_name,password=password) if user is not None: auth.login(request,user) return redirect(reverse('upload')) else: print('Failed') return render(request,'login') My intention is whenever user (login/register), web page should redirect from /account/login to /dashboard/upload. -
Unexpexted MultiValueDictKeyError in signup code
I am new to Django. I am creating a signup page. But I am having an unexpected MultiValueDictKeyError with Exception value fname. I am not able to get it. Kindly help me to solve it -
Seo Analysis Tool for Django
is there any SEO Analysis tool (like Yoast SEO plugin for Wordpress) for Django? -
Unable to create a superuser after deploying to heroku(KeyError: 'createsuperuser')
I was able to deploy to Heroku but I am unable to create superuser. Command I want to run: heroku run python manage.py createsuper Error I am getting: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'createsuper' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 211, in fetch_command settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mysite.settings' -
Django-Storages ('`data` must be bytes, received', <class 'str'>) when saving a model field
I read through the django-storages docs which suggest using the following to save files to cloud storage (GCS in my case): >>> obj2 = Resume() >>> obj2.pdf.save('django_test.txt', ContentFile('more content')) >>> obj2.pdf <FieldFile: tests/django_test_.txt> >>> obj2.pdf.size However, following the same logic, I'm struggling to save a Pandas DataFrame as a CSV using FileField object: My code: df = load_some_df() print(df.head()) # prints contents of df contents = ContentFile(df.to_csv(index=False, header=True)) output_file_name = 'df.csv' instance = MyModel() instance.output_file.save(output_file_name, contents) The above gives me the error: ('`data` must be bytes, received', <class 'str'>) -
Django - converting datetime.date tuples
I'm trying to get some dates from my model. In my queryset I get: datetime.date(2019, 10, 15), datetime.date(2019, 10, 18), datetime.date(2019, 10, 2), datetime.date(2019, 9, 18), datetime.date(2019, 10, 28), datetime.date(2019, 10, 29)] when querying the DB for my "reservation dates". I need them to convert to normal dates,and if possibile,format them like this: "19-10-2019" So, dd-mm-yy format. I created a monstrosity to do this for me, wich (kinda sometimes) works...I will show the monster just for lols. here you go : var unavailableDates = "{{ unavailable_dates }}" unavailableDates = unavailableDates.replace(/datetime.date/g, "").replace(/[{()}]/g, "").replace(/]/g, ' ').replace("[", ' ').split() var y = unavailableDates[0].match(/.{1,14}/g) var dates = [] y.forEach((date, i) => { var now = moment(date).format('D-MM-YYYY') dates.push(now) }) console.log(dates); function unavailable(date) { dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear(); if ($.inArray(dmy, dates) == -1) { return [true, ""]; } else { return [false, "", "Unavailable"]; } } $(function () { $("#datepicker").datepicker({ dateFormat: 'yy-mm-dd', beforeShowDay: unavailable }) }) What would be the correct way of achieving what I want to do here ? Thanks so much ! -
good practices in django authentication system
I have a question, when adding the authentication urls of the auth application (django.contrib.auth.urls). Where should I add the templates? (login.html, etc) I have seen that they add in the templates folder of the project: project > templates > registration > login.html ... I've also seen that they do it in an application called registration: |-- project |-- registration |-- templates | |-- registration | |-- login.html | .... | |-- __init__.py |-- admin.py ..... But that name doesn't convince me much, I've also seen that they do it in applications called users andaccounts In which app should I do it? (accounts, users, registration) which one is best practice? I also want to comment that I am creating a custom user model, and I think it should go in one of these apps right? It would be the most logical, according to the name of the app. -
Redirecting correctly HTTP to HTTPS using Django and Nginx
Hi here's my problem. I'm trying to redirect my website from HTTP to HTTPS and I've succeeded partially doing so. The thing is, when I type mywebsite.fr, I get the name of the service of the container that contains the website's code in my address bar (e.g. djangoapp/) with a DNS_PROBE_FINISHED_NXDOMAIN error. Now, I tried the same thing with another Chrome browser of a another computer and this time when I type www.mywebsite.fr I get the same result where as the non-www is correctly redirected to the secure address. Finally, I tried the exact same process using my smartphone (Brave) with the www and non-www, I get https://djangoapp with an error ERR_NAME_NOT_RESOLVED whereas when I explicitly type https:\\mywebsite, I get no issues. So here is the NGINX portion that redirects to the HTTPS server: server { ... location / { return 301 https://djangoapp$request_uri; } } This is the location in the HTTPS server that refers to the upstream: server { ... location / { ... proxy_pass http://djangoapp; } } And, this is the service that runs the code: djangoapp: build: . ports: - "8000:80" links: - db depends_on: - db I do not master yet all the intricacies of NGINX … -
Hi, I am looking to create a form that displays a drop down menu with items specific to that user
I am looking to create a form that displays a drop down menu with items specific to that user. Please note my original code has no errors, I have summarised this one for simplicity. So let's say I have a form like this: html doc: <form> <p>Select a car:</p> <p>{{ form.car_name }}</p> </form> My models look like this: models.py class LoggedInUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='logged_in_user', on_delete=models.CASCADE) session_key = models.CharField(max_length=32) class Car(models.Model): car_name = models.CharField(max-length=100) car_owner = models.ForeignKey(LoggedInUser, on-delete=models.CASCADE) class SavedCars(models.Model): car_name = models.ForeignKey(Car, on-delete=models.CASCADE) I then created the form class as such: form.py class CarSelect(forms.Modelform): class Meta: model = SavedCars fields = [ 'car_name', ] As you can see. This current form setup gives me options to select ALL cars in that table even ones that are not assigned to a user. Which means on the form, every user can select any car. Not the desired result. I understand that a user has to be assigned a set of cars to choose from, So I tried this: class LoggedInUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='logged_in_user', on_delete=models.CASCADE) session_key = models.CharField(max_length=32) car_select = models.ManyToManyField(Car) // which detects the user selecting the car but this isn't my form. :( And this is obviously not possible: … -
ChoiceField disappears after overriding init method of BaseForm class
My application from an uploaded CSV file, reads header values and passes these headers into another class which extends Form. The goal was to populate this passed headers list finally into ChoiceField. To get the arguments, I overrode __init__. Somehow on overriding the __init__, my choicefield disappears, without any exception appearing. The choiceField appears when I am directly using ChoiceFields and not overriding the __init__ method. I tried modifying and working on different ways of overriding to get the arguments but could not succeed as in every case the ChoiceField goes missing. I am using python version 3.7.1 and Django version 1.9.8. Any advice would be appreciated. 1.views.py: def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() fs.save(myfile.name, myfile) for row in myfile: headerlist = row.decode('utf-8').split(",") break expense_form = ExpenseForm(headerlist) return visualize_view(request, expense_form) return render(request, 'core/simple_upload.html') def visualize_view(request, expense_form): return render(request,'core/visualize_view.html',{'expense_form':expense_form}) 2.forms.py : from django import forms class ExpenseForm(forms.Form): def __init__(self, headerlist, *args, **kwargs): super(ExpenseForm,self).__init__(*args, **kwargs) CHOICES = [] for i in range(len(headerlist)): c = (i, headerlist[i]) CHOICES.append(c) columns = forms.ChoiceField(choices=CHOICES) 3.visualize.py: {% extends 'base.html' %} {% block content %} {{ expense_form.as_p }} {% endblock %} -
Update last inserted record in Django
In Django, I want to retrieve the last inserted record from the database and update its values. I use this model: def User(models.Model): name = models.CharField(max_length=15) I run the following code to retrieve the last inserted record and update the name: User.objects.last().update(name=‘NEW NAME’) However, the error is that update is not a known method. Does .last() indeed return the entire record, or only the primary key? Thank you very much. -
TypeError: __init__() got an unexpected keyword argument 'choices'
TypeError: init() got an unexpected keyword argument 'choices' forms.py class StudentMarksheetform2(forms.Form): subject_code=( (1,'CS101') ,(2,'CS102') ,(3,'CS103') ,(4,'CS104') ,(5,'CS105') ,(6,'CS106') ) code_title=forms.IntegerField(choices=subject_code,default='1') class Meta(): model=StudentMarksheetdata2 fields=['code_title'] -
How can you specify where to create a virtual environment using pipenv?
I'm learning django and just installed pipenv via pip install pipenv and then pipenv shell and I notice that the virtual environment files are installed or created in some random default directory, I have two questions regarding this: 1) How can I customize that installation/creation directory for the virtual environment? Do I have to use a different command line from pipenv shell? 2) Can you have multiple folders with different virtual environments inside each folder/project? -
Inserting a url into a custom Django email template
I'm able to send the email, however, the link does not show up. There is just a blank spot where the link is supposed to be. Do I need to add it to like the username? from django.core.mail import EmailMessage from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context subject, from_email = 'subject', '<info@mysite.com>' plaintext = get_template('email.txt') htmly = get_template('email.html') username = user.username d = { 'username': username } text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email]) msg.attach_alternative(html_content, "text/html") msg.send() Here is the email.html file: <h3>Hi <strong>{{ username }}</strong>,</h6> <p> disown kvdsvnsdov vknvisodvnsdv dsdov siod vsd. Here is a link:</p> <a href="http://domain{% url 'home' %}">Check Now</a> Here is the email.txt: Hi {{ username }}, disown kvdsvnsdov vknvisodvnsdv dsdov siod vsd. Here is a link: http://domain{% url 'home' %} -
Recommended way to show balance in bank account in django template
In Django I have a model where I log transaction (date, amount, description fields). In my view I would like to show a running balance, something like so: Date | Description | Amount | Balance ---------------------------------------------- 2019-01-01 | Item 1 | $100 | $100 2019-01-02 | Item 2 | -$10 | $90 2019-01-03 | Item 3 | $200 | $290 2019-01-04 | Item 4 | $10 | $300 Now, the problem is that BALANCE should of course be calculated by summing the previous balance and the current transaction. To me, it seems to make most sense to do this calculation inside the view. I wouldn't know any other sensible way to put it anywhere else. Is this correct? If so, what is the best way of doing this? If not, what is the right way of handling this? class Transaction(models.Model): date = models.DateField() amount = models.DecimalField(max_digits=15, decimal_places=2) account = models.ForeignKey(BankAccount, on_delete=models.CASCADE) description = models.TextField(null=True, blank=True) In my view: transactions = Transaction.objects.all().order_by("date") -
Django: storing currently logged in user in database on form submission
What I am trying to do is on submission of a form store the currently authenticated username in an object so that I can write code in my template that will check the currently authenticated user against the value stored in the database and only present certain options if the logged in user matches the user value stored in the database. I would also like to be able to create an object without a user logged in and check an object instance within the database for an empty value and present options to an unauthenticated user. I am using from django.contrib.auth.models import User for authentication and it is working fine, I have all other aspects of the code working. I just can't seem to find a way to extract the value from auth.models and store it. I've tried all of the different methods I could find on stack overflow for extracting the value within the .view and storing it, but none have worked. This may have to do with the specifics of my code. Here is the model: class Job(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() requirements = models.TextField(blank=True, default="") location = models.CharField(max_length=80) type = models.CharField(choices=JOB_TYPE, … -
Card Layout Bootstrap overlaps my other card items | Django, Bootstrap
I've been using Django to build an E-Commmerce WebApp. I've implemented the Card Layout from Bootstrap. The issue is that in some cases my Card items are overlapping each other. Not only that, but my images and the text (item description) are also not properly aligned inside the card. Can anybody tell me what's wrong in my code and suggest improvements? I've pushed my entire project to GitHub. Click Here. Any kind of help is hugely appreciated! -
Django + GeoDjango and Postrgresql (postGis extension): Wrong distance returned from the database
So we're having a seemingly straight forward problem with Django, GeoDjango and Postgis. There's a lot of mention online that you need to include the SRID both on the point you're trying to query and on the database field. The problem is we do have the SRID on the database field and yet the distance returned is incorrect. Normally I wouldn't care so much and just do the calculation in python for the returned rows, but in this case we need to filter on distance and without it being accurate I'm not comfortable moving forward. Model: class LocationStore(BaseLocation, LocationStoreFunctions): street = models.CharField(max_length=64) extras = models.CharField(max_length=64, blank=True, null=True) town = models.CharField(max_length=64) zip_postal = models.CharField(max_length=32) region = models.ForeignKey(Region) country = models.ForeignKey(Country) coordinates = PointField(srid=4326, db_index=True) timezone = TimeZoneField(default='US/Eastern', blank=True) phone_number = models.CharField(max_length=32) is_closed = models.BooleanField(default=False) features = MultiSelectField(choices=LOCATION_FEATURE_CHOICES, default=[]) Query Set: locations = LocationStore.objects.filter(coordinates__distance_lte=(self.client_point, D(m=distance))).annotate(distance=Distance('coordinates', self.client_point, sphereoid=True)).order_by('distance') Resulting Query: SELECT "retailers_baselocation"."id", "retailers_baselocation"."polymorphic_ctype_id", "retailers_baselocation"."retailer_id", "retailers_baselocation"."identifier", "retailers_baselocation"."name", "retailers_baselocation"."date_created", "retailers_baselocation"."date_updated", "retailers_baselocation"."rating", "retailers_locationstore"."baselocation_ptr_id", "retailers_locationstore"."street", "retailers_locationstore"."extras", "retailers_locationstore"."town", "retailers_locationstore"."zip_postal", "retailers_locationstore"."region_id", "retailers_locationstore"."country_id", "retailers_locationstore"."coordinates", "retailers_locationstore"."timezone", "retailers_locationstore"."phone_number", "retailers_locationstore"."is_closed", "retailers_locationstore"."features", ST_DistanceSphere("retailers_locationstore"."coordinates", ST_GeomFromEWKB('\001\001\000\000 \346\020\000\000s\242]\205\224\037F@\353\016s\223\342!S\300'::bytea)) AS "distance" FROM "retailers_locationstore" INNER JOIN "retailers_baselocation" ON ("retailers_locationstore"."baselocation_ptr_id" = "retailers_baselocation"."id") WHERE ST_DistanceSphere("retailers_locationstore"."coordinates", ST_GeomFromEWKB('\001\001\000\000 \346\020\000\000s\242]\205\224\037F@\353\016s\223\342!S\300'::bytea)) <= 10000.0 ORDER BY "distance" ASC; Resulting Results: **NOTICE: Coordinate values were coerced into … -
Django select2, show subcategories when parent category name searched
I used django-select2 to show parent categories and sub categories. When I search the name of parent category using 'Select2MultipleWidget' (Pacific Time Zone, for example), it does not show its sub categories. Is it possible to show belonging sub categories when parent categories are searched? I was reading select2 documentation but I couldn't find relevant options. #models.py class Category(models.Model): name = models.CharField(max_length=200) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=180) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user") title = models.CharField(max_length=200) category = models.ManyToManyField(SubCategory) desc = models.TextField() #forms.py class PostForm(forms.ModelForm): def categories_as_choices(): categories = [] for category in Category.objects.all(): new_category = [] sub_categories = [] for sub_category in category.subcategory_set.all(): sub_categories.append([sub_category.id, sub_category.name]) new_category = [category.name, sub_categories] categories.append(new_category) return categories category = forms.ChoiceField( choices=categories_as_choices(), widget = Select2MultipleWidget( attrs={'class': 'form-control col-4'} ), ) class Meta: model = Post fields = ['title', 'desc', 'category'] I tried to use select2's example of timezone and state name (Pacific Time Zone as a parent category with California as a sub category). When I type 'Pacific Time Zone', it won't show 'California', sub category. -
Python Django getting 3 inputs instead of one as an array on condition
Trying to build a form in django as a newcomer, What I am trying to achieve is to build a form where the first input is an option from a list returned by a script, have a checkbox for whether the second input is a list of 3 numbers when the value is false or something from the choice list other than first input when the value is true what I tried was from . import script from django import forms class PostForm(forms.ModelForm): players = script.script() p1 = forms.ChoiceField(choices=enumerate(players)) choice = forms.BooleanField(label=choice,initial=False) p2 = forms.ChoiceField(choices=enumerate(players)) if choice else ... what i cant figure out is a method to take a 3 valued list as a form or if the above is a correct way to do it. My ultimate goal is to use the form data to fire script.run(p1,p2,choice) and not store the data.