Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My virtual environment is having access to global packages
I have virtualenv 15.1.0 installed. The problem is that when I create a virtual environment with virtualenv venv and then activate it, it will have access to packages installed globally (django-admin for example). This happens although it is mentioned in virtualenv reference guide here that: Not having access to global site-packages is now the default behavior. Also, I want to mention that running pip3 freeze while the virtual environment is activated prints nothing. -
Django Haystack: is there a way to search in choices representation of a field that has choices as model field options?
I have a model that has choices as options for a field. class TMSDeviceSetting(models.Model): PULSE_STIMULUS_TYPES = ( ("single_pulse", "Single pulse"), ("paired_pulse", "Paired pulse"), ("repetitive_pulse", "Repetitive pulse") ) tms_setting = models.OneToOneField(TMSSetting, primary_key=True, related_name='tms_device_setting') tms_device = models.ForeignKey(TMSDevice) pulse_stimulus_type = models.CharField(null=True, blank=True, max_length=50, choices=PULSE_STIMULUS_TYPES) coil_model = models.ForeignKey(CoilModel) I'm using haystack/elasticsearch in my Django project. What I'd like to know is if I can make Haystack to search in the field choice representation: "Single pulse", "Paired pulse", "Repetitive pulse". My search index to this model is: class TMSDeviceSettingIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) tms_setting = indexes.CharField(model_attr='tms_setting__id') def get_model(self): return TMSDeviceSetting def index_queryset(self, using=None): experiments = Experiment.lastversion_objects.filter( status=Experiment.APPROVED ) tms_settings = TMSSetting.objects.filter(experiment__in=experiments) return self.get_model().objects.filter(tms_setting__in=tms_settings) -
Django CreateView: set user before validation
I have a model that uses different validation for its name field depending on whether the object was created by a user or by the system. class Symbol(models.Model): name = models.CharField(_('name'), unique=True, max_length=64) creator = models.ForeignKey('User', null=True, on_delete=models.CASCADE) def is_system_internal(self): """ whether or not this Symbol belongs to the system rather than having been created by a user """ return (self.creator is None) def clean(self): """ ensure that the Symbol's name is valid """ if self.is_system_internal(): if not re.match("^_[a-zA-Z0-9\-_]+$", self.name): raise ValidationError( _("for system-internal symbols, the name must consist of letters, numbers, dashes (-) and underscores (_) and must begin with an underscore."), params = { 'value' : self.name }, ) else: if not re.match("^[a-zA-Z][a-zA-Z0-9\-_]*$", self.name): raise ValidationError( _("the symbol name must consist of letters, numbers, dashes (-) and underscores (_) and must begin with a letter."), params = { 'value' : self.name }, ) I want to create a Form and a CreateView with which users can create the objects. When a user creates such an object, the user should be used as the value for the value of the 'creator' field. Currently it looks like this: class SymbolCreateForm(forms.ModelForm): name = forms.CharField(max_length=Symbol._meta.get_field('name').max_length, required=True) class Meta: model = Symbol fields … -
Archive MonthYear widget not working in django
I have an app in Django where I want to create an archive where events will be displayed. I want to filter the archive after a month and a year. Unfortunately, my solution does not work - we do not see the current events and there are no events before 2017. Please help. Here is my view: class BookingListView(ListView, FormView): model = models.Booking form_class = BookingForm queryset = models.Booking.objects.order_by('-date_start') paginate_by = 80 template_name = 'events/archive_list.html' context_object_name = 'object_list' date_field = 'date_start' allow_future = True success_url = '/' def get_context_data(self, **kwargs): context = super(BookingListView, self).get_context_data(**kwargs) context['form'] = BookingForm() return context Here is my url: url('^$', views.BookingListView.as_view(), name="list"), Here is my form: from django import forms from django.forms.extras.widgets import SelectDateWidget from archive.models import Booking class BookingForm(forms.ModelForm): date_start = forms.DateField(widget=SelectDateWidget()) class Meta: model = Booking fields = ('date_start', ) widgets = {'date_start': SelectDateWidget()} -
Django filtering objects by repeats in each month
I have a model like this: class Event(models.Model): user = models.CharField() event_date = models.DateTimeField() I want to get the user ids who have an event (or events) each month from the minimum event_date to the maximum event_date. Is this possible using Django aggregations? Or should I do it manually with a loop or something? -
django rest framework detail_route not working in get method
I defined a viewset using ModelViewSet as follow I tried to redefine the GET method to do something like getting something from celery . but this part of code just won't work , it acts just like a standard API and didn't do what I wrote in the get_job_detail function. How should I correctly define the "detail_route" function. views.py class JobViewSet(viewsets.ModelViewSet): queryset = job.objects.all() serializer_class = JobSerializer @detail_route(methods=['get']) def get_job_detail(self, request, pk=None): # print('these part wont proceed') job_item = self.get_object() if job_item.isReady or job_item.isSuccessful: return Response(self.serializer_class(job_item).data) celeryjob = sometask.AsyncResult(pk) celeryjob.get() if celeryjob.state == 'SUCCESS': job_item.state = celeryjob.state job_item.result = celeryjob.result job_item.isReady = True job_item.isSuccessful = True job_item.save() if celeryjob.state == 'FAILURE': job_item.state = celeryjob.state job_item.result = celeryjob.result job_item.isReady = True job_item.isSuccessful = False job_item.save() return Response(self.serializer_class(job_item).data) urls.py from django.conf.urls import url, include from apply_api import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'job',views.JobViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] -
multiple authentication backends configured and therefore must provide the `backend` argument or set the `backend` attribute on the user
first of i am new to django/python . i am trying to create a login website that allows the user to register an account and verify via email or directly login via fb or google(Oauth) i receive the error when i click on the validation url sent to the email. error: ValueError at /activate/Mjk/4p1-dcc5f7ed2e7c847fe362/ You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user. Request Method: GET Request URL: http://127.0.0.1:8000/activate/Mjk/4p1-dcc5f7ed2e7c847fe362/ Django Version: 1.11.3 Exception Type: ValueError Exception Value: You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user. Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/init.py in login, line 149 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/gaby/django projects/simple-signup-master/profile-model', '/usr/local/lib/python2.7/dist-packages/virtualenv-15.1.0-py2.7.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/gaby/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Wed, 30 Aug 2017 12:34:31 +0000 mysite/settings AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) this is the function being called when i receive the error def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() … -
Django render doesn't works with for loop but yes without it
I have been looking for this for a while and i didn't found any solution for my issue. I'm rendering with Django according next sentence: render(request, url, context). This is my problem: If I write manually de context of the render in the template: Manual template <p>Data starting...</p> <ul> <li>Data1</li> <li>Data2</li> <li>Data3</li> </ul> The webpage looks fine and every data is shown as I want because, obviously, the output after and before rendering is: <p>Data starting...</p> <ul> <li>Data1</li> <li>Data2</li> <li>Data3</li> </ul> But when I write a dynamic template to retrieve dynamic data, according next template's code: Dynamic template <p>Data starting...</p> <ul> {% for vdom in ioDict %} <li>{{ vdom }}</li> {% endfor %} </ul> The output BEFORE rendering is like in the manual example: <p>Data starting...</p> <ul> <li>Data1</li> <li>Data2</li> <li>Data3</li> </ul> But the output AFTER rendering is what follows: <p>Data starting...</p> <ul> </ul> ioDict is a dictionary like this: {'Data1':{...}, 'Data2':{}, 'Data3':{...}} Could someone help me? I'm really lost with this. Note: I've been using loops in others templates oof my proyect and there aren't issues on them Thanks, Mike. -
filter drop down data using model form according to selection of one drop down in django 1.11.2
I am working on a project where i have three models defined class Vendors(models.Model): user = models.ForeignKey(Users,null=True,) vendor_name = models.CharField(max_length=100, null=True, blank=True, default=None) store_name = models.CharField(max_length=100, null=True, blank=True, default=None) store_image = models.FileField(upload_to='store_pic/',null=True, blank=True, default=None) lat = models.DecimalField(max_digits=9, decimal_places=6, null=True) long = models.DecimalField(max_digits=9, decimal_places=6, null=True) auto_response = models.BooleanField(default=False) max_discount = models.CharField(max_length=100, null=True, blank=True, default=None) objects = VendorsManager() class Meta: verbose_name_plural = 'Vendors' def __unicode__(self): return str(self.vendor_name) class Dishes(models.Model): vendor = models.ForeignKey(Vendors,null=True) dish_name = models.CharField(max_length=100,null=True, blank=True,default=None) Description = models.CharField(max_length=250,null=True, blank=True,default=None) price = models.CharField(max_length=20,null=True, blank=True,default=None) # discount = models.CharField(max_length=20,null=True, blank=True,default=0) dish_image = models.FileField(upload_to='dish_pic/' ,null=True, blank=True, default=None) class Meta: verbose_name_plural = 'Dishes' def __unicode__(self): return str(self.dish_name) class Offers(models.Model): vendor_id = models.ForeignKey(Vendors,null=True) dish_id = models.ForeignKey(Dishes, null=True) discount = models.FloatField(null = True, default=None) per_discount = models.FloatField(null=True,blank=True,default=None) discounted_price = models.FloatField(null=True,default=None) offer_name = models.CharField(max_length=100,null=True,default=None) offer_description = models.CharField(max_length=100,null=True,default=None) class Meta: verbose_name_plural = 'Discounts' def __unicode__(self): return str(self.dish_id.dish_name) Now I am creating a create view for Offer model in which I want all the data in drop down for disk_id created using ModelForm in Offers model according to selected item in vendor_id in same form. My forms.py file code is as follows: class OffersForm(ModelForm): class Meta: model = Offers fields = [ 'vendor_id', 'dish_id', 'discount', 'per_discount', 'discounted_price', 'offer_name', 'offer_description', ] … -
Django: django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
A new migration, adding a single, simple table, gives me the error "Cannot add foreign key constraint" during migration. Here's an existing model, called EventLog: class EventLog(models.Model): """ The event log. """ user = models.ForeignKey(User, blank=True, null=True) timestamp = models.DateTimeField(auto_now=True) text = models.TextField(blank=True, null=True) ip = models.CharField(max_length=15) metadata = JSONField(default={},blank=True) product = models.TextField(default=None,blank=True, null=True) type = models.ForeignKey(EventType) def __unicode__(self): return "[%-15s]-[%s] %s (%s)" % (self.type, self.timestamp, self.text, self.user) def highlite(self): if self.type.highlite: return self.type.highlitecss return False Here is then the new model, which I'm trying to create: class EventLogDetail(models.Model): eventlog = models.ForeignKey('EventLog', related_name='details') order = models.IntegerField(default=0) line = models.CharField(max_length=500) class Meta: ordering = ['eventlog', 'order'] Seems simple enough, right? So I make the migration: ./manage.py makemigrations: Migrations for 'accounts': accounts/migrations/0016_eventlogdetail.py - Create model EventLogDetail So far, so good. Then, I migrate, like so: ./manage.py migrate: Operations to perform: Apply all migrations: accounts, admin, attention, auth, contenttypes, freedns, hosting, info, mail, sessions, sites, taggit, vserver Running migrations: Applying accounts.0016_eventlogdetail...Traceback (most recent call last): File "./manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) … -
Storing multiple select values in django
I am a fresher in Django. I was searching for a article or SO thread describing the way django stores multiselect list box values in the database but couldn't find one. In my case I have categories list box with options for example(C1,C2,C3). The category name can be a long one. I want to assign multiple categories to single user. It can be single category assigned to a user as well. My model will look like this(cat_name fiels depends on how it stores in the db) class Category(models.Model): user = models.ForeignKey(User) cat_name = models.CharField(max_length=100) #or cat_name = models.TextField() My question is how django will store the values in the db id user_id cat_name 1 1 C1&C2&C3 2 2 C1&C2 3 3 C3 Or id user_id cat_name 1 1 C1 2 1 C2 3 1 C3 4 2 C1 5 2 C2 6 3 C3 If it's the first case then I'll use TextField else CharField. & used in the first case is just an example. Any suggestion/link is highly appreciated. Thanks in advance. -
django CreateView class return to the Previous page
i have tow models in my models file: Project model Task model every project have a tasks and the user can see the project and click on it then it view the tasks i make the user able to update the task title but i want them to be redirect to the project detail again i know how if it was a function that update the task but i am using the class : class UpdateTask(UpdateView): ... success_url = ???? -
Python django error
am new to python and django I am trying to build a small python django application on my local windows laptop. i am not able to underlying tables required for my Django project as when i run "python manage.py syncdb" i get the below error ` Error :django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? ' And when i try running "pip install mysqlclient" i get the below error 'error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279' I am stuck in this step and not able to find any leads. can someone suggest any workaround -
How to generate multiple SVG plots dependent on incoming JSON
My end goal is to create something like this: The Timeseries shows total sales per department over time The slider (red) selects a month of interest that drives the radar plots The radar plot(generated for each Job Role) show the data for the specific month, broken out to show sales per department per Job Role (over time) My timeseries chart is working correctly (loading from a csv file). However, I am now stumped at how to: Dynamically generate as many SVGs as are required from the incoming JSON array. Have the eventual radar plots only plot the corresponding month of the passed JSON (according to the slider) My attempts so far have mostly be around trying to create new d3 objects pointing and appending to #svg-container-RadarPlots based on the below HTML skeleton: <body> <div class="container"> <div class="row" id="svg-container-RadarPlots"> <div class="col-md-4"> <svg class="center-block Junior"> <circle cx="150" cy="100" r="70"></circle> </svg> </div> <div class="col-md-4"> <svg class="center-block Senior"> <circle cx="150" cy="100" r="70"></circle> </svg> </div> <div class="col-md-4"> <svg class="center-block Manager"> <circle cx="150" cy="100" r="70"></circle> </svg> </div> </div> <div class="row" id="svg-container-TimeSeries"> <div class="col-lg-12"> <svg id="timeline" class="center-block" width="800" height="500"></svg> <input id="slider" type="range" min="1" max="20" step="1" value="10"/> </div> </div> </div> </body> The javascript/D3 code I have is based … -
Django auto increment value
I'm using Django models and I would like to get current value of auto increment field "id". I use this in my model class but still getting erros when I access with "userLog.id" id = models.AutoField(primary_key=True) SO, how can I know id value of my object ? Thanks -
Vue.JS on top of existing python/django/jinja app for filter and list render
I have an existing python/django app with jinja template engine. I have a template with a filter and a list the gets rendered correctly via server, also the filters work perfectly without javascript. (based on url with parameters) The server also responds with json if the same filter url is requested by ajax. So it's ready for an enhanced version. Now: I would like to make it nicer and update/rerender the list asynchronously when I change the filter based on the json response I receive. Questions: When I init the vue on top of the page template, it removes/rerenders everything in the app. All within the vue root element becomes white. Can I declare only parts of my whole template ( the one filter and the list) as separate vue components and combine these instances (there are other parts that are not part of the async update part vue should not take of) Can I somehow use the existing markup of my components in jinja to be used to rerender the components again with vue or do I have to copy paste it into javascript (please no!) ? TLDR: I don't wan't to create the whole model with vue and … -
Django custom form validation in ListView
I am using a ListView to set a form and to show results. However i am not sure how can I make form validation and having the same form with errors in case form.is_valid() is not True. this is my code forms.py class InsolventiForm(forms.Form): anno_validator = RegexValidator(r'[0-9]{4}', 'L\'anno deve essere un numero di 4 caratteri') anno = forms.CharField(label='Anno', required=True, max_length=4,validators=[anno_validator]) def clean_anno(self): anno = self.cleaned_data['anno'] return anno views.py from .forms import InsolventiForm class InsolventiView(LoginRequiredMixin, ListView): template_name = 'insolventi.html' model = Archivio form_class = InsolventiForm def get(self, request): import datetime if self.request.GET.get('anno'): form = self.form_class(self.request.GET) if form.is_valid(): date = '31/12/'+self.request.GET.get('anno') dateTime = datetime.datetime.strptime(date, "%d/%m/%Y") dateC = '01/01/'+self.request.GET.get('anno') dateTimeC = datetime.datetime.strptime(dateC, "%d/%m/%Y") context = Archivio.objects.filter(~Q(quoteiscrizione__anno_quota__exact=self.request.GET.get('anno')) \ & Q(data_iscrizione__lte=dateTime) \ & (Q(cancellato__exact=False) | (Q(cancellato__exact=True) & (Q(data_canc__gte=dateTimeC))))) self.request.session['insolventi_queryset'] = serialize('json', context) return render(request, self.template_name, {'form':form}) else: return redirect(reverse('insolventi')) return render(request, self.template_name, {'form':self.form_class()}) this is my template and I am displaying the form manually. insolventi.html <form method="get" action=""> {% for field in form %} {{ field.errors }} {{ field.as_widget() }} {% endfor %} <input type="submit" value="Ricerca" /> </form> Even if there are errors and form.is_valid() is returning False (giving me a redirect to the same view) on the template I never get {{ form.errors }}. … -
How to create a form in django that fill the fields on a related model
I Have a Model that have a OnetoOne relationship with django.contrib.auth.models auth. When i create one User Model i send a signal to the Profile Model wich is related to this User. Then the Profile Object is created, but i cant figure out how to fill the others fields of Profile Object. Eg. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Could some one help me? How can i fill these bio, location and birth_date on a form? Thanks. -
Django: assert 'Many-to-many' relation exists in test
I am writing tests for my project, but I've run into a problem when trying to verify the existence of a 'ManyToMany' relationship. The test concerns the following two models, that are linked together with a ManyToMany Models: class Project(models.Model): (...) linked_attributes = models.ManyToManyField(attributes, blank=True) class Attributes(models.Model): (...) class linked_projects = models.ManyToManyField(Project, blank=True) In my test I wanted to verify that the form created a new many to many relationship. I created the assert on the last line, based on some example code, but it doesn't seem to be working. Test: class ProjectTest(TestCase): (...) form_data = {'linked_attributes' : self.attribute} form = ProjectForm(data=form_data, project=self.project, instance=self.project) self.assertTrue(Project.attributes_set.filter(pk=self.Project.pk).exists()) Does anyone know what I am doing wrong? -
When overriding the reset_password template, it is being shown in the context of the admin panel
When overriding the reset_password template, it is being shown in the context of the admin panel. This is something I dont want. I want it to just be visualised. As plain HTML. I am registering it as follows: urlpatterns = [ ... url(r'^password_reset/$', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html')), ] This is the code of the form: {% extends "frontend/base.html" %} {% block content %} <form action="" method="post">{% csrf_token %} {% if form.email.errors %}{{ form.email.errors }}{% endif %} <p>{{ form.email }}</p> <input type="submit" class='btn btn-default btn-lg' value="Reset password" /> </form> {% endblock %} frontend/base.html is something that my other templates are are extending and are not shown as part of the admin panel. Here is a screenshot: EDIT: INSTALLED_APPS = [ 'waffle', 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend', 'blog', 'profiles' ] where the template is in profiles/templates/registration/ -
Preventing Mezzanine CMS from filtering the style tag
I am trying to insert style tags into RichText Pages, but despite specifying "RICHTEXT_FILTER_LEVEL" as 3 (no filtering) in "local_settings.py", the style tag is still filtered. Short of directly modifying the page content in my database, is there a way of properly turning off RichText filtering? -
Installating Django on Godaddy Deluxe with mysql as database (Linux Plan)
I am trying to setup the Django in GoDaddy. I have IP address say 123.154.12.152. The plan enables me to have multiple domains. so i have abc.com as primary domain(/public_html) and xyz.com as addon domain under it(/public_html/xyz/). To my knowledge, I believe that both share the same IP i managed to install virtual env with latest Python 3.6.2 and connect to the database(mySQL). the I have the SSH access. But I don't know how Django connect to xyz.com domain that I have in GoDaddy. Couldn't find any solution. Any help is really appreciated Thanks your time. -
filtering many to many relationship admin.py
I have three objects. in admin.py i have instaled the three models. I wish when i add a new room, the field "img_galery", only show the images related with the hotel i am adding a new room. How can i filter the many to many, in django admin.py?. class Hotel(models.Model): name = models.CharField(max_length=30, blank=True, null=True) class Room(models.Model): hotel = models.ForeignKey(Hotel) name = models.CharField(max_length=20, blank=True, null=True) img_galery = models.ManyToManyField(Images) class Images(models.Model): hotel = models.ForeignKey(Hotel) name = models.CharField(max_length=30, blank=True, null=True) img = models.FileField(upload_to="front/img_hotels/", blank=True, null=True) -
JavaScript - Front-end MVC
My actual question here: I'm wondering if (beargrylls.com) uses Django or it's packages. Or some other framework. Or a custom framework? Also, if you take a look at the website (beargrylls.com), you can see that it uses a lot of paralax scrolling, sliders and cool animations. Is this custom-made or is this another framework/plugin/whatever? If found an awesome website (beargrylls.com) on awwwards.com. I'm familiar with the MVC model that Laravel uses. So I know the basics. But I found out that (beargrylls.com) uses some kind of routing inside it's scripts!? What I also found remarkanble is that the script(s) and the entite css of the website is loaded in inline HTML. So there are no HTTP requests, no files to load except the images Which framework/plugin compiles this? Example: , Route = function t() { classCallCheck(this, t); var e = new Router({ xhr: !0 }); e.get("/", HomeController), e.get("/about", AboutController), e.get("/television", TelevisionController), e.get("/live", LiveController), e.get("/experiences", ExperiencesController), e.get("/socialwall", SocialwallController), e.get("/adventurers", AdventurersController), e.get("/termsofuse", TermsofuseController), e.get("/faqs", FaqsController), e.get("/signup", SignupController), e.error(ErrorController), e.run() } , App = function t() { classCallCheck(this, t), Support.init(), index.TopWhenRefresh(), new Route }; new App; Another example that boosted my suspisions can be found inside it's createClass function or class. Where it … -
django forms min and max selection in ModelMultipleChoiceField
I have problem with determine min and max selection in ModelMultipleChoiceField used with widget CheckboxSelectMultiple. can some one help? my code in forms.py: class MyForm(forms.Form): def __init__(self, *args, **kwargs): extra = kwargs.pop("extra") super(MyForm, self).__init__(*args, **kwargs) for q in extra: if q.type == '1': self.fields['question_%s' % q.id] = forms.ModelMultipleChoiceField( queryset=q.answers.all().filter(is_active=True), label=q.text, required=q.is_required, widget=forms.CheckboxSelectMultiple(), # mix_length=3, # min_length=2, )