Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to execute Celery beat the second time
I am using Celery beat for getting the site data after every 10 seconds. Therefore I update the settings in my Django project. I am using rabbitmq with celery. settings.py # This is the settings file # Rabbitmq configuration BROKER_URL = "amqp://abcd:abcd@localhost:5672/abcd" # Celery configuration CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERYBEAT_SCHEDULE = { # Executes every Monday morning at 7:30 A.M 'update-app-data': { 'task': 'myapp.tasks.fetch_data_task', 'schedule': timedelta(days=1), }, celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # Indicate Celery to use the default Django settings module os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myapp') app.config_from_object('django.conf:settings') # This line will tell Celery to autodiscover all your tasks.py that are in # playstore folders app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app_keywords = Celery('keywords') app_keywords.config_from_object('django.conf:settings') # This line will tell Celery to autodiscover all your tasks.py that are in # keywords folders app_keywords.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app1 = Celery('myapp1') app1.config_from_object('django.conf:settings') # This line will tell Celery to autodiscover all your tasks.py that are in # your app folders app1.autodiscover_tasks(lambda: settings.INSTALLED_APPS) tasks.py @task(bind=True) def fetch_data_task(self, data): logger.info("Start task") import pdb;pdb.set_trace() # post the data to view headers, cookies = utils.get_csrf_token() requests.post(settings.SITE_VARIABLES['site_url'] + "/site/general_data/", … -
Parameter passed in save() difficult to understand
I am learning Django from a most recommended and beneficial book named 'Django By Example'. There is a project called Bookmark. I am now stuck in the forms part which is for downloading the image and saving image object to the database. I could understand validation part(clean_url) and also downloading part. I could not get into the parameter passed in to save() save(self, force_insert=False, force_update=False, commit=True) and saving image object image.image.save(image_name, ContentFile(response.read()), save=False) Where is force_insert and force_update been used in this function? Also i did not understand the parameter part in image.image.save() because image has field like title, url, description, image etc. What image_name is refering to? I think response.read() part is for image field. Could anyone please make me clear? Here is the code class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True) views.py def image_create(request): """ View for creating an Image using the JavaScript Bookmarklet. """ if request.method == 'POST': # form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_item = form.save(commit=False) # assign current user to … -
integrate gulp and bower with django for angularjs
I am new in django and I try configure angularjs template with django. Angularjs template uses gulp configration. So anyone please tell me that how I configure gulp with django to run Angularjs template ? Plaese suggest me tutorial or steps for this. -
Django reusable app testing failed: relation "auth_user" does not exist
I am currently working on a Django reusable app. One of my models need an OneToOneField class MyModel(TimeStampedModel): author = models.OneToOneField(settings.AUTH_USER_MODEL) When I run my runtest.py file that looks like the following: import os import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'openrecipe_db', 'USER': 'test_user', 'PASSWORD': 'mypassword', 'HOST': '', 'PORT': '', } }, ROOT_URLCONF="openrecipes.urls", INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "openrecipes", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() msg = "To fix this error, run: pip install -r requirements/development.txt" raise ImportError(msg) def run_tests(*test_args, **kwargs): if not test_args: test_args = ['tests'] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=kwargs.get('verbosity', 2)) failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == '__main__': run_tests(*sys.argv[1:]) Then I get the following error: $ python runtests.py Creating test database for alias 'default' ('test_openrecipe_db')... Operations to perform: Synchronize unmigrated apps: openrecipes Apply all migrations: auth, contenttypes, sites Synchronizing apps without migrations: Creating tables... Creating table openrecipes_recipemodel Creating table openrecipes_ingredientmodel Running deferred SQL... Traceback (most recent call last): File "/home/arch/.environments/openrecipes_dev/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) psycopg2.ProgrammingError: relation "auth_user" does not exist The … -
You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth
I've just created Django project and ran server. It works fine but showed me warnings like You have 14 unapplied migration(s)... Then I ran python manage.py migrate in the terminal. It worked fine but showed me this ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. And now I have this warning after starting my server. You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth. So how do I migrate correctly to get rid of this warning? I am using PyCharm and tried to create the project via PyCharm and terminal and have the same issue. ~$ python3.5 --version Python 3.5.2 >>> django.VERSION (1, 10, 1, 'final', 1) -
Keep browser history with django-el-pagination
Im using django-el-paginationhere to do lazy loading of entries. When I click an entry and then use the browser back button, all of the lazy loading is gone, I tried to add window.history.pushState() but then I only get the current page i.e.?page=4 when I use the browser back button, and all of the entries on top is not loaded. Is there any way to implement a correct history so that the user is back at the same place when they use the browser back button? $.endlessPaginate({ paginateOnScroll: true, paginateOnScrollMargin: 400, paginateOnScrollChunkSize: 2, onCompleted: function(context, fragment) { window.history.pushState(null, null, context.url); } }); -
How to loop by month between 2 dates and refer to those values as foreign key?
I have 2 dates of beginning and end of rent and I have to collect rent for each month.What is the best way to do it if I want to refer to each of those values as to foreign key , since if you paid some money for June for 2016 this payment should relate to June 2016 and total should be calculated for this month owning. I have 2 main options calculate it on the fly and to relate to those values on the fly somehow? dt1, dt2 = dateRange start_month=dt1.month end_months=(dt2.year-dt1.year)*12 + dt2.month+1 dates=[datetime.datetime(year=yr, month=mn, day=1) for (yr, mn) in ( ((m - 1) / 12 + dt1.year, (m - 1) % 12 + 1) for m in range(start_month, end_months) )] I see a lot of headekes doing it on the fly since I might have discounts etc applied for particular month and since might get complex out of proportion Or preferably have a table with all the years and month lets say fro next 50 years and to use those as FK for each payment. But then doesn't the calendar is already such a table and isn't it poor design practise. I am developing in Django / … -
Celery - Single AMQP queue bound to multiple exchanges
I have a RabbitMQ topology(set up independent of celery) with a queue that is bound to two exchanges with the same routing key. Now, I want to set up a celery instance to post to the exchanges and another one to consume from the queue. I have the following questions in the context of both the producer and the consumer: Is the CELERY_QUEUES setting necessary in the first place if I specify only the exchange name and routing key in apply_async and the queue name while starting up the consumer? From my understanding of AMQP, this should be enough... If it is necessary, I can only set one exchange per queue there. Does this mean that the other binding will not work(producer can't post to the other exchange, consumer can't receive messages routed through the other exchange)? Or, can I post and receive messages from the other exchange regardless of the binding in CELERY_QUEUES? -
Add CSRF-TOKEN into angularJs 2
I am making a website using Django and AngularJs2. When I created the login form then submit form, Django shows an error: forbidden (CSRF token missing or incorrect.) I know Django wants me to add a CSRF token, but I don't know how. -
Django: using context variable in a script
I have a class view that inherits from TemplateView and sets a context variable to a serialized list of items: class MyView(TemplateView): def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) context['items'] = serializers.serialize("json", items) # assume items is an existing list return context As is noted in this post you're supposed to be able to access Django variables from our Django templates in the following manner: <script>var items = {{ items }};</script> However I am getting a JavaScript error, which I assume is caused because of automatic escaping: Uncaught SyntaxError: Unexpected token & I also tried using the filter: <script>var items = {{ items | escapejs }};</script> Only to find another error, this time a Django one (TemplateSyntaxError): Could not parse the remainder: ' | escapejs' from 'items | escapejs' How can I solve this issue? PS: I am using Django 1.4. (and no, I cannot upgrade it to the most recent version). -
change datetime format in python
I am getting this datetime in this format from my database. 2016-09-13T08:46:59.953948+00:00 I want to change this date into format like 13 sep 2016 08:46:59 I have used datetime module like import datetime datetime.datetime.strptime(2016-09-13T08:46:59.953948+00:00, 'changing format') But it is giving error TypeError at /admin/help must be string, not datetime.datetime -
Can I use parameters in django template tag [duplicate]
This question already has an answer here: Django pass object to include 1 answer I want to send base template I am extending as a parameter. Currently, my template first tag is like this {% extends "rent_base.html" %} I want it to be like this {% extends {{base}} %} Can I achieve it with Django templates? -
Refresh/redraw jquery datatables with data from django view
I use jquery DataTables 1.10.0 to display some data on a table. This is how I load the data: var layer_data = $("#layer_data").DataTable({ "scrollX": true, "aaData":whole_array, "iDisplayLength": 10 }); Where the whole_array is a an array of arrays as: [Array[7], Array[7], Array[7] Each array has different values as: 0:"<button id="1" class="btn btn-info btn-sm _edit_save_btn" style="margin-bottom:5px;width:68px; background-color:#a7a3a3;border-color:#a7a3a3">Edit</button></br><button id="fid__1" class="btn btn-info btn-sm _add_save_btn" data-toggle="modal" data-target="#add_geometry" data-fid="afghanistan_test.1" style="background-color:#a7a3a3; border-color:#a7a3a3;margin-bottom:5px;width:68px;">Geometry</button></br><button id="fid__cancel__1" class="btn btn-info btn-sm _cancel_btn" style="margin-bottom:5px;width:68px; background-color:#a7a3a3;border-color:#a7a3a3">Cancel</button>" 1:"Afghanistan" 2:"Badakhshan" 3:... What I want to do is to redraw/refresh the table on a button click. I read there are ways to do this with ajax requests but I think this is not my case as the data come from a django view which is initialized on page load. -
python - django - using a flag on each model field
I want to build a simple moderation system for my application.I have a class in my application models like this: #models.py class TableName(models.Model): is_qualified = False title = models.CharField(max_length=300, blank=False) description = models.TextField(max_length=500, default="DEFAULT VALUE") video = models.FileField(upload_to='somepath') picture_thumbnail = models.ImageField(upload_to='somepath') I have 3 questions: How can I add is_qualified to every field in my model and setting it to False as default? How can I write a view method first for checking if admin checked an object (for example title or description) and used its checkbox to change field's is_qualified value to True? How to add a checkbox for each object in admin area for using that view method? Thank you very much. -
AttributeError - module 'django.http.request' has no attribute 'META'
I got this error, but I've done exactly the same: AttributeError at /courses/ module 'django.http.request' has no attribute 'META' The error is occuring in : from django.shortcuts import render from django.http import request from django.http import HttpResponse from .models import Course # Create your views here. def course_list(response): courses = Course.objects.all() return render(request, 'courses/course_list.html',{'courses':courses}) # output=', '.join([str(course) for course in courses]) # return HttpResponse(output) But the server shows no issues at all. Performing system checks... System check identified no issues (0 silenced). September 13, 2016 - 13:51:18 Django version 1.10.1, using settings 'learning_site.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. -
How to combine Prefetch with annotate and order_by annotated value
anyone have idea how to make that query working ? users.prefetch_related( Prefetch( 'rooms', queryset=Room.objects.filter(participants__in=[user]), to_attr='common_rooms' ), ).annotate( common_rooms_count=Count('common_rooms') ).order_by( 'common_rooms_count' ) -
Save another model's object in CreateView
I have 3 model: class City(models.Model): name = models.CharField() class State(models.Model): name = models.CharField() class Role(models.Model): CITY = 1 State = 2 NOACCESS = 0 VIEW = 1 UPDATE = 2 DELETE = 3 TYPE_CHOICES = ( (CITY, 'City'), (STATE, 'State'), ) ROLE_CHOICES = ( (NOACCESS, 'No access'), (VIEW, 'View'), (UPDATE, 'Update'), (DELETE, 'Delete'), ) obj_type = models.IntegerField(choices=TYPE_CHOICES) obj_id = models.IntegerField(verbose_name="Object ID") obj_role = models.IntegerField(choices=ROLE_CHOICES, default=NOACCESS) obj_user = models.IntegerField() I would like to save a role for each user in views.py: class FormCreateView(CreateView): form_class = City def form_valid(self, form): users = self.request.POST.getlist('access-users') f.save() for i in users: role = RoleCreateView() # save a role for each user role.type = 'city' role.user = i role.city = f.id role.save() return super(FormCreateView, self).form_valid(form) How I can do this? -
How do I use Python Django variables in my JS code?
I'm trying to make a vertical side navigation bar populated with categories (dynamic, fetched from django models) where each category has sub-categories (also dynamic and fetched from models). When I refer to classes in my JS code, the code works i.e., upon clicking of a category, the sub-menu consisting of its respective subcategory opens up. But the problem is, when I click on any of the categories, all of them expand to reveal all their sub-categories. I just want one, which is clicked on, to open and stay open. My HTML: <div class="col-md-12 col-xs-12 body-container leftsidenavigator" style="margin-top:15px;"> <div class="col-md-12 col-xs-12 leftsidenavigator-inner" style="padding:0px;"> <h2><center>Categories</center></h2> <ul class="catindexlist catlistcat nav-collapse89"> {% for category in catindexlisted %} <div class="catindexlistitem"> <li class="category-name" style="font-weight:600;padding-right:20px;"><a href="" id="category-name{{category.name}}">{{category.name}}</a></li> </div> <div class="nav-collapse88"> <ul style="padding:0px;"> {% for forum in category|forumindexlistbycat %} <div class="catlistforum" id="catlistforum{{forum.name}}"> <li class="forum-name" style="padding-right:10px;"><a href="{{ forum.get_absolute_url }}">{{forum.name}}</a></li> </div> {% endfor %} </ul></div> {% endfor %} </ul></div></div> My non-ideal but working Javascript: $(function() { $(".catlistforum").hide(); $(".category-name a").click(function(e) { e.preventDefault(); $(".catlistforum").slideToggle(); if(!($(this).parent('li').parent('div').siblings('div').child('ul').child('div').is(":visible"))){ $(this).parent('li').parent('div').siblings('div').child('ul').child('div').is(":visible").slideToggle(); } }); I need something like this to work: $(function() { $(".catlistforum").hide(); $("#category-name{{category.name}}").click(function(e) { e.preventDefault(); $("#catlistforum{{forum.name}}").slideToggle(); if(!($("#catlistforum{{forum.name}}").is(":visible"))){ $("#catlistforum{{forum.name}}").is(":visible").slideToggle(); } }); }) This code, when I click on any category, reloads the page and no sub-menu is … -
Getting image from Django on AWS, to Android Glide. 404 error
I made rest api using Django-rest-framework. I also be helped by AWS-ec2. My django settings.py MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'images') My django serializers.py class PostSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') class Meta: model = Post fields = ('author', 'text', 'image') def create(self, validated_data): validated_data['author'] = self.context['request'].user return super(PostSerializer, self).create(validated_data) My django urls.py router = SimpleRouter() router.register(r'posts', views.PostViewSet, base_name='posts') urlpatterns = router.urls urlpatterns = [ # ex: /polls/ url(r'^', include(router.urls)), ] My django views.py class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() So, it returned { "author": "ghdalsrn", "text": "11", "image": "http://ec2-52-78-138-143.ap-northeast-2.compute.amazonaws.com:8000/images/images/Avril_Lavigne_-_00_-_Sk8er_Girl_-_Frontcover_-simplemp3s.jpg" } I used "image": "http://ec2-52-78-138-143.ap-northeast-2.compute.amazonaws.com:8000/images/images/Avril_Lavigne_-_00_-_Sk8er_Girl_-_Frontcover_-simplemp3s.jpg" on my Android studio. My Android studio's MainActivity.java public class MainActivity extends AppCompatActivity { public ImageView mimage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mimage = (ImageView) findViewById(R.id.iv_image); Glide.with(this) .load("http://ec2-52-78-138-143.ap-northeast-2.compute.amazonaws.com:8000/images/images/Avril_Lavigne_-_00_-_Sk8er_Girl_-_Frontcover_-simplemp3s.jpg") .centerCrop() .into(mimage); But, according to my putty message, putty "GET /images/images/filename_sk8er_Girl.jpg HTTP/1.1" 404 5184 Also my Android application - imageview with Glide shows and gives me nothing. Why this happend? How can i make it doing right? -
Error "pkg_resources.DistributionNotFound: Django==1.9" when startproject
I have a problem when i try to create new project. It happens after updating Django from 1.8 version to 1.9. So when i use command: django-admin.py startproject myproject i've got error: CommandError: /var/www/myproject/manage.py already exists, overlaying a project or app into an existing directory won't replace conflicting files when i type this command: django-admin startproject myproject i've got this error: Traceback (most recent call last): File "/usr/local/bin/django-admin", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2749, in <module> working_set = WorkingSet._build_master() File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 446, in _build_master return cls._build_from_requirements(__requires__) File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 459, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 628, in resolve raise DistributionNotFound(req) pkg_resources.DistributionNotFound: Django==1.9 So according to this post, i check the path of django-admin.py and check the django, and it the same. I tried to delete and install django using pip, but i've got still the same error. I will be glad if somebody help me with that. Thank You! -
redis.exceptions.ConnectionError: Error 97 connecting to localhost:6379. Address family not supported by protocol
when ever i try to run my program following error will will raise. redis.exceptions.ConnectionError: Error 97 connecting to localhost:6379. Address family not supported by protocol. Previously the program runs normally now this error will be raised. Traceback (most recent call last): File "securit.py", line 26, in <module> bank = red.get('bank') File "/usr/local/lib/python2.7/dist-packages/redis/client.py", line 880, in get return self.execute_command('GET', name) File "/usr/local/lib/python2.7/dist-packages/redis/client.py", line 578, in execute_command connection.send_command(*args) File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 538, in send_packed_command self.connect() File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 442, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: Error 97 connecting to localhost:6379. Address family not supported by protocol. And my program is bank = red.get('bank') content_icons={"Wire":"wired.png","Wireless":"wireless.png","NC":"nc.png","NO":"no.png","Keypress":"keypad.png","Key":"key.png","Daylight":"sun.png","Normal":"norm.png","Iso":"iso.png","Silent_p":"silent_sound.png","Normal_p":"normal_sound.png","Timer":"timer.png"} def call_screens(): ip='NA' li=[['screen','-d','-m','-t','gsmmodem','sudo','python','/home/pi/GaliMisic/banksecurity/pythonclient/gsm_modem2.py'], ['screen','-d','-m','-t','localsecurityserver','nodejs','/home/pi/GaliMisic/banksecurity/nodescripts/securitynodeserver_lan.js'], ['screen','-d','-m','-t','securityclient','nodejs','/home/pi/GaliMisic/banksecurity/nodescripts/securityclient.js'], ['screen','-d','-m','-t','zonepolling','sudo','python','/home/pi/GaliMisic/banksecurity/pythonclient/test.py'], ['screen','-d','-m','-t','keypolling','sudo','python','/home/pi/GaliMisic/banksecurity/pythonclient/test_2.py'] ] while ip=='NA': try: ip = os.popen("ifconfig eth0|grep 'inet'").read().split('inet addr:')[1].split(' ')[0] for cmd in li: subprocess.call(cmd) except Exception as e: ip = 'NA' time.sleep(3) def fetch_ip(ipvar,button): button.configure(state=DISABLED) ip='NA' li=[['screen','-d','-m','-t','gsmmodem','sudo','python','/home/pi/GaliMisic/banksecurity/pythonclient/gsm_modem2.py'], ['screen','-d','-m','-t','localsecurityserver','nodejs','/home/pi/GaliMisic/banksecurity/nodescripts/securitynodeserver_lan.js'], ['screen','-d','-m','-t','securityclient','nodejs','/home/pi/GaliMisic/banksecurity/nodescripts/securityclient.js'], ['screen','-d','-m','-t','zonepolling','sudo','python','/home/pi/GaliMisic/banksecurity/pythonclient/test.py'], ['screen','-d','-m','-t','keypolling','sudo','python','/home/pi/GaliMisic/banksecurity/pythonclient/test_2.py'] ] while ip=='NA': try: ip = os.popen("ifconfig eth0|grep 'inet'").read().split('inet addr:')[1].split(' ')[0] button.configure(state=NORMAL) except Exception as e: ip = 'NA' time.sleep(3) print ip print 'leaving thread' ipvar.set("LOCAL IP : "+ip) ''' if red.get('screenscalled')=='False': for cmd in li: subprocess.call(cmd) red.set('screenscalled','True') ''' if red.get('scriptssyncd')=='False': subprocess.call(['bash','-x','/home/pi/GaliMisic/banksecurity/nodescripts/syncscripts.sh']) red.set('scriptssyncd','True') -
Django: Parse JSON in template using Javascript array
In my template I pass parameters in array: technicCategories is array of json_serializer.serialize So I can't to make something like this: var technicCategories = '{{ technicCategories|escapejs }}'; because it is array and I tried and it gives me error: "JSON Parse error: Unexpected identifier "u"", my array looks like: var technicCategories = '[u\u0027[{\u0022model\u0022: \u0022automarket.technicandallf.... So i decided to do this: for (var i = 0; i < {{ index }}; i++){ var technicCategories = '{{ technicCategories.i|escapejs }}'; technicCategories = JSON.parse(technicCategories); console.log(technicCategories); } but there is a problem: SyntaxError: JSON Parse error: Unexpected EOF. But if I make this: var technicCategories = '{{ technicCategories.0|escapejs }}'; all works fine but gives me only object at index 0. -
FormSet object has no attribute 'save'
When I submitted form, I have an error 'LookupFormFormSet' object has no attribute 'save' My template: <form method="post" action="">{% csrf_token %} {{ formset.management_form }} {% for form in formset %} <section id="test_data"> {{ form }} <ul> <li>{{form.id}}</li> {% if formset.can_delete %} <li>{{ form.DELETE }}</li> {% endif %} </ul> </section> {% endfor %} <button type="submit" class="btn btn-default" id="submit_form">Submit</button> <button type="button" class="btn btn-default" id="add" value="Add row"/>Add row</button> </form> My forms.py: class LookupForm(forms.ModelForm): class Meta: model = look exclude = () LookupFormSet = formset_factory(LookupForm, can_delete=True) My model class look(models.Model): class Meta(): db_table = 'lookup' id_device = models.CharField(max_length=75) phone_number = models.CharField(max_length=100) phone_number_country = models.CharField(max_length=1000) text = models.CharField(max_length=1000, default=None) my view def manage_articles(request): LookupFormSet = formset_factory(LookupForm) if request.method == "POST": formset = LookupFormSet(request.POST, request.FILES, prefix='lookups') if formset.is_valid(): formset.save() return HttpResponseRedirect('/') else: formset = LookupFormSet(prefix='lookups') return render(request, 'req/lookup.html', {'formset': formset}) -
TypeError: view must be a callable or a list/tuple in url of image Django
When I am writing the url for the image, I am not able to run the server. And if I remove the url, I won't be able to save the image.. url(r'^item/(.*)$', 'django.views.static.serve', {'document_root' : settings.MEDIA_ROOT}), Please suggest a solution, I tried a couple of solutions from SO, but couldn't solve. -
Using CheckboxSelectMultiple on a SimpleArrayField (Django)
I've got a user model form with a couple of fields that allow multiple values. Right now these values are rendered in the templates as select inputs where several options can be chosen and I want to change that for checkboxes. I have to change the widget for these fields, currently defined as Postgres' ArrayField in the model. The form fields are customized because of some error, I don't really know, but it overrides the default SimpleArrayField. The widget in the code overrides SelectMultiple widget, I tried changing it for CheckboxSelectMultiple and didn't display nothing in the template, same happened when I tried to change the widget in forms.py. I've reading but I haven't understand much, and I don't want to change the model fields as it's not code written by me. Would appreciate any help. I found this but I couldn't understand the code or how to use it: https://gist.github.com/jbaldivieso/96af08a6e0d55d634d4b models.py languages = ArrayField( models.CharField(max_length=50, blank=True, choices=LANGUAGE_CHOICES, default=''), default=list ) forms.py languages = ArraySelect(forms.CharField(max_length=50), widget=ArrayFieldCheckboxSelectMultiple(choices=User.LANGUAGE_CHOICES)) widgets.py from django.contrib.postgres.forms.array import SimpleArrayField from django.forms import SelectMultiple class ArraySelect(SimpleArrayField): """ This class fixes an issue when converting back to python but the data is already a list """ def to_python(self, value): if …