Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django: Populating Model Form Fields with values from Imported JSON file
I have a model form that saves all form field inputs to the backend database as one entry. I also have a JSON file that contains multiple JSON objects whose fields corresponds to the model form field. This JSON file is being uploaded via FileField in the model. Ultimately, I want to be able to upload a JSON file with the multiple JSON objects into my model form and populate the fields with the corresponding values from the uploaded JSON file. Each JSON object will be a single entry to my database and they can have null values for at least one field. Ideally, I would like to be able to choose which JSON object (from the uploaded JSON file) gets loaded to my model form fields to eventually be saved in my database. How would I go about implementing this? -
The use of argparser instead of the OptParser in Django >= 1.8
I recently trying to learn about argparse in python, this gave me a hint on how programs like the Django framework and python itself give helpful Tracebacks for helping trace errors in a typical developers life :). I read about argparse in a few places to find out more and when I came across Django that changed from OptParser to argparser. What I know is argparser is just used for The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments. My question is what does a command line parser like OptParser lack or what is better in argparse that made a huge framework Django change a cmd parser -
RadioSelect widget does not show labels in MultiWidget
I am trying to build a custom MultiValue field in django that consists of two widgets: RadioSelect and TextInput: if a user chooses 'Other' then they can insert the value there. Everything works, with one weird exception: the labels for radio buttons are not shown (see picture). Values are rendered ok, but the labels are just not there. What I am doing wrong? fields.py from .widgets import OtherSelectorWidget class OtherModelField(models.CharField): def __init__(self, *args, **kwargs): self.inner_choices = kwargs.pop('choices', None) super().__init__(*args, **kwargs) def formfield(self, **kwargs): return OtherFormField(choices=self.inner_choices, **kwargs) class OtherFormField(MultiValueField): def __init__(self, **kwargs): self.choices = kwargs.pop('choices') self.widget = OtherSelectorWidget(choices=self.choices) fields = (CharField(), CharField(),) super().__init__(fields=fields, require_all_fields=False, **kwargs) def compress(self, data_list): return str(data_list) widgets.py from datetime import date from django.forms import widgets class OtherSelectorWidget(widgets.MultiWidget): def __init__(self, choices=None, attrs=None): self.choices = choices _widgets = ( widgets.RadioSelect(choices=choices), widgets.TextInput(attrs=attrs), ) super().__init__(_widgets, attrs) def decompress(self, value): if value: return [value[0], value[1]] return [None, None, ] def format_output(self, rendered_widgets): return ''.join(rendered_widgets) def value_from_datadict(self, data, files, name): datelist = [ widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)] radio_data = self.widgets[0].value_from_datadict(data, files, name + '_0') text_data = self.widgets[1].value_from_datadict(data, files, name + '_1') try: D = [radio_data, text_data] except ValueError: return '' else: return D -
django ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' runserver
when I run python manage.py runserver and I try to visit my site on my local I get the following error: File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 432, in stored_name raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' my settings file in full: """ Django settings for suitsandtables project. Generated by 'django-admin startproject' using Django 1.11.10. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os from decouple import config, Csv import datetime # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=True, cast=bool) DEBUG_PROPAGATE_EXCEPTIONS = config('DEBUG_PROPAGATE_EXCEPTIONS', default=True, cast=bool) BLOCKEMAIL = config('BLOCKEMAIL', default=True, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) # send grid email code EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool) EMAIL_HOST = config('EMAIL_HOST') EMAIL_PORT = config('EMAIL_PORT') EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # Amazon S3 code AWS_UPLOAD_BUCKET = config('AWS_UPLOAD_BUCKET') AWS_UPLOAD_USERNAME = config('AWS_UPLOAD_USERNAME') AWS_UPLOAD_GROUP = config('AWS_UPLOAD_GROUP') AWS_UPLOAD_ROOT_URI = config('AWS_UPLOAD_ROOT_URI') # … -
Need help creating catch-all url() entry using regex
So had zero issues with my Django and React URL routing in dev, but now that I am trying to move to production, running into all kinds of issues. Yes, I suck when it come to regex... definitely something I need to sit down and commit to learning. In dev, my catch-all was just the following which worked perfectly: url(r'', TemplateView.as_view(template_name='index.html')), In production, I got Uncaught SyntaxError: Unexpected token <. This, as it was explained to me, had to do with JS being caught in the url instead of index.html and that the JS needed to "pass through". I was told to try: url(r'^$', TemplateView.as_view(template_name='index.html')), This worked. The web application loaded and I was able to navigate. Another problem came up, however, when it came to verification emails and just with links in those am I running into issues with Page not found (404) which, again, wasn't an issue in my dev setup. The email links look like the following: https://test.example.com/auth/security_questions/f=ru&i=101083&k=6d7cd2e9903232a5ac28c956b5eded86c8cb047254a325de1a5777b9cca6e537 What I get back is this: Page not found (404) Requested URL: http://test.example.com/auth/security_questions/f%3Dru&i%3D101083&k%3D6d7cd2e9903232a5ac28c956b5eded86c8cb047254a325de1a5777b9cca6e537/ My react routes are the following: <App> <Switch> <Route exact path='/auth/security_questions/f=:f&i=:id&k=:key' component={SecurityQuestions} /> <Route exact path='/auth/*' component={Auth} /> <Route exact path='/' component={Auth} /> </Switch> </App> This … -
Django Authentication with Firebase/Firestore
I want to integrate Django authnetication with Firebase. I know for custom Django authentication I need to return a user object, the problem is my users are registered in Firebase's Firestore. I had the idea to work with request.session, where I can add ['uid'] on login and clear it on logout, but I am not sure if it is the best way. Is there any more official way for me to authenticate my users on Django with firebase's firestore? -
Group by Month and Gender in Django queryset
I have the following queryset, It works well with the grouping by month. from django.db.models.functions import TruncMonth queryset = UserProfile.objects.filter(date_created__year='2018') .annotate(date=TruncMonth('date_created')) .values('date').annotate(total_entries=Count('id')) What I want is to group also by gender, here is a similar model with the gender field class UserProfile: date_created = models.DateTime(auto_now_add=True) gender = models.CharField(max_length=3,choices=[('F',"Female"),('M',"Male")],default='M') Expecting result: May: 5 users [4(Male), 1(Female)] June: 20 users [15(Male), 5(Female)] -
Django static files being generated with additional path
So, I'm using Django and pythonanywhere in order to setup an webpage, but I'm facing some issues when retrieving static files. I've followed the tutorial for static files (which is great btw) and everything works for the index.html page. However, when trying to go to a second page, it throws an error which fits one of the issues described in this other link: https://help.pythonanywhere.com/pages/DebuggingStaticFiles/ The path to the file and the path in the URL don't quite match (eg, there's an extra level of folder hierarchy in one and not the other) However, I don't know how to fix it... What is happening is that my log info shows that I'm loading: /static/pgbfiles/medicine.png -- this is working for the index.html /publicacoes/static/pgbfiles/img.css -- for the second page named publicacoes.html What I would like to have is all the static files in one single folder. They are already there but I don't know how to tell Django that they are all there for both html files... I think I could add an additional folder for the "publicacoes" files, but that is not what I would like to do atm. And this is how I'm loading the info on both index and publicacoes.html: … -
Dumped heroku database gives 'UnicodeDecodeError' exception on local machine
I'm trying to download heroku project (django) alongside with its database to another local machine. I've managed to download project with git and database through pg:backups. I've restored database from backup to local postgres and now I can succesfully see it in pgAdmin. But when I'm trying to run project or migrate it, I get 'UnicodeDecodeError' exception. What can be a source of the problem? I use conda with python2.7 on Windows7. [worldcup2018env] G:\Programming\world-champ-2018>python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_ line utility.execute() File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\core\management\commands\migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\db\migrations\loader.py", line 52, in __init__ self.build_graph() File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\db\migrations\loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\db\migrations\recorder.py", line 69, in applied_migrations self.ensure_schema() File "C:\Anaconda\envs\worldcup2018env\lib\site-packages\django\db\migrations\recorder.py", line 63, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128) My environment: (worldcup2018env) conda list # packages … -
How to set correct pagination href of next page if having arguments in url - django
I am working on a django project but I am facing problem in pagination, on search page if multiple argument are passed in url then how I can set them to href of next page, here what I am trying to do is - {% if is_paginated %} <ul class="pagination pull-right"> {% if page_obj.has_previous %} <li><a href="?q={{ query }}&page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?q={{ query }}&page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li><a href="?q={{ query }}&page={{ page_obj.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} but if first page url is http://127.0.0.1:8000/search/products/?q=shirt&brand=Adidas and the next page is http://127.0.0.1:8000/search/products/?q=shirt&page=2 brand is not there !! it is not possible for me to add each arguments to href as I did for query, is there any way to just add &page{{i}} at the end of url? -
ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' django heroku angular
I am running django heroku and angular I am having an issue where I add new static files to django then upload to heroku, but the heroku instance keeps showing an old version of the code rather than the one I updated. I posted this question to address it. static file issue causing django 500 error? to which I was given an answer to do this: This is a common problem with whitenoise. I have wasted countless hours on this. Heres how you can deal with this issue. put these two lines in your settings.py DEBUG = False DEBUG_PROPAGATE_EXCEPTIONS = True and try to run the app on heroku. It will break just like it always did. Now go to https://dashboard.heroku.com/apps/<app_name>/logs Normally you wont be able to see logs when debug is False, but thanks to DEBUG_PROPAGATE_EXCEPTIONS=True you can see logs There, look for the file which whitenoise can't find and making whitenoise go haywire. In my case it was some random css file which was reference in my base.html. either you can fix its location or simply delete the line from base.html which references this file. after this, if tehre is issue with another file(s) keep doing it. Eventually … -
How do I make this regex utl pattern works in django 2
I need to make a url pattern which could work with this url: mysite.com/blog/12/بلاگ-مثال It contains utf-8 characters so I tried using \X: re_path(r'^blog/?P<blog_id>[\d+]+/(?P<slug>[\X.*]+)/$', views.single_blog, name='single_blog') But it didn't work. I don't know why. Maybe just because I'm not good in regex. So I tried a different pattern using just .* to accept anything: re_path(r'^blog/?P<blog_id>[\d+]+/(?P<slug>[.*]+)/$', views.single_blog, name='single_blog') But this also doesn't work and I get: The current path, blog/12/بلاگ-مثال, didn't match any of these. So as I mentioned I'm not good in regex, what's the right way to fix this? Is it the right time to say now I have two problems or regex is the only way? -
How do I create a session between an Android Application and Django Rest-Auth through Retrofit?
I am able to do the initial log in to the server and get the token, but when I try to do another request I get the HTTP error 403, so I am not actually being authenticated. When I go through the browser or the android application, this is the key that I am getting when I log in. { "key": "64ea43a78fa18da19364d2d0ae5a12371e5d0ee2" } Is there anything that I can do with this key using retrofit? I have tried using the header "Authorization" and following with the token. Here is my RestClient interface: public interface RestClient { @POST ("rest-auth/login/") Call<Token> login( @Body Login body ); @GET ("v2/users/{user}/") Call<List<CustomUser>> getUser( @Header("Authorization") String token, @Path("user") String user ); Here is the AsyncTask which will perform the requests to the server. The authenticateUser gives me an HTTP response of 200, but the syncUser gives 403. public class ActionSync extends AsyncTask<String, Void, Boolean> { RestClient client; IData activity; private static String token; public ActionSync(Context context) { activity = (IData) context; } @Override protected Boolean doInBackground(String... params) { Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("http://" + params[2] + ":" + params[3] + "/") .addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.build(); client = retrofit.create(RestClient.class); //Authenticate the user. authenticateUser(params[0], params[1]); //Once … -
Django form wizard: Operational error: cursor "..." does not exist
I can't figure out what to do with this error: OperationalError at /nehnutelnosti/vytvorit/ cursor "_django_curs_140105188636416_1" does not exist Couple lines below I see this: The above exception (column nehnutelnosti_lokalita.krajina_id does not exist LINE 1: ...TH HOLD FOR SELECT "nehnutelnosti_lokalita"."id", "nehnuteln... ^ HINT: Perhaps you meant to reference the column "nehnutelnosti_lokalita.krajina". ) was the direct cause of the following exception: I use django-formtools wizard to create an object in multiple steps. This error is being raised after second step (when sending data from LokalitaCreationForm). MINIMAL EXAMPLE OF THE VIEW: class NehnutelnostCreateView(SessionWizardView): # TODO loginrequired atd form_list = [DruhNehnutelnostCreationForm, LokalitaCreationForm, NehnutelnostCreationForm, BytProfileCreationForm] model = Nehnutelnost TEMPLATES = {"0": "nehnutelnosti/creation_wizard/druh.html", "1": "nehnutelnosti/creation_wizard/lokalita.html", "2": "nehnutelnosti/creation_wizard/nehnutelnost_base.html", "3": "nehnutelnosti/creation_wizard/nehnutelnost_spec.html"} I suppose that the problem is with second form LokalitaCreationForm which is a ModelForm. Lokalita model has a foreign key ForeignKey('Krajina') which is migrated and should work correctly. class LokalitaCreationForm(BootstrapFormControlMixin, forms.ModelForm): class Meta: model = Lokalita exclude = ['id'] model Nehnutelnost has ForeignKey('Lokalita'...) -
regular expression in urls. py in django 2.0
How can I write these two urls including their regular expression in django 2.0? Huge thanks. url(r'^page/(?P<id>\S+_[0-9]{3,})', views.pageinfo, name="page"), url(r'^something/(?P<id>\S+)/', views.jsoninfo, name="testinfo2"), -
Select options in form will not show using Django
So I am trying to show a dropdown menu with Django 2.x (latest version) for an ecommerce site that allows you to select the quantity of an item before adding to cart but the quantity form is not showing. I have a shop app and a cart app and the form is in the cart app. Here is what it looks like: No quantity drop down menu is showing How do I get it to show? html <form action="{% url "cart:cart_add" product.id %}" method="post"> {% csrf_token %} {{ cart_product_form }} <input type="submit" value="add to cart" class="btn btn-primary"> </form> Here is what the dev tools looks like: Dev Tools for the form I think it may have something to do with my css / javascript in the header that I extend because when I don't extent the header the drop down menu loads. How can I fix this? I am using MDBootstrap and here is what my css and javascript links look like in the header: css js -
Calculate no of matches for __in or __contains lookup in Django
I'm trying to build a recommendation engine and one of the sub-task is to rank Venues on the basis of tags matched in from a list of tags available. I could do a __contains lookup in the filter to fitler the venues where some of the tags from the list already exists. But my motive is to also somehow know how many tags are matched for each venue so that I can allocate some rank to them. For example, give a rank of 10 for each matched tag. Here are my models: class Venue(TimeStampedUUIDModel): name = models.CharField(max_length=100, null=False, blank=False) tags = ArrayField( models.PositiveIntegerField( verbose_name=_('tag'), choices=TAGS_CHOICES ), null=True, blank=True ) Since tags is an ArrayField which can only contain choices defined by positive numbers, __contains lookup works in the filter query, but how can I annotate the no of matches? End result can be something like: venue_queryset.filter(tags_contains=tag_list).annotate(no_of_tags_matched=...) Please let me know if more information is needed. -
Django: Authorization using query parameters
I'm writing a chat app where registered users can send messages to each other. One of the components of this is a Django-based Messaging microservice, which has an API for sending and receiving messages. For simplicity, there are only two URLs: # List all messages in Thread "thread_id" GET /threads/<int:thread_id>/messages/?user_id=123 # Send a message as user "user_id" to Thread "thread_id" POST /threads/<int:thread_id>/messages/?user_id=123 This service is only visible internally, so there's no potential for spoofing user_ids. Authorization is based on user_id, which is passed to the service as a query param and processed like so: views.py: class MessagesViewClass(django.views.View): def get(request, thread_id): # If this user is not part of this thread user_id = request.GET.get('user_id') if this_user_not_part_of_this_thread(user_id, thread_id): raise Some403Exception() else: process_response_normally() Right now, I'm validating via a query parameter. Is there a more conventional or canonical way of handling authorization of this type? -
static file issue causing django 500 error?
I am using angular heroku and django. I have been noticing that when I use 'ng build' to build new static files to add to django then push to heroku, the heroku instance is showing a website that is several versions behind what my current code is. I attempted to run my django local server today after doing ngbuild placing my files in the designated folder, running python manage.py collectstatic which it runs successfully. then I run my django server, navigate to my page and I get a 500 response. Because I am using angular, I have set up my django server as a rest backend. every endpoint the rest service uses starts with the url api/ so localdomain/api/ <-- restful service localdomain alone serves the angular app. I only receive the 500 sever error when I try and get the app served. Here are all my settings regarding static files: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', #angular distro root ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'frontend/dist/') #image distro root ASSETS_DIR = os.path.join(BASE_DIR, 'frontend/dist/assets/') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ #STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, … -
Django template variable in style tag
Can't seem to get a variable percentage width output in my Django tag. {% with "width: "|add:percent|add:"%" as percent_style %} <div class="percentile" style={% include percent_style %} /> {% endwith %} What am i doing wrong here? I get this error django.template.exceptions.TemplateDoesNotExist: % -
star ratings not working with turbolinks django
I just finished implementing star ratings into my django app and turbolinks is preventing the ability to rate posts. It just clicks out to a dead link - example: ratings/17/24/?return=/post/post.id/ When I refresh the post page it works just fine. I followed instructions from jquery turbolinks repo but still having the same issues. Any tips would be appreciated. -
make a button that will run .py
I'm making a website that will take 2 input files and return the differences between those file as an output. I already made the textcompare program in python and the first two webpages that will take the uploaded files and store it in one folder with the textcompare.py The last webpage that i'm having problem with has only one button that says execute. The main idea behind this button is when I click it, it will run textcompare.py, the program produces an output, then it will send it to the user to download it. Problem is, I dont know how to define a class that will run textcompare .py. I'm new to python and django so thanks for bearing with me. In the execute.html I have {% extends 'base.html' %} {% load static %} {% block content %} <div> <form action= '{% url my_view_name%}' method="POST"> <input type="submit" value="Execute" id="Execute" /> </form> </div> {% if uploaded_file_url %} {% endif %} {% endblock %} In the views.py I have from django.shortcuts import render, redirect from django.conf import settings from django.core.files.storage import FileSystemStorage from uploads.core.models import Document from uploads.core.forms import DocumentForm def home(request): documents = Document.objects.all() return render(request, 'core/home.html', { 'documents': documents }) … -
How to set a default field in my class for make a migration to my sqlite db at Django Rest?
I have issues when I'm trying to execute the following code at ubuntu terminal: $ python manage.py makemigrations I need to add a field called 'album' in my class named music, like that: models.py file -- coding: utf-8 -- from future import unicode_literals from django.db import models Create your models here. class Music(models.Model): class Meta: db_table = 'music' title = models.CharField(max_length=200) seconds = models.IntegerField() album = models.ForeignKey('Album', related_name='musics') def __str__(self): return self.title class Album(models.Model): class Meta: db_table = 'album' title = models.CharField(max_length=200) band = models.ForeignKey('Band', related_name='albuns') date = models.DateField() serializers.py file from rest_framework import serializers from .models import Music, Band, Album, Member class MusicSerializer(serializers.ModelSerializer): class Meta: model = Music fields = '__all__' class BandSerializer(serializers.ModelSerializer): class Meta: model = Band fields = '__all__' My error obtained: (music) leonardo.oliveira@dss-skinner:~/django_music/myapi$ python manage.py makemigrations You are trying to add a non-nullable field 'album' to music without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 2 -
how to use Ajax success function store data in database?Django
I want to get data(user) from dropdown by using Ajax success function. I want when clicking 'add member',it will show username under the button,and also the username will stay when refreshing the page. {% block script %} var url = $( '#selection-button' ).attr( 'action' ); $("#selection-button").on('click', function(e) { e.preventDefault(); var value =$('#member_list').val(); $.ajax({ type:'POST', url: '{% url 'project:project_add_member' project_id=project_id %}', data: { user_id:value }, success:function (result) { $("#res").append(value); }, error:function (result) { alert('error'); console.info(data); } }); }); {% endblock %} -
Django select multiple objects
I have a set of community objects defined by the following model: class Community(models.Model): name = models.CharField(max_length=20, unique=True) banner = models.ImageField(upload_to="communityBanners", blank=True) creation_date = models.DateTimeField(default=timezone.now) I've made it so that users are able to create new communities. However, I want to also make it so that other users can go to a multiple choice form and select which communities they want to join, then hit submit and store the preferences. Since the communities are objects, how do I create a multiple choice object field and form that they can select those? I'm under the impression that ModelChoiceField will not work here since I want to be able to select one, all, or any number in between of objects.