Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multi process Daphne with supervisor, getting [Errno 88] Socket operation on non-socket
daphne and Django channels work fine on command line or single process. But when I start it with supervisor, the error occurs. 2020-02-18 12:40:35,995 CRITICAL Listen failure: [Errno 88] Socket operation on non-socket My config file is [program:asgi] socket=tcp://localhost:9000 directory=/root/test/test/ command=daphne -u /run/daphne/daphne%(process_num)d.sock --endpoint fd:fileno=0 --access-log - --proxy-headers test.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=2 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/root/test/test/script/asgi.log redirect_stderr=true [supervisord] [supervisorctl] Any ideas? Thanks! -
Use pk from url in django form
In my django app I have a table which contains a button that redirects you to a form like this: <a href="{% url 'employee:delivered_docket_form' docket.pk %}" class="btn btn-primary">Create Delivered Docket</a> Urls.py path('delivered-docket/add/<int:pk>/', DeliveredDocketFormView.as_view(), name='delivered_docket_form') Views.py @method_decorator([login_required, employee_required], name='dispatch') class DeliveredDocketFormView(CreateView): model = DeliveredDocket form_class = DeliveredDocketeditform template_name = 'packsapp/employee/docketDeliveredForm.html' def form_valid (self, form): product = form.save(commit=False) product.save() data = form.cleaned_data print("form data is ", data) print("pk is ",self.kwargs['pk']) messages.success(self.request, 'The Delivered Docket was created with success!') return redirect('employee:delivered_docket_table') I am able to access the pk in the views function by self.kwargs['pk'] but how can I access it in the formclass. Here's my form Forms.py class DeliveredDocketeditform(forms.ModelForm): class Meta: model = DeliveredDocket fields = '__all__' -
Rest Framework incorrect validation on update using SlugRelatedField
I have successfully used SlugRelatedField to validate relationship with other model in create. However when I use update, it does not validate correctly. Suppose I have: #models.py class Product(models.Model): name = models.CharField() amount = models.IntegerField() description = models.TextField() def __str__(self): return "{} XL".format(self.name) class Query(models.Model): name = models.CharField() product = models.ForeignKey(Product) ... #serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class QuerySerializer(serializers.ModelSerializer): product = serializers.SLugRelatedField(slug_field='name', queryset=Product.objects.all()) class Meta: model = Query fields = '__all__' def create(self, validated_data): product = validated_data.pop('product').name ... def update(self, instance, validated_data): instance.product = validated_data.get('product', instance.product) ... When I POST, it gets successful: { "name": "Query 1", "product": "Pants", ... } But when I PATCH, it gets problem and got a response error. I know the __str__ in the model complicates things. However I want to solve it without removing it. { ... "product": "Shirt", ... } Response Error: {'product': ['Object with name=Shirt XL does not exist.']} How can I catch validation on update? I tried adding validate to print the data. But why is not printing when updating? def validate(self, data): print(data) # Does not print on update return data Is there also a way to change it before update to make product … -
Right way to fetch parent table with it's child tables
I have one to many relationship on parent and child tables. And trying to fetch parent table with it's child tables as json. I tried something like below. if (request.method == "GET"): parents = Parent.objects.all() datas = [] childTables = [] for parent in parents: #fetching parent first and creating DICT for json #also creating an array for the child tables parentDict = { "id": parent.id, "project_name": parent.project_name, childTables: [], } #then fetching child tables NO problem at this part as well. childs = parent.child_set.all() for child in childs: #creating a DICT FOR THE json. childDict = { "id":child.id, "ad_kind":child.ad_kind, "parent_id":child.parent_id, } #problem starts right below. I can't append childDict inside the parent's array parentDict["childTables"].append(childDict) #at last append all parent table inside an array and send it as JSON. datas.append(parentDict) return JsonResponse(datas, safe=False) the problem starts when I try to append child tables inside it's parent dict. The error says: unhashable type: 'list' is there any other simpler way to achieve this? -
Is it bad practice to have two different end points performing same task but having different permission
I have an endpoint that performs a task(say unlock something). There are two different screens from which when I can call this endpoint from screen A only admin should be able to access but say from screen B both admin and the normal user should be able to access. Using the Django rest framework for designing my rest endpoints. My code as of now looks like this. @is_admin(error='User doesn't have permission') def doSomething(): ...... I was wondering whether I should just duplicate this endpoint without permission and use it from screen B or is there some other better way. -
how to send send the data using python django?
How to send the json data using post request in django python. I have a code for get the data and I don't use any html file. class employeeList(APIView): def get(self, request): employee1 = employees.objects.all() serializer = employeeSerializer(employee1, many=True) return Response(serializer.data) def post(self,request): pass can you please help for post request.Now I want to create post function to send the data -
Django Newbie error: - TypeError: view must be a callable or a list/tuple in the case of include()
I am a total newbie to python Django and would like to know why are views not being created. here's my urls.py which is under myproject. from django.contrib import admin from django.urls import path,include from django.conf.urls import url admin.autodiscover() urlpatterns = ['', path('admin/', admin.site.urls), url('myapp/', include('myapp.url')) ] here's my view.py which is in myapp folder from django.shortcuts import render # Create your views here. def hello(request): return render(request,"myapp/templates/hello.html", {}) here's my url.py in myapp folder from django.conf.urls import include, url urlpatterns = ['', url('hello/', 'views.hello', name='hello'),] and here's the complete traceback Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/mayureshkadam/Learning-Django/lib/python3.7/site-packages/django/utils/functional.py", … -
how to increment a Vote field within a Django database of Voting System
I'm trying to make a system in which a person(Voter) will vote for a candidate against their 'Candidate Id', so for that Voter has to input the 'Emirates Id' (which is primary key of Voter) and 'Election Id' -which is primary key of the polling station - both these ID's will get validated to check if vote has been cast or not, but the problem really lies within my logic. here is my Views.py : def vote(request): can_id_obj = Candidate_Form.objects.get(pk=request.POST['Can_ID']) voterrecord = Election_Day( #through this we will create an object of the class or our model Can = can_id_obj, #these are the fields in my 'Election Day' model emirates_id = Emirates_ID, election_id = Election_ID ) can_id_obj.Vote += 1 #we will call a field to manipulate it voterrecord.save() #finally we can call save method on the object return render(request, 'Election_Day.html') Everytime the vote gets polled, Instead of incrementing the same record for which the vote was previously cast, it will make a new record and then save the vote as 1, so basically i want it to increment the same record, if the vote has been polled for the same candidate.I hope you understand the explanation.. -
passing the value from the form to another page
def get_name(request): if request.method == 'POST': user_code = generate_code(8) subject = 'ver code' message = user_code phone = request.POST['phone'] form = NameForm(request.POST) if form.is_valid(): Registration.objects.create(fio=request.POST['fio'],mail=request.POST['mail']) send_mail(subject, message,settings.EMAIL_HOST_USER,[mail],fail_silently=False) return JsonResponse({ 'form1': render_to_string( 'registers/endreg.html', {'form': NameForm1() } ) }) else: form = NameForm() return render(request, 'registers/detail.html', {'form': form}) def endreg(request): if request.method == 'POST': form = NameForm1(request.POST) if form.is_valid(): code_use = form.cleaned_data.get("key") try: user = Registration.objects.get(code=code_use) user.verification = True user.save() messages.warning(request, u'thanks.') except: messages.warning(request, u'error.') else: form = NameForm1() return render(request, 'registers/endreg.html', {'form': form}) I have 2 fields in the form. when you submit the form to the server, a random confirmation code is generated and sent to this mail how on page 2, where is the code input field, display to which mail it was sent? 1 page detail 2 page endreg. how to send the sender email to the endreg page? -
How to Constrain a Django Model Table to One Row
I want to create a table with only one row in MySQL database. It's for site settings. This is the SQL for it that I found in another question on this site: CREATE TABLE T1( Lock char(1) not null DEFAULT 'X', /* Other columns */, constraint PK_T1 PRIMARY KEY (Lock), constraint CK_T1_Locked CHECK (Lock='X') ) Can I do this in a Django model program? So far, I have: class Settings(models.Model): lock = models.CharField(max_length=1, null=False, primary_key=True, default='X') employer_day_date = models.DateField class Meta: constraints = [CheckContraint()] I can add class Meta: to it, but PyCharm doesn't recognize CheckConstraint so I haven't gone any further with it. I have no problems doing it in SQL if that's the only way. I was thinking of altering the database after the migration, but it seemed rather crude. -
How to update the model from the ajax by rest framework(csrf problem??)
I want to update the table row by from ajax From auto generated form (by rest framweorks) posting and updating works correctly. However from ajax it shows "POST /api/issues/372/ HTTP/1.1" 403 58 error I googled around and found that this is related with csrt. However How can I send correct json??? var json = { "id": 37; "name": "This is my new name", "color": "#dddddd" }; $.ajax({ type:"POST", url: "{% url 'issues-detail' 372 %}", data:JSON.stringify(json), contentType: 'application/JSON', dataType: "JSON", success: function(response) { console.log(response); }, error: function(response) { console.log(response); }, complete: function() { console.log("complete"); } }); -
Django Group by as Query
claims.values("p_id").annotate(id_count=Count('id'),id_amount=Sum('amount')).order_by('p_id') OutPut:- [ { "p_id": "AAA", "id_count": 1, "id_amount": 15000.0 } ] Instead of P_id i want to name this field partners, like how we do this in SQL select p_id as partners.?? -
What is best way to add product features in django with database mysql
I want to store product features in MySQL database so, I've some confusion about which way is better to store it for better performance as well as for scalability. Basically as per my idea, I design models like given below: in that, I have a product table, features table which contains field product type for which type of product belongs to this particular feature. the last table is product_features in that I actually storing data of specific product_id and feature_id is it the right way? I'm using Django. so here's is my model! class Product(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=255, null = False, unique=True) product_slug = models.SlugField(unique=True, blank=True, null=True) product_title = models.CharField(max_length=255, null = True) product_info = models.TextField(null = False) product_description = models.CharField(max_length = 255) product_price = models.CharField(max_length = 255) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True) product_status = models.CharField(max_length = 100, default = "publish") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) class Feature(models.Model): feature_id = models.AutoField(primary_key=True) feature_name = models.CharField(max_length=255, null = False) product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True) feature_has_value = models.CharField(max_length = 1, null = False) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) class Product_feature(models.Model): product_feature_id = models.AutoField(primary_key=True) feature = … -
Django connection to database from local machine to server
I'm new in Django, so I need some guide. Our company has server and Oracle database in this server. My Django app is in my local machine. I should connect my app to database in server. For this should I put my app in server and connect, or can I connect from local machine? And if I can from local machine how I connect to Oracle database in server? -
How to create Advance search bar in html
I want to make an advance search bar which first displays few tags and when a value of tag is selected, then it displays logical operator then again the tag options should be display if a value of operator is selected and this should happen simultaneously. More than code, i want logic of how it can be done. Even if you can explain it with a small example then its fine. I tried doing it with dropdown box toggling but couldn't accomplish my task. Please provide best possible logic and small example code, if possible. -
IntegrityError at /blog/2 NOT NULL constraint failed: blog_comment.post_id
I get an error when I try to add comments to my app. my form is : ''' from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = [ 'content' ] ''' And the model is : ''' class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() author = models.ForeignKey(User , on_delete=models.CASCADE) image = models.ImageField(upload_to='blog/' , blank=True, null=True) # tags category = models.ForeignKey('Category' ,null=True, on_delete=models.SET_NULL) created = models.DateTimeField(default=timezone.now) tags = TaggableManager(blank=True) class Meta: verbose_name = ' post' verbose_name_plural = 'posts' def __str__(self): return self.title class Category(models.Model): category_name = models.CharField(max_length=50) class Meta: verbose_name = ' category' verbose_name_plural = 'catogires' def __str__(self): return self.category_name class Comment(models.Model): user = models.ForeignKey(User , on_delete=models.CASCADE) post = models.ForeignKey(Post , on_delete=models.CASCADE) content = models.TextField() created = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.content) ''' my views is : ''' from django.shortcuts import render from .models import Post , Category , Comment from taggit.models import Tag from .forms import CommentForm def post_detail(request , id): post_detail = Post.objects.get(id=id) categories = Category.objects.all() all_tags = Tag.objects.all() comments = Comment.objects.filter(post=post_detail) if request.method == 'POST' : comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.user = request.user new_comment.post = post_detail new_comment.save() else: comment_form = CommentForm() context = { 'post_detail' … -
How can I send POST request with csrf without django rest framework
I send ajax request to my api, it returns "POST /api/myapi HTTP/1.1" 403 58 error , while 'GET' works. I googled around and found it is relevant with csrf token. There are many samples with django rest framework, but I want to use without that. How can I send the csrf token to my API by ajax?? $.ajax({ type:"POST", // 'GET' works url: "{% url 'myapi' %}", data:JSON.stringify(jsonData), contentType: 'application/JSON', dataType: "JSON", success: function(response) { console.log(data); }, error: function(response) { console.log(response); }, }); in views.py @api_view(['POST', 'GET']) @ensure_csrf_cookie def myapi_view(request): if request.method == 'GET': print(request.data) return JsonResponse({"message":"please use POST"}) data = {"name":"myapi","message":"success"} return JsonResponse(data) -
floppyforms in INSTALLED_APPS got error django
When I add 'floppyforms' to your INSTALLED_APPS in settings.py, it throw this error. Can anyone help me to suggest what is the solution,Please help! INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'floppyforms', 'products', ] Receive this error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/floppyforms/__init__.py", line 5, in <module> from .fields import * File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/floppyforms/fields.py", line 5, in <module> … -
Embedded Bokeh DataTable not showing in Django
I have developed a Django web application showing interactive maps generated by Bokeh, and sent to the templates as script/div using 'components' (from bokeh.embed). All items (figure, slider, title) are shown correctly except DataTable, which I can show in a standalone document or in Jupyter, but not with 'components'. I have read Bokeh DataTable not show in Flask, Embedding bokeh plot and datatable in flask and other threads, which helped me to fix the JS/CSS links, but it did not help with my problem. I tried to wrap the DataTable inside different modules, like Panel, WidgetBox, etc., after reading https://github.com/bokeh/bokeh/issues/4507, without success. For simplicity, I used example data with no link to my data to generate the table in a separate Django view, and created a separate template. I have run out of ideas for now. I know that widgets in Bokeh have had rendering issues, so I am guessing my issue could be related to those issues, but more likely to my lack of knowledge. The code is below. DJANGO VIEW: def datatable_test(request): data = dict( dates=[date(2014, 3, i + 1) for i in range(10)], downloads=[randint(0, 100) for i in range(10)], ) source = ColumnDataSource(data) columns = [ TableColumn(field="dates", … -
Django - template - reduce for loop repetition, reduce sqlite3 db query
I find myself repeatedly cycling through the same set of data, accessing database several time for the same loops to achieve displaying the correct data on one template, here's the code: <!-- item images and thumbnails --> <div class="row"> <div class="col-12 col-sm-8"> <div id="item{{item.pk}}Carousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for image in item.itemimage_set.all %} <li data-target="#item{{item.pk}}Carousel" data-slide-to="{{forloop.counter0}}" {% if forloop.first %} class="active" {% endif %}></li> {% endfor %} </ol> <div class="carousel-inner shadow-lg rounded-sm"> {% for image in item.itemimage_set.all %} <div class="carousel-item {% if forloop.first %} active {% endif %}"> <a href="#itemImageModal" data-toggle="modal"><img src="{{image.image.url}}" class="d-block w-100" alt="..."></a> </div> {% endfor %} </div> {% if item.itemimage_set.count > 1 %} <a class="carousel-control-prev" href="#item{{item.pk}}Carousel" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#item{{item.pk}}Carousel" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> {% endif %} </div> </div> <div class="pl-sm-0 col-12 col-sm-4 d-flex flex-wrap align-content-start"> {% for image in item.itemimage_set.all %} <div class="col-4 {% if item.itemimage_set.count > 3 %} col-sm-6 {% else %} col-sm-8 {% endif %} mt-2 px-1 mt-sm-0 pb-sm-2 pt-sm-0 mb-0"> <img src="{{image.image.url}}" alt="" class="col-12 p-0 rounded-sm shadow-sm" data-target="#item{{item.pk}}Carousel" data-slide-to="{{forloop.counter0}}"> </div> {% endfor %} </div> </div> <!-- /item images and thumbnails --> The above code renders the item's itemimage bootstrap carousel … -
Compare Def Post and Django Form
I’m a backend developer. Currently, I have some questions between using Django Form and pure Def Post for request processing. My manager said that using Def Post will be better than Django Form because of easy model controlling and prevent conflict with the others. So, do I really need to RECREATE “a wheel” or just use Django Form to MODIFY it? -
Which module to manage nodes in multiple tree?
I am creating a web tool to manage bills of materials (BOM). I managed to get some nice presentation of BOMs using django with js-tree but now I would like to put all of this in a database. My trees look like this: - Root Part (ie Product A) - PartA - Qty: 1 - PartB - Qty: 1 - PartC - Qty: 1 - Part D - Qty: 4 - Part E - Qty: 1 - Part F - Qty: 2 ... The problem is that a same part can be present in different products, or in different subassembly (think of a screw for example). I would like to be able to reuse an existing node (and its children) in an other tree (for example I could have a Product B that also include Part E (and thus Part F)). If I am updating a node (ie Part E) the change should appear in every trees where it is used. django-mptt seems a good candidate but unfortunately a node can only have one parent. There is a TreeManyToManyField but nothing in the documentation about it, I am not sure if it could help me. I could create the Part … -
How to address unscriptable Django objects?
I have the following model: class WorkMusic(MPTTModel, Work): ... class Performance(Event): date_created = models.DateTimeField(_('date created'), default=timezone.now) date_modified = models.DateTimeField(_('date_modified'), auto_now=True) class PerformanceWork(models.Model): perf = models.ForeignKey(Performance, related_name='perf_work', blank=True, null=True, on_delete=models.CASCADE) work = models.ForeignKey(WorkMusic, related_name='work', blank=True, null=True, on_delete=models.CASCADE) In my view.py: class PerformanceView(TemplateView): template_name = 'performances/performance.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'perf': Performance.objects.get(pk=self.kwargs['pk']) }) return context In my template, I am trying to render a recursive tree with this in my template: {% for work in perf.perf_work.all %} {% recursetree work.work %} <li> {% if node.is_leaf_node %} {{ node.name_original }} {% endif %} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} {% endfor %} When run my app, I get the following error. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/performance/2/ Django Version: 3.0 Python Version: 3.7.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'opus', 'generic', 'art_perf', 'art_visual', 'debug_toolbar', 'mptt', 'import_export', 'googlemaps'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware') Template error: In template /Users/howiec/Desktop/Opus/templates/performances/base.html, error at line 0 'WorkMusic' object is not subscriptable 1 : {% load static i18n %} 2 : 3 : <!DOCTYPE html> 4 : <html lang="en" class="{% block html_class %}{% endblock %}"> … -
Database most efficient tables system
I'm using Django and Mysql in order to display some news articles. These articles are in English and German. I would like to know what database organization is more efficient: 1 table made of the following fields: Articles English_title English_body German_title German_body Picture or 2 tables made of the following fields: English articles English_title English_body Picture German articles German_title German_body Picture I will display English articles on a template and German ones in another one. I don't know a lot of about db so thank you for the help! -
Count of values in a dict keys
I have a Queryset in which I am returning values using values() method for the query - model.objects.filter....values(). I get the result <QuerySet [{'vals': u'101381,101905,102168,102170,104109,104284,105557,106767,107181,107577,108377,108378,108896,108910,109338,109965,111955,111978,112101,112323,112972,112973,113085,113457,113459,113925,113926,113928,114364,114744,114745,2,61372,61641,69231,69495,77283,84017,84702,85012,88448,91204,92280,93795,94453,95160,97035,97629,97939,97994,98955'}, {'vals': u'102799,107739,108331,108510,108511,108998,109000,109012,109046,109545,109551,110127,110145,110150,110808,111764,111788,112111,112281,112471,112592,113155,113170,11517,33190,40467,46350,49222,52586,54776,56905,56943,57023,57120,57137,57144,59572,59581,59584,61674,61677,61678,61683,61702,63356,64193,64255,64792,67270,71806,71977,71982,72295,72299,72570,73155,73196,74019,74048,74057,74099,74109,74131,74427,74467,74476,74477,74478,77072,78542,78798,78800,78802,78804,78811,78814,78873,78876,79464,80230,81537,82546,83232,83357,83595,83599,83857,85170,85171,85172,90970,93630,93640,93648,98221,98229,98230,98232,98236,98243'}, {'vals': u'100593,100594,100596,100597,100598,100599,100600,100601,100602,100603,100604,101445,101449,101450,101452,101453,101454,101455,101456,102963,102964,102965,102966,102967,102968,102969,102971,102972,102973,102974,102975,102976,103238,103239,103240,103241,103243,103244,103245,103247,103248,103249,104597,105383,108632,108633,108634,108635,108636,108637,108638,108640,108641,108642,108644,112939,113970,115220,94668,94669,94670,94671,94672,94673,94674,94675,94676,94677,94678,94679,95978,96021,96025,96026,96027,96028,96029,96030,96031,96032,96033,96034,96035,96036,96037,96038,96039,96040,96041,96042,96043,96044,96045,96046,96047,96048,96892,96893,96894,96974,96975,96976,96977,96978,96979,96980,96981,96982,96983,96984,96985,96986,96987,96988,96989,96990,96991,96992,96993,96994,98959,98960,98961,98962,98963,98964,98965,98966,98967,98968,98969,98970,98972,98973,98974,98976,98977,98978,99275,99280,99441,99926,99927,99928,99931,99932,99933,99934,99938,99941,99946,99947'}, {'vals': .....} I require to calculate the count the elements in val. Any leads for this?