Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to implement a type of qstion into a django quiz
I am trying to implement an already existing type of question into an already existing quiz. So I'm using this quiz app: https://github.com/tomwalker/django_quiz I am trying to implement this: https://github.com/rodrigosetti/recruitr which is a coding challange into the quiz above. Does anyone have an idea on how I would do that. It is not as simple as copying models from one place to the other. A detailed answer would be perfect but even a rough idea will be very appreciated. Thanks in advance. -
Redirect with arguments and message
I want to do a redirect with arguments and at the same time send a message to the redirected page. Where to redirect: path('companies/<int:pk>/', AccountCompanyDetailView.as_view(), name='detail_company') from django.shortcuts import redirect def post_view(request, id): return redirect('detail_company', pk=id) I want to send to the page to wich will be redirected a 'message' to show to the user why it was redirected. It is possible ? -
Python Implement makemigrations and migrate with c++/c?
Latest project I am working on has 3500+ database models(grown rapidly form 620) which need to run makemigrations and migrate (which takes almost 6hours to complete on a skylake xeon single core). I would like to implement the migration part is C++/C which I guess, can be faster. How can I start experimenting with C/C++ with Python? Any simple code or guide? thanks, -
Django Forms Showing No Input Fields
instead of the whole form i am just seeing the submit button not the form fields Goal: get form fields to load and be able to submit form. views.py file from django.shortcuts import render from django.template.response import TemplateResponse from django.views import generic from friendsbook.models import Status,User from django.views.generic.edit import CreateView from .forms import CreatePost class IndexView(generic.ListView): template_name='uposts/home.html' context_object_name='status_object' def get_queryset(self): return Status.objects.all() class post_detail(generic.DetailView): model=Status context_object_name='user_profile' template_name='uposts/detail.html' def get_queryset(self): abc=Status.objects.all() return abc; def create_post(request): form=CreatePost() return render(request,"uposts/createpost.html",{'form':form}) forms.py file from django import forms from friendsbook.models import Status class CreatePost(forms.Form): class meta: model=Status fields = ("title","username" ) createpost.html file inside designated folder {% extends "friendsbook/structure.html" %} {% block content %} <form action="" method="post">{%csrf_token %} {{ form.as_table }} <input type="submit" value="Save"> </form> {% endblock %} i also try by python shell but it's of no use. look at this it's giving me empty string instead of form fields. please help me. -
POST doesn't write to database
I have my requestaccess view below, which will write to my database if I remove the if request.method == 'POST', but if i keep it in. The request is never written. I'm trying to understand why the POST isn't occurring and how to make it happen? def requestaccess(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc') reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True) checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) coid = User.objects.filter(coid = request.user.coid).filter(formattedusername=request.user.formattedusername) facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid , active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True) divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True) selectedaccesslevel = '7' if request.method == 'POST': selectedaccesslevel = request.POST.get('accesslevelid') print(selectedaccesslevel) selectedphi = '0' if request.method == 'POST': selectedphi = request.POST.get('phi') print(selectedphi) if request.method == 'POST': for i in checkedlist: requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title ,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi, access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00') requestsave.save() args = {'retreivecheckbox': reportlist, 'cfo7':facilitycfo, 'cfo5':divisioncfo, 'checkedlist':checkedlist } return render(request,'accounts/requestaccess.html', args) # return render(request, 'accounts/requestaccess.html', args) My request.method == 'POST' … -
Trying to run python script within Django within Docker
I am trying to run my python script that uses some models defined inside django which is then within a docker container. I use the following command: sudo docker-compose -f production.yml run django python manage.py shell < send.py But I keep getting this error: IndentationError: unexpected indent File "<console>", line 1 stats = grp_px.calc_stats(dropna=False) ^ IndentationError: unexpected indent File "<console>", line 1 st = stats.render_perf(key=key) ^ IndentationError: unexpected indent File "<console>", line 1 perf_list.append([key, st.render()]) ^ IndentationError: unexpected indent File "<console>", line 1 send_mail(html_message=render_to_string('fund_vs_peers.html', {'perf_list': perf_list}), ^ IndentationError: unexpected indent File "<console>", line 1 message='', ^ Basically, I get an indentation error each line of my code. Any ideas? -
Class inside dict - Django template
Probably a simple question but I've searched for a while and haven't been able to find an answer for how to cycle through all of the items in my dictionary and call the class items inside of the template I've tried using custom template tags, but the syntax doesn't seem to line up with what I'd like. Here is my code: data = [[OrderedDict([('token', 'XXXXXXXXXXXXXXX'), ('devices', [['Christmas Lights', 'XXXXXXXXXX'], ['Gold Beedrom Lamp', 'XXXXXXXX']])])], [[['5', 'off', 124], ['6', 'off', 124], ['7', 'off', 100], ['8', 'off', 124]]]] #Dictionary and Class assignment class LightStatus: def __init__(self,id): self.id = id self.state = None self.bri = None def add_data(self,id,state,bri): self.id = id self.state = state self.bri = bri AllLights = dict() for i in data[1]: for light in i: id = light[0] state = light[1] bri = light[2] AllLights[id] = LightStatus(id) AllLights[id].add_data(id,state,bri) What I'd like to have in template: #What I want to do in the template for i in AllLights: print(AllLights[i].id) print(AllLights[i].state) print(AllLights[i].bri) return render(request, 'file.html', 'lights': AllLights) #What I've tried {% for light in lights %} {% for i in light %} {{lights.light.id}} #light being the variable from above. {% endfor %} {% endfor %} I've also tried using a custom template tag: … -
Users with different attributes
from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): type_choices = ( ('A', 'User Type A'), ('B', 'User Type B'), ('C', 'User Type C'), ) user_type = models.CharField(max_length=2, choices=type_choices, default='C') class UserDetails(model.Model): type = models.OneToOneField('CustomUser') extra_info = models.CharField(max_length=200) How would I make it so that each user has different fields? Examples. One has a available hours field. Another has an address field. Or Would I do something like this? class BaseUser(AbstractUser): # all the common fields go here, for example: email = models.EmailField(max_length=10,unique=True) name = models.CharField(max_length=120) class StoreOwnerUser(BaseUser): # All Store Owner specific attribute goes here balance = models.some_balance_field() stores_owned = models.some_stores_owned_field() class Meta: verbose_name = 'Store Owner' And if this is the way to do it then: What would be specified as AUTH_USER_MODEL? Also at the time of login: user = authenticate(username = username, password = password). From which table (CustomerUser or StoreOwnerUser) would the authenticate function check from? -
Issues with queryset and slicing
I have 2 models, Company and Product, with Product having a ForeignKey to Company I do the following filtering: company = Company.objects.filter(account=account, pk=company_pk) if not company: raise Http404 product = Product.objects.filter(company=company, pk=product_pk) if not product: raise Http404 return product And I have the following error: The QuerySet value for an exact lookup must be limited to one result using slicing. I presume it happens because company result is a QuerySet and is pushed as argument in Product.objects.filter -
How to Replicate PHP Crawling of Server Directory in Django
I have a D3 visualization that relies on a PHP function to crawl through a folder and return filenames of CSVs. That visualization is served via IIS and a PHP CGI handler. I would like to include that .php file in a Django project (that already includes database-driven apps) to centralize all pages behind one URL base (i.e. servername/mysite/...). I understand that mixing PHP and Python is a bad idea, so how would I replicate this PHP functionality in the context of a Django project? Would the Python code necessary to crawl through a folder be placed in a Django view, and then somehow translated to a template? I'm not sure where to start. -
Like button with Ajax
I am trying to create a like button with ajax but It doesn't work, look the architecture below: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_publicacion = models.DateTimeField(auto_now_add=True) tag = models.ManyToManyField(Tags, blank=True) slug = models.SlugField(null=True) likes = models.ManyToManyField(Perfil, blank=True, related_name="likes") def __str__(self): return (self.titulo) @property def total_likes(self): return self.likes.count() def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Comentario, self).save(*args, **kwargs) views.py def like(request): if request.method == 'POST': user = request.user slug = request.POST.get('slug', None) comentario = get_object_or_404(Comentario, slug=slug) if comentario.likes.filter(id=user.id).exists(): comentario.likes.remove(user) message = 'You disliked this' else: comentario.likes.add(user) message = 'You liked this' ctx = {'likes_count': comentario.total_likes, 'message': message} return HttpResponse(json.dumps(ctx), content_type='application/json') urls.py url(r'^like$', login_required(like), name='like'), html <input type="button" id="like" name="{{ company_slug }}" value="Like" /> <script> $('#like').click(function(){ $.ajax({ type: "POST", url: "{% url 'home:listar' %}", data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(response.message); alert(' likes count is now ' + response.likes_count); }, error: function(rs, e) { alert(rs.responseText); } }); }) </script> When I push the button like it does not do anything. When I look the console it tells me: 'Uncaught TypeError: $.ajax is not a function enter code here` at HTMLInputElement. (listar:92) at HTMLInputElement.dispatch (jquery-3.2.1.slim.min.js:3) … -
INNER JOIN in PYTHON (Django Project)
I would like to know how this sql code looks like in the python language: > SELECT * FROM COLETA INNER JOIN TRANSDUTOR ON COLETA.id_transdutor = > TRANSDUTOR.id_transdutor INNER JOIN USER ON TRANSDUTOR.id_user = > USER.id_user Note that I have 3 tables (COLETA, TRANSDUTOR, USER), and I want to relate them through your foreign keys. I saw something about SELECT-RELATED to Django, does anyone know how to use this? Thanks guys. -
Django Mixing Static Pages With Django Apps
I have a Django project that has one database-driven (i.e. normal) Django app. I have a .php webpage that I would like to include within the Django project that is a D3 visualization based on CSV files. Is it possible and kosher to include this page that includes php, JavaScript, and references to static CSV files in the Django project? If so, how would it be accomplished? I have seen flatpages, but the Django documentation and various tutorials make it seem like that is only for simple html pages. -
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured.
I wanted to connect MySQL database to my django project. But its throwing an error - "django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." (myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell Traceback (most recent call last): File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute saved_locale = translation.get_language() File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language return _trans.get_language() File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__ if settings.USE_I18N: File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. **settings.py** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'user', 'PASSWORD': 'root', 'HOST':'', 'PORT': '', } } -
How do I solve " TypeError ... missing positional argument: on_delete " in Django while migrating my blog/app?
So I just started learning Django yesterday, and here, I created some classes in my app and now I am trying to migrate it. Here's the script, saved in 'models.py' : from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title It is meant to make a simple blog, and I am following the exact steps mentioned in https://tutorial.djangogirls.org/en/django_models/ After running "python manage.py migrate blog", I get the following error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File … -
Passing a GET from one view to a POST in another?
I have a field report_id which is a collection of check boxes that gets passed from one view called profile to another called request. I can access the GET request in the request view using: checkedlist = request.GET.getlist('report_id') I'm running into problems now because I need to send those checkedlist report_id's to a POST request to a URL called submitted. What are my options to send the POST? In my request form I'm displaying the report name as : reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) I can render report_name_sc from submitted but not the report_id, which needs to be part of my save to the db in submitted, but it won't display anything because checkedlist is an empty set at this point: if request.method == 'POST': for i in checkedlist: requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title ,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi, access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00') requestsave.save() Added the template for requestaccess: <form action = "{% url 'submitted' %}" form method = "POST"> {% csrf_token %} {{ form.as_p}} <div class="container"> <div class="row"> <div class="col"> <h2>{{ user.username … -
Django REST framework serialization error on pk field
In my Django REST framework project i have this model: class ml_request(models.Model): model_id = models.CharField(max_length=100) created = models.DateTimeField(auto_now=True) p_country = models.CharField(max_length=100, blank=False, default='') p_description = models.TextField(null=False, blank=False) p_designation = models.CharField(max_length=200, blank=False, default='') p_points = models.IntegerField(default=00) p_price = models.IntegerField(default=00, blank=False) p_province = models.CharField(max_length=100, blank=False, default='') p_region_1 = models.CharField(max_length=100, blank=False, default='') p_region_2 = models.CharField(max_length=100, blank=False, default='') p_variety = models.CharField(max_length=100, blank=False, default='') p_winery = models.CharField(max_length=100, blank=False, default='') owner = models.ForeignKey('auth.User', related_name='req_owner', on_delete=models.CASCADE) highlighted = models.TextField() class Meta: ordering = ('created',) then i create my serializer like this: from rest_framework import serializers from botoapi.models import ml_request, ml_response, LANGUAGE_CHOICES, STYLE_CHOICES, ml_logs from django.contrib.auth.models import User class RequestSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) highlight = serializers.HyperlinkedIdentityField(view_name='request-highlight', format='html') owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = ml_request fields = ('id', 'model_id', 'highlight', 'created', 'p_country', 'p_description', 'p_designation', 'p_points', 'p_price', 'p_province', 'p_region_1', 'p_region_2', 'p_variety', 'p_winery', 'owner') def create(self, validated_data): log_save = ml_logs(l_verbose=validated_data, l_method="CREATE", l_action=validated_data.get("model_id", None)) log_save.save() return validated_data bur when i run it and try to add values django return this error: AttributeError at /requests/ 'dict' object has no attribute 'pk' Request Method: POST Request URL: http://127.0.0.1:8000/requests/ Django Version: 1.11.7 Exception Type: AttributeError Exception Value: 'dict' object has no attribute 'pk' i have the id as PK and i add it … -
change django application directory in PyCharm
I have set up a Django project in PyCharm using pipenv. I have used pipenv to create the virtual environment in my project directory. Within the virtual environment directory, I have created src directory to place my Django project. The directory structure is like / Project Directory |- src |- django_app |- other_app |- manage.py |- db.sqlite3 |- Pipfile |- Pipfile.lock In PyCharm IDE, I have opened the Project Directory as a project. When I use Alt+Enter to auto import modules from other apps. The import line is prefixed with src. like from src.other_app.models import ModelName Whereas It should be from other_app.models import ModelName How can I reconfigure Django path in PyCharm to use src directory as root for Dango apps/modules? -
Structure models in django
I want to display some metadata from some files and also want to check whether files have the data within them or not (by extracting file). The structure for files is that I have some data sources (lets say ds1, ds2, ds3 etc) and each data source have some heads (group of files) (head1, head2 etc) and then each head has files (file1, file2 etc) within them which I want to operate on. The data source can contain 0 or more heads and each head can contain 0 or more files. My approach has been so far that I created a project in django then for each data source I created an app (django app). Within each app I created model with the name of heads and, file name became the fields for that model. However this does not seem to be a good approach as lets say in future if any of my head gets extra file then I have to add a field(column) in that head which is not easy and also this is not scalable with increasing number of heads. How can I design the django models for 3 layered file extraction? Are there any good resources … -
Django hosted on Apache - Uploading a file going to wrong location
I have a simple website that allows the user to upload a file to my server. I want the file to be uploaded into my django project folder in a sub directory. Everything is working fine but when I use the upload feature on my website I get a permissions denied on the folder /var/www BUT the thing is I changed the DocumentRoot to equal /mnt/public/apps - which is where I want my uploaded files to go (the upload creates a sub directory). I have correct permissions in /mnt/public but I can't figure out how to point django or apache so that my upload goes to the /mnt/public/apps root instead of /var/www Any help would be greatly appreciated! -
IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (..))
when deleting users with schedule_files I got this: IntegrityError at /admin/auth/user/166/delete/ (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (vacation.vacations_schedulefile, CONSTRAINT vacations_schedulefile_user_id_e85fa52f_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))') My models are: class ScheduleFile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) added = models.DateTimeField(default=django.utils.timezone.now) def __str__(self): return '[User ID: {}] {}'.format(str(self.user.id), self.user.username) And class VacationEvent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) schedule_type = models.CharField(choices=SCHEDULE_TYPES, default=STRICT_TIME, max_length=3) exclude_fba_from_chatzos = models.BooleanField(default=False) schedule_file = models.ForeignKey(ScheduleFile, on_delete=models.CASCADE, null=True) status = models.CharField(verbose_name="status event", choices=EVENT_STATUSES, max_length=3, default=CREATED) And User(AbstractUser) I decided to create pre_delete signal and delete relative objects of schedule model: @receiver(pre_delete, dispatch_uid='User') def user_del(sender, instance, **kwargs): i = instance events = VacationEvent.objects.filter(user_id=166) schedule = prefetch_related_objects(events, 'schedule_file__user') schedule.delete() # instance.user.schedulefile_set.clear() # qs = VacationEvent.objects.filter(user_id=166).prefetch_related_('schedule_file') # qs.delete() # b = ScheduleFile.objects.filter(user_id=166) # e = VacationEvent.objects.filter(user_id=166) # e.schedule_file.remove(b) But it returns 'NoneType' object has no attribute 'delete'. How can I do it right? Thanks for any help. -
Django Dropdown POST
... I'm new in django and I have this problem: When I want to show the data selected on my dropdown, it doesn't work ... this is the code index.html <form method="post" action="/getdata/"> <select name="Lista"> <option selected="selected" disabled>Objects on page:</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> <input type="submit" value="Select"> </form> views.py def index(request): if request.method == 'POST': Lista = request.POST.get('Lista') print Lista context = { Lista: 'Lista' } return render(request, 'showdata.html', context) else: template = loader.get_template('index.html') return HttpResponse(template.render()) getdata.html <form method="post" action="/getdata/"> <table> <tr> <td>Numero:</td> <td><strong>{{ Lista }}</strong></td> </table> </form> when I executed the server i just see the following "Numero: " without any number selected ... Thanks for your help ... -
Trying to react to a woocommerce webhook on django
Hello, I'm trying to react to a woocommerce webhook on django. I have a webhook who reacts to each order of my website. For each order, I have to parse the content to save de id, price, etc... HOW can i tell to my Django (in views.py, models.oy, etc...) to do an action when a webhook from www.xxx.com arrives thank you! -
Django AutoCompleteSelectMultipleField has required=True, but form saves with it being blank when adding an instance for the first time
On a Django project, I am using AutoCompleteSelectMultipleField from the ajax_select.fields module and I am specifying required=True for this field. The field is mandatory when I am trying to save the form for an instance that already exists, i.e. the browser does not let me save without filing in the field. But when I try to add a new instance (a photo in my case) I can save the instance without the field being filled in. Here is the code for the field in 'admin.py': from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField class PhotoExtendedAdminForm(forms.ModelForm): authors = AutoCompleteSelectMultipleField('authors', required=True, help_text=None, plugin_options={'minLength': 4}) How do I make this field absolutely mandatory even when I am adding a new instance? -
Two Ajax calls only meet one condition at a time
I have the following script that sends a POST of my select option to a url called requestaccess. This works great when using only one of the two, but when I change the other field the result of the POST is None for the first and correct for the second and vice-versa. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <select title ="accesslevelid" class="form-control" id="accesslevelid" onclick="accesslevelid"> <option value=""> Please select your access level </option> <option value="7"> Facility </option> <option value="5"> Division </option> <option value = "3"> Corporate </option> <option value = "6"> Market </option> <option value = "4"> Group </option> </select> <script> $(document).ready(function () { $('#accesslevelid').on('click', function () { var accesslevelid = $(this).val(); $.ajax({ url: "{% url 'requestaccess' %}", headers: { 'X-CSRFToken': '{{ csrf_token }}' }, data: { accesslevelid: accesslevelid, }, type: 'POST', success: function (result) { ; }, }); }); }); </script> </div> <div class="col"> <label for="phi"><h3>PHI</h3></label> <select class="form-control" id="phi" title = "phi" onclick="phi"> <option value = ""> Please select if you need access to PHI data </option> <option value = "0"> No </option> <option value = "1"> Yes </option> </select> <script> $(document).ready(function () { $('#phi').on('click', function () { var phi = $(this).val(); $.ajax({ url: "{% url 'requestaccess' %}", headers: { 'X-CSRFToken': '{{ csrf_token }}' …