Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view fetching data
I have two tables in my database which are relevant for this problem: exercise_state with following fields: id | intensity_level | progress | exercise_id | user_id | current_date | user_rating auth_user with following fields: id | password | last_login | is_superuser | username | first_name | last_name | email | is_staff | is_active | date_joined Right now I am fetching some data in my view as follows: def get_specific_exercise_finish_count(request, exerciseId): # Number of users who completed a specific exercise specific_exercise_finish_count = Exercise_state.objects.filter(exercise_id=exerciseId, intensity_level=7).count() data = {} data['count'] = specific_exercise_finish_count return JSONResponse(data) Now I want to filter those results further for specific set of usernames i.e. usernames those starts with 'yg_' (I have two sets of usernames registered in my system one group starts with 'yg' and the other with 'yg_'). As username is not a field of exercise_state, I am not sure how to proceed. How can I achieve this? -
Customize username and password field in Django?
First, How can I set min_length for username? ChachaUser._meta.get_field('username').min_length = 2 doesn't work. Second, How can I place placeholder for password1 and password2? forms.PasswordInput(attrs={'placeholder' : "6μ리 μ΄μ"}), doesn't work. This is my customized User model and UserCreationForm. models.py from django.core.validators import RegexValidator from django.contrib.auth.models import AbstractUser from django.db import models GENDER_CHOICES = ( ('M', 'λ¨'), ('F', 'μ¬'), ) phone_regex = RegexValidator( regex=r'^\d{11}$', message=" '-' μμ΄ μ λ ₯ν΄μ£ΌμΈμ", ) username_regex = RegexValidator( regex=r'^[0-9a-zA-Z]*$', message='μμ΄λλ μμ΄μ μ«μλ‘λ§ κ΅¬μ±λμ΄μΌ ν©λλ€.' ) class ChachaUser(AbstractUser): birth = models.DateField("μλ μμΌ") name = models.CharField( "μ΄ λ¦", max_length=4 ) gender = models.CharField( "μ± λ³", max_length=1, choices=GENDER_CHOICES, default='M' ) phone_number = models.CharField( "νΈλν°", validators=[phone_regex], max_length=11 ) job = models.CharField( "μ§ μ ", max_length=20, ) # python manage.py createsuperuser ν λ λμ€λ νλͺ© REQUIRED_FIELDS = [ 'birth', 'name', 'gender', 'phone_number', 'job', 'email' ] ChachaUser._meta.get_field('username').verbose_name = 'μμ΄λ' ChachaUser._meta.get_field('username').validators = [username_regex] ChachaUser._meta.get_field('username').max_length = 20 ChachaUser._meta.get_field('username').min_length = 2 forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model class MyUserCreationForm(UserCreationForm): birth = forms.DateField( label="μλ μμΌ", widget=forms.SelectDateWidget( years=range(1970, 2015) ), ) class Meta(UserCreationForm.Meta): model = get_user_model() fields = UserCreationForm.Meta.fields + ( 'name', 'gender', 'birth', 'phone_number', 'job', ) exclude = ('email', ) widgets = { 'username' : forms.TextInput( attrs={'placeholder': 'μνλ²³, μ«μλ§ κ°λ₯(20μ μ΄λ΄)'} ), 'phone_number' : β¦ -
how to pass value in url in Django?
i need to pass the parameter for the search page to the check out page, like the url used in Airbnb. in the last search page, you input the new york and check in and check out date, the value will pass one page by one page. how to do that in Django? https://www.airbnb.com/s/New-York--NY?guests=1&checkin=08%2F31%2F2016&checkout=09%2F21%2F2016&ss_id=2kt1xthw&ss_preload=true&source=bb&s_tag=aL03a8ai -
Django ImportError: ImportError: No module named 'sheets'
I'm stuck with this error for one on my app : Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/usr/local/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.5/site-packages/django/apps/config.py", line 142, in create app_module = import_module(app_name) File "/usr/local/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 956, in _find_and_load_unlocked ImportError: No module named 'sheets' My config file is : LOCAL_APPS = ( # custom users app 'sorbetcitron.users.apps.UsersConfig', # Your stuff: custom apps go here 'sorbetcitron.sheets.apps.SheetsConfig', 'sorbetcitron.cashflows.apps.CashflowsConfig', ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS And my project directory is: What I don't get is that I have no problem with my second app named "cashflows". -
Django Admin Interface design is different
The django version is 1.9.2. I have my website on two different servers ( the same website) the problem is that the Django admin interface on the first server is different from that on the second here are some screenshots of the two copies of the admin website -
how to dynamically load css names into django templates without cluttering the view
I have a django app and I retrieve there "theme" value from memcached in views.py and pass it to several templates. What I've achieved is to be able to switch jqueryui theme of various templates system-wide. Here is an example of the template: <link rel="stylesheet" href="{% static "jquery-ui-1.11.4/themes/"%}{{theme}}/jquery-ui.css"> The problem is that I need to retrieve and pass the theme for various view end points and if I forget to do it for one of them, then pf course the theme will not be found. Is there a better way? Maybe using template tags? -
AttributeError: 'unicode' object has no attribute 'regex' while upgrading Django from 1.7.11 to 1.9.2
I'm working with the "third_party" example project of pybb (https://github.com/hovel/pybbm) [test folder] which works fine in django 1.7.11 but I've built the rest of my website in django 1.9.2. It gives me the following traceback in 1.9.2 and I'm not able to figure out whats wrong. Unhandled exception in thread started by <function wrapper at 0x032FB6B0> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver. py", line 116, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 10, in c heck_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 27, in c heck_resolver warnings.extend(check_pattern_startswith_slash(pattern)) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 63, in c heck_pattern_startswith_slash regex_pattern = pattern.regex.pattern AttributeError: 'unicode' object has no attribute 'regex' If it helps: My urls.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals try: from django.conf.urls import patterns, include, url except ImportError: from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from .forms import SignupFormWithCaptcha admin.autodiscover() from account.views import ChangePasswordView, SignupView, LoginView urlpatterns = ['', url(r'^admin/', include(admin.site.urls)), # aliases to match original django-registration urls url(r"^accounts/password/$", ChangePasswordView.as_view(), name="auth_password_change"), url(r"^accounts/signup/$", SignupView.as_view(form_class=SignupFormWithCaptcha), name="registration_register"), url(r"^accounts/login/$", LoginView.as_view(), name="auth_login"), url(r'^accounts/', include('account.urls')), url(r'^captcha/', include('captcha.urls')), url(r'^', include('pybb.urls', namespace='pybb')), ] β¦ -
Identifying primary key for a vote table
I am working on a voting table design using Postgres 9.5 (but maybe the question itself is applicable to sql in general). My vote table should be like: ------------------------- object | user | timestamp ------------------------- Where object and user are foreign keys to the ids corresponding to their own tables. I have a problem identifying what actually should be a primary key. I thought at first to make a primary_key(object, user) but since I use django as a server, it just doesn't support multicolumn primary key, I am not sure either about the performance since I may access a row using only one of those 2 columns (i.e. object or user), but the advantage this idea works automatically as a unique key since the same user shouldn't vote twice for the same object. And I don't need any additional indexes. The other idea is to introduce an auto or serial id field, I really don't think of any advantage of using this approach especially when the table gets bigger. I need also to introduce at least a unique_key(object, user) which adds to the computational complexity and data storage. Not even sure about the performance when I select using one of β¦ -
DRF Serializer Nested Field for User Creation
So I have a custom model - Profile, which has a OneToOne relation with a django User object. class Profile(models.Model): user = OneToOneField(User, on_delete=models.CASCADE) profile_type = models.CharField() I want to make a django rest framework serializer which allows for creation of creation and retrieval of a User object's nested attributes as well as the "profile_type" attribute. I want the names to be specified on the POST request as simply as "username", "password", "email", etc. - instead of "profile_username", "profile_password", ... So far I have class ProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(source='profile_user_username') password = serializers.CharField(source='profile_user_password') email = serializers.CharField(source='profile_user_email') class Meta: model = Profile fields = ('id', 'profile_user_username', 'profile_user_password', 'profile_user_email', 'username', 'password', 'email') depth = 2 But - I've been getting an error: ImproperlyConfigured: Field name 'profile_user_username' is not valid for model 'Profile' Am I getting the syntax for nested fields wrong? Or is it something else? -
Django Form with Foreign Key Related Data
I am having some issues with having my form have the user select a value rather than typing it into a text box. I am trying to create a tool checkout transaction, which requires the ToolID, Quantity of the tool checked out, and the PartyID. I would like to let the user be able to see a list of the users First and Last Names rather than select the PartyID. The First and Last Names are required but when I make a form containing those fields it gives me a text box for input. I believe I would rather have the user select the desired user from a drop down option. Any help would be appreciated. Models: class Party(models.Model): PartyID=models.AutoField(primary_key=True, db_column='PartyID') FirstName=models.CharField(max_length=100, null=False) LastName=models.CharField(max_length=100, null=False) PhoneNumber=models.CharField(max_length=25, null=False) Organization=models.CharField(max_length=100, null=True) Deleted=models.BooleanField(default=0) objects=models.Manager() class Meta: managed=True db_table='Party' def __unicode__(self): return str(self.PartyID) def get_absolute_url(self): return reverse("ToolSearch:borrowerUpdate", kwargs={"pk": self.PartyID}) class ToolTransaction(models.Model): CheckOutID=models.AutoField(primary_key=True) ToolID=models.ForeignKey(Tool, db_column='ToolID', on_delete=models.CASCADE,) PartyID=models.ForeignKey(Party, db_column='PartyID', on_delete=models.CASCADE,) Quantity=models.IntegerField(null=False) CheckOutDate=models.DateField(null=False, default=datetime.datetime.now) CheckInDate=models.DateField(null=True) Deleted=models.BooleanField(default=0) objects=ActiveTransactionManager() #objects=models.Manager() class Meta: managed=True db_table='ToolTransaction' ordering=('CheckOutID',) def __unicode__(self): return str(self.CheckOutID) def get_absolute_url(self): return reverse("ToolSearch:toolCheckin", kwargs={"pk": self.CheckOutID}) class Tool(models.Model): ToolID=models.CharField(max_length=100, primary_key = True, unique=True, db_column='ToolID') Quantity=models.IntegerField(null=False) Location=models.CharField(max_length=100, null=False) CategoryID=models.IntegerField(null=True) Deleted=models.BooleanField(default=0) objects=models.Manager() class Meta: managed=True db_table='Tool' def __unicode__(self): return self.ToolID def get_absolute_url(self): β¦ -
Django NoReverseMatch wrong number of arguments
I am getting a NoReverseMatch error after having added a new argument to one of my URLs. Initially, the URL in urlpatterns had been url(r'^(?P<myID>[0-9]+)/go/(?P<otherID>[0-9]+)/$', views.go, name='go') and this worked. I changed it to url(r'^(?P<myID>[0-9]+)/go/(?P<listID>[0-9]+)/(?P<otherID>[0-9]+)/$', views.go, name='go') and updated the function go in views.py to accept another argument (def go(request,myID,listID,otherID):#...). The new argument is not being recognized. When I try to go to my_app/18/go/14/12/ (for example) from my local server it gives the error Reverse for 'go' with arguments '(18, 12)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['frackr/(?P[0-9]+)/go/(?P[0-9]+)/(?P[0-9]+)/$'] So it seems that it does not recognize the listID argument. However, the debugging message says that one of the local variables in the view function is listID with the value of u'14'. So the problem does not seem to be coming from interpreting the URL. I have looked through tons of questions already to try to figure this out, but no one seems to have the same problem. And I realize this is probably a beginner's mistake, but any help would be greatly appreciated. -
django register multiple admin link to each other
Hi im still new to django. im planning to create an admin where i can add a Quiz,Question and choice. a Quiz has a Question and a Question has a choice. I can only do (Quiz and Question) and (Question and Choice). here is my model. class Quiz(models.Model): quiz_title = models.CharField(max_length=200) created_date = models.DateTimeField('date created') expired_date = models.DateTimeField( null=True, blank=True) def __str__(self): return self.quiz_title class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) answer = models.CharField(max_length=200,blank=True) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return self.choice_text class UserSession(models.Model): #for future use. user = models.ForeignKey(User) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) user_answer = models.CharField(max_length=200) and here is my admin from django.contrib import admin # Register your models here. from .models import Choice, Question, Quiz class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionInline(admin.TabularInline): model = Question extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date Information', {'fields': ['question_text'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_filter = ['question_text'] search_fields = ['question_text'] list_display = ('question_text',) class QuizAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['quiz_title']}), ('Date Information', {'fields': ['created_date'], 'classes': ['collapse']}), ] inlines = [QuestionInline] list_filter = ['created_date'] search_fields = ['quiz_title'] list_display β¦ -
How to use foriegn key api in django?
I am building a simple django site, and am trying to get all the list of comments related to a particular post. Thank you -
Download link for database in Django
I want to put a link in my Django app to download app's data from MySQL server as .csv format. Is there any easy way to do that? -
Heroku/python failed to detect set buildpack
I'm a Django newbie, I created an app and want to deploy it using Heroku. However, when I do git push heroku master (I follow Heroku's getting started), this is what I got: Counting objects: 36, done. Delta compression using up to 4 threads. Compressing objects: 100% (33/33), done. Writing objects: 100% (36/36), 19.22 KiB | 0 bytes/s, done. Total 36 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Failed to detect set buildpack https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to dry-waters-63931. remote: To https://git.heroku.com/dry-waters-63931.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/dry-waters-63931.git' My root directory: βββ assignment βββ household_management (django app) βββ templates | βββ db.sqlite3 | βββ manage.py I will be very appreciated if you guys can help. I'm really depressed right now... -
How to add a field to admin without using inlines?
Inlines provide additional block of fields at the bottom of admin page. I need just one field user that I want to be displayed in the main block of admin page, i.e. among other fields of Gallery model). # models from photologue.models import Gallery from profiles.models import UserProfile class GalleryExtended(models.Model): gallery = models.OneToOneField(Gallery) user = models.ForeignKey(UserProfile, verbose_name=_('user'), on_delete=models.CASCADE) def __str__(self): return self.gallery.title # admin from django import forms from django.contrib import admin from photologue.admin import GalleryAdmin as GalleryAdminDefault from photologue.models import Gallery from .models import GalleryExtended class InlineGalleryExtendedAdmin(admin.TabularInline): model = GalleryExtended class GalleryAdminForm(forms.ModelForm): class Meta: model = Gallery exclude = ('description', ) class GalleryAdmin(GalleryAdminDefault): form = GalleryAdminForm save_on_top = True inlines = [InlineGalleryExtendedAdmin] # Do not want to use inlines I tried to add to class GalleryAdmin: fields = ('user',) # also tried to add to fieldsets def user(self, instance): return instance.galleryextended.user but it does not work. It works just for list_display, i.e.: list_display = ('user',) -
Django TypeError: allow_migrate() got an unexpected keyword argument 'model_name'
So I copied over my Django project to a new server, replicated the environment and imported the tables to the local mysql database. But when I try to run makemigrations it gives me the TypeError: allow_migrate() got an unexpected keyword argument 'model_name' This is the full stack trace: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/base.py", line 353, in execute self.check() File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models errors.extend(model.check(**kwargs)) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/base.py", line 1266, in check errors.extend(cls._check_fields(**kwargs)) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/base.py", line 1337, in _check_fields errors.extend(field.check(**kwargs)) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 893, in check errors = super(AutoField, self).check(**kwargs) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 208, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 310, in _check_backend_specific_checks if router.allow_migrate(db, app_label, model_name=self.model._meta.model_name): File "/home/cicd/.local/lib/python2.7/site-packages/django/db/utils.py", line 300, in allow_migrate allow = method(db, app_label, **hints) TypeError: allow_migrate() got an unexpected keyword argument 'model_name' I would appreciate any help in debugging this error and trying to understand what is causing this error. -
How to queue asynch tasks sharing the same background thread
On a Linux server (running Ubuntu), I have an asynchronous task that compresses/encodes videos uploaded by users on a certain Django web application. This task takes around 120s on average. I'm a newbie in the web stack and don't have a lot of experience in it. I'm worrying that if two users simultaneously call the asynch video compression task, one will over-ride the other (this would happen if a single background thread was being used). How does one go about checking whether the above holds true? Secondly, if indeed one task is being blocked by the other, how can I ensure some kind of queuing to happen here? Please give me guidance, preferably with an illustrative example. -
Formating Django TimeField in a Django view
How do you format a TimeField in a Django view? Currently in my django html template I can easily do something like: {{movie.start_time|time:"g:iA"|lower}} How can I do the equivalent of the above in a Django view? -
Couldn't import Django error when I try to startapp
I usually work on PC's but started to work on projects on my mac. I run Python 3 and when I started a new project I did the following: 1) In main project folder, installed virtualenv and activated it. 2) Install Django and Gunicorn 3) Did startproject When I try to python3 manage.py startapp www I get an error that Django could not be imported. Below is what was in the terminal: (venv) AB:directory AB$ pip freeze Django==1.10 gunicorn==19.6.0 (venv) AB:directory AB$ ls directory manage.py (venv) AB:directory AB$ python3 manage.py startpap www Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ImportError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Gunicorn with unix socket not working gives 502 bad gateway
I'm following the http://www.obeythetestinggoat.com/book/chapter_08.html book, and it says to add a unix socket to run nginx server with gunicorn, which i did. This is my nginx file server { listen 80; server_name superlists-staging.ottg.eu; location /static { alias /home/elspeth/sites/mydjsuperlist-staging.tk/static; } location / { proxy_set_header Host $host; proxy_pass http://unix:/tmp/mydjsuperlist-staging.tk.socket; } } Nginx reloads without any failure and checked it with nginx -t When i run: gunicorn --bind unix:/tmp/mydjsuperlist-staging.tk.socket superlists.wsgi:application It succesfully creates mydjsuperlist-staging.tk.socket file in tmp folder and i get this on my terminal 2016-09-01 18:56:01 [15449] [INFO] Starting gunicorn 18.0 2016-09-01 18:56:01 [15449] [INFO] Listening at: unix:/tmp/mydjsuperlist-staging.tk.socket (15449) 2016-09-01 18:56:01 [15449] [INFO] Using worker: sync 2016-09-01 18:56:01 [15452] [INFO] Booting worker with pid: 15452 Everything seems fine, but when i go to my site mydjsuperlist-staging.tk it gives a (502) bad gateway error. When i was using a port my site was running perfectly. What am i doing wrong over here ? -
Advance filtering with list of elements using django tastypie
I am using MultiSelectField to select multiple choices within my django admin it creates an array for fields in the backend of all the choices I select. I then use django tastypie's List Field to make sure its a list of elements the api returns. My problem is as I am building the filter when I put /api/?brand_category=Clothing&q=athletic,bohemian in the browser it does not return anything but an empty list. So I want to know if I am doing something wrong? Or not building my filters correctly? models.py class Brand(models.Model): # category brand_category = MultiSelectField(max_length=100, blank=True, choices=categories)) # style brand_style = MultiSelectField(max_length=100, choices=styles, blank=True) api.py class LabelResource(ModelResource): brand_category = fields.ListField(attribute='brand_category') brand_style = fields.ListField(attribute='brand_style') class Meta: filtering = { "brand_category": ALL, "brand_style": ALL, "q": ['exact', 'startswith', 'endswith', 'contains', 'in'], } def build_filters(self, filters=None): if filters is None: filters = {} orm_filters = super(LabelResource, self).build_filters(filters) if('q' in filters): query = filters['q'] qset = ( Q(brand_style__in=query) ) orm_filters.update({'custom': qset}) return orm_filters def apply_filters(self, request, applicable_filters): if 'custom' in applicable_filters: custom = applicable_filters.pop('custom') else: custom = None semi_filtered = super(LabelResource, self).apply_filters(request, applicable_filters) return semi_filtered.filter(custom) if custom else semi_filtered JSON Response { "brand_category": [ "Clothing" ], "brand_style": [ "athletic", "bohemian", "casual" ] } -
How do I send a JavaScript confirm response over Django to a script to perform operations based on the response?
I'm very very new to Django and I'm currently trying to build a simple To-Do application. I'm currently able to display my To-Do list on the webpage using HTML Tables, but to be able to delete it, I added a new row at the end of every entry called "Delete" with an a href element, on click event sending it to a JS function that pops up a confirmation to the user asking if he actually wants to delete it. I'm storing the response in a variable called response. Now, my question is how do I send this response across django to actually be able to delete the entry? This is what I have done so far and its not working. All help will be appreciated. Thank You. {% for item in task %} <tr> <td>{{ item.task_name }}</td> <td>{{ item.task_priority }}</td> <td>{{ item.task_status }}</td> <td>{{ item.target_date }}</td> <td><a href="" onclick="return delete_function()">Delete</a></td> <p id="delete"></p> </tr> {% endfor %} </table> <script> function delete_function() { var response = confirm("Are you sure you want to delete this item?"); if (response == true){ response.post() } } </script> In my views page, I have this function to handle this post method: def view_task(request): if request.method == β¦ -
AngularJS and CMS
If I built a web app using AngularJS and also want to use Django as a CMS, how do the 2 integrate? For example if I built a site search app using AngularJS how would I integrate the AngularJS searchApp with the Django CMS? AngularJS has UI Router to manage navigation(urls), states, url and query parameters etc. However, Django can manage that as well. So how do you integrate an AngularJS web app with Django CMS. I built both independently and now am not quite sure how to integrate the two? -
Can't delete/modify model permissions
So I have a django model with custom permissions added to it. class TestModel(models.Model): class Meta: permissions = ( ("test_permission1", "Test permission 1"), ("test_permission2", "Test permission 2"), ) I wanted to modify/deleted those existing permissions. So I updated the model to the following: class TestModel(models.Model): class Meta: permissions = ( ("test_permission1", "Updated description"), ) I ran the migration (which detected the changes). But both permissions remain in the database and admin site unchanged / unremoved. Is it not possible to remove/modify a permission once it has been created? (I'm running Django 1.9.1 w/ psql 9.5.3)