Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Python DetailView not working as expected. I get an issue when I try and view a specific note
Advice required. would someone point me in the right direction? Using Django 3.1.1 with Pycharm Community 2020.2 I'm working with ListView to show all To-Do notes on one page allTasks.html {% extends "app/base.html" %} {% load static %} {% block content %} <body> <div class="section"> <div class="container" id="heading"> <h3>List of all Tasks to-date</h3> </div> <div class="container"> <ul id="taskcontainer"> {% for i in obj %} <li> <div class="row"> <div class="col-md-12"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ i.name }}</strong> <h6 class="mb-0">{{ i.date }}</h6> <div class="mb-1 text-muted">Team {{ i.team_project }}</div> <p class="card-text mb-auto">{{ i.notes }}</p> <p class="card-text mb-auto">Priority: {{ i.urgency }}</p> <strong class="d-inline-block mb-2 text-danger">Completed? {{ i.completed }}</strong> <span> <a href="{% url 'task-detail' task.id %}" class="link">View</a> <a href="#" class="link">Edit</a> </span> </div> </div> </div> </div> </li> {% endfor %} </ul> </div> </div> </body> From here I go into DetailView to each individual note task_detail.html {% extends "app/base.html" %} {% load static %} {% block content %} <br> <div class="row"> <div class="col-md-12"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ object.name }}</strong> <h6 class="mb-0">{{ object.date }}</h6> <div … -
Object of type QuerySet is not JSON serializable Django with AngularJS
I have a Django project where am using AngularJs as frontend. I have a very simple search where user will search a code and if the code matches from the db table it will show it. Am pretty new with angularjs what i tried is fetching objects as an array. ** my view ** @csrf_exempt def hscodesearch(request): chaptercode = '' hs4code = '' chapter_description = '' chapter_description1 = '' if (request.method == 'POST'): data = json.loads(request.body) s_t = data.get('hs_search') hs_content = { "chaptercode": chaptercode, "chapter_description": chapter_description, "chapter_description1": chapter_description1, "search_test": s_t, "hs4code": hs4code, } result = [hs_content] return HttpResponse(json.dumps({"status": 1, "data": result}), content_type='application/json') my controller.js mainApp.controller('hsController', function($scope, $http, $compile, $timeout, $location) { $scope.data = {}; $scope.init = function() { console.log("angular loaded!") } $scope.data.form = { hs_search: "", result: "", }; $scope.data.formStyle = { hs_search: "" }; $scope.submitForm = function() { //console.log($scope.data.form) var error = 0; if(!$scope.data.form.hs_search) { $scope.data.formStyle.hs_search = "is_invalid"; error++; } else { $scope.data.formStyle.hs_search = ""; } if(error==0) { var jsonCall = $http({ method: 'POST', url:'/theapp/hs-code-search', data: $scope.data.form, headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} }); jsonCall.success(function(data, status, headers, config) { if(data.status==1) { $scope.data.form.result = data.data console.log($scope.data.form.result) } }); jsonCall.error(function(data, status, headers, config) { if(data.status==0) { $.growl.error({ message: data.error}); } }); console.log($scope.data.form) } … -
Django rest framework, DELETE request responds with "Method \"GET\" not allowed." to every valid request
Here is my code for DELETE method for a "comment" model (views.py): class CommentDelete(DestroyAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer in urlpatterns it looks like this (urls.py): ... path('delete/', views.CommentDelete.as_view()), ... For some reason when I make a direct DELETE request, the result is "Method \"GET\" not allowed." I'm also using swagger, and it gets even more weird there. There is a DELETE option but it doesn't provide any parameter field even after I've specified it in views.py (lookup_field = 'id'). When I run it, it gives me an expected error: Expected view CommentDelete to be called with a URL keyword argument named "id". -
Nested foreign key serializer with customized response in Django not working
Part of models.py class Supporting_organizationSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) image_name = serializers.CharField(required=False) class Challenge(models.Model): title = models.CharField(max_length= 1000, blank=False) supporting_organization = models.ForeignKey(Supporting_organization, related_name="supporting_organizationId",on_delete=models.CASCADE,blank=True) class Challenge_progressLog_detail (models.Model): challenge = models.ForeignKey(Challenge, related_name="challengeCreationId",on_delete=models.CASCADE) latitude = models.DecimalField(max_digits=9, decimal_places=6,default=0.0) longitude = models.DecimalField(max_digits=9, decimal_places=6,default=0.0) location_address = models.TextField(default='') photo_description = models.TextField(default='') part of serializers.py: class Supporting_organizationSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) class Meta: model = Supporting_organization fields = '__all__' class ChallengeSerializer(serializers.ModelSerializer): supporting_organization = serializers.RelatedField(source='supporting_organizationId', read_only=True) class Meta: model = Challenge fields = '__all__' class Challenge_progressLog_detail_Serializer(serializers.ModelSerializer): challenge = serializers.RelatedField(source='challengeCreationId', read_only=True) class Meta: model = Challenge_progressLog_detail fields = '__all__' I want the Challenge_progressLog_detail_Serializer to return a nested object detail which will havechallenge detail with respective supporting organization. The categorization is straightforward, having a list of challenge progress log detail in the first level, challenge types in the second, and supporting organization items in the third level. Problem is that Challenge_progressLog_detail_Serializer only returns the first and second level only i.e. only the challenge detail is shown. But I want the full nested list of Challenge_progressLog_detail with Challenge Detail, And supporting organization detail items. I used below serializer class in in challenge_progresslog_detail ==> serializer.py file for get customized response in list. Apart from I used rest_framework serializer. class challengeListSerializer(serializers.ModelSerializer): challenge_id = serializers.SerializerMethodField() challenge_title = … -
Git db.sqlite and wsgi.py file keep reverting on pull
I have a python/django/wagtail project that I built locally using db.sqlite3. I did an initial push with everything to github, and then pulled it to my server. I made a change to the wsgi file and did some work in the cms which updated the database. I made some changes locally. I changed my .gitignore to exclude db.sqlite3 and wsgi.py. git add ., git commit, git push origin master. then, on the server, sudo git pull origin master. db.sqlite3 reverts back to before I made the cms changes and the wsgi.py reverts back to pointing to my dev settings. I made the changes back to the cms but now I need to do another update when I have made even more cms changes and I do not want to overwrite the database again. wsgi.py is a small fix but still. My .gitignore # Created by https://www.toptal.com/developers/gitignore/api/django # Edit at https://www.toptal.com/developers/gitignore?templates=django ### Django ### *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 db.sqlite3-journal media wsgi.py # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ # in your Git repository. Update and uncomment the following line accordingly. # <django-project-name>/staticfiles/ ### Django.Python Stack ### # Byte-compiled … -
Crispy form does not work with specific form field and button
I am trying to use crispy-forms but ran into the following two problems. This is the form.py from django import forms from menu.models import Item class TableCheckInForm(forms.Form): guest_count = forms.IntegerField(min_value =0) # item = forms.ModelChoiceField(queryset=Item.objects.all()) item = forms.IntegerField(min_value =0) and the template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}Table{% endblock %} {% block content %} <div class="table_order_form"> <h1>Order</h1> <form action="{% url 'table_order_view' %}" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class = "button table_order">PLACE ORDER</button> </form> </div> {% endblock %} And of course in the settings.py, I have declared: crispy_forms and CRISPY_TEMPLATE_PACK = 'bootstrap4' Problem 1: in forms.py, if the field item is a ModelChoiceField (the commented line), the form is out of whack, not "crispy" at all. But if I replace it with a usual form field such as IntegerField, the form is nicely formatted. Problem 2: in the template, I place a button right below the form, but when rendered, the button appears in parallel with the form, to its top right, and out of whack. Looking for some advice. Thanks. -
How to increment inside session in Django?
I try to create a counter inside session but I fail. the session is print out the result I added once and it doesn't increment the process when I want to add a new comment again. the comment will be added but counter is still equal to one so, how can I do increment into session: def post(self, request, user_slug, *args, **kwargs): my_question = UserAsking.objects.get(ask_slug=user_slug) userprof = UserProfile.objects.get(userasking__ask_slug=user_slug) comment_form = CommentForm(request.POST, instance=request.user) name = "%s %s" % (self.request.user.first_name, self.request.user.last_name) username = self.request.user.username logo = self.request.user.userprofile.logo.url if comment_form.is_valid(): comment_request = self.request.POST.get('comment', None) comment_form = Comment.objects.create(comment=comment_request, userasking_id=my_question.id, userprofile_id=userprof.id, name=name, username=username, logo=logo, comment_slug=my_question.ask_slug ) q = UserAsking.objects.get(ask_slug=my_question.ask_slug) c = comment_form u = comment_form.userprofile if 'notify_counts' in request.session: counter = request.session.get('notify_counts', 0) request.session['notify_counts'] = counter + 1 request.session.save() print('%s is commented your post: %s and comment is (%s) notify = %i' %(u, q, c, counter)) return redirect('community:question_view', user_slug) # return redirect('community:question_view', comment_form.userasking.ask_slug) return render(request, 'community/question_view.html', {'comment_form': comment_form}) -
Django - Business users to fill a form that is to be sent as an email
Here is the problem I got. I need non-developers to send occasional marketing emails via the Django admin. Nothing too crazy or customized to justify paying for mailchimp and/or similar services, but more than just plain old text (which is currently working). Markdown formatting will do. I am aware of render_to_strings and using html files. But, that would require either manipulation of those html files by non-developers or doing a lot of them to fit the marketing needs. Currently it's a simple TextField that gets sent as is to the customers. Here is the code. Models from django.db import models from django.conf import settings from django.core.mail import EmailMessage class Subscriber(models.Model): email = models.EmailField(unique=True) def __str__(self): return self.email class Email_update(models.Model): subject = models.CharField(max_length=150) content = models.TextField() -- *Change to Markdownx or something similar?* created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") def send(self, request): subscribers = Subscriber.objects.all() email_list = [] for sub in subscribers: email_list.append(sub.email) email = EmailMessage( self.subject, self.content, "email@company", ["email@company.com"], email_list, ) email.send() Admin.py from django.contrib import admin from .models import Subscriber, Email_update # Register your models here. def send_email_update(modeladmin, request, queryset): for email_update in queryset: email_update.send(request) send_email_update.short_description = "Send selected Newsletters to … -
How can solve errors on cookiecutter django?
I tried running django using cookiecutter but while running it there were some errors error message: [2020-10-12 01:18:22,782 basehttp] ERROR: "GET /en/ HTTP/1.1" 500 23209 [2020-10-12 01:18:23,900 basehttp] INFO: "GET /favicon.ico HTTP/1.1" 302 0 [2020-10-12 01:18:23,928 log] WARNING: Not Found: /en/favicon.ico/ [2020-10-12 01:18:23,928 basehttp] WARNING: "GET /en/favicon.ico/ HTTP/1.1" 404 1335 -
DRF, read/write permission for own profile
There is a write problem about own profile. I arrange some permissions and now super user can read and write all profiles. No problem at this part. But when it comes to normal user, I give a permission that user can only read it's own profile and write it also... Read part is working, but not write part. Here is part of my code. permissons.py from rest_framework import permissions class IsSuperUser(permissions.BasePermission): def has_permission(self, request, view): return request.user and request.user.is_superuser class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: if request.user.is_superuser: return True else: return obj == request.user else: return False views.py class ProfileViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = ProfileSerializer def get_permissions(self): # not very sure how to handle get permissions function. # if I try [IsSuperUser, IsOwner] it's not quite working. self.permission_classes = [IsSuperUser] # # I pass the IsOwner in condition, but ofcourse then it can't write # it's own profile only read if self.action == 'retrieve': self.permission_classes = [IsOwner] return super(self.__class__, self).get_permissions() How to arrange that user can read/write it's own profile? -
How to control the format of a duration field in django
I am making a simple clock in app. You push a button to punch in, and push it to punch out. I am trying to display the hours/mins between the out-punch and the in-punch. The code works, but I would like to change the output of the code. The output I am getting is something like this: I am pretty new to django and python in general, and would like to know how I can make this output something better, maybe like x:hours y:minutes or something like that. I definitely do not need the milliseconds. For clarity, the code is as follows: The model for the process is: class Punch(models.Model): employee = models.ForeignKey("timekeeper.User", on_delete=models.CASCADE, related_name="employee_punch") punchDate = models.DateField(default='2020-01-01') punchInTime = models.TimeField(default='01:01:01') punchOutTime = models.TimeField(null=True) worked = models.DurationField(null=True) def __str__(self): return f"Emp: {self.employee}, Timestamp: {self.punchDate}, IN: {self.punchInTime}, OUT:{self.punchOutTime} -- Worked: {self.worked}" The view code is: # Create your views here. def index(request): # The punch button was pushed if request.method == 'POST': r = request.POST.get('punch_button') # Record the punch on the Punch table if r == "PUNCH IN": Punch.objects.create( employee=request.user, punchInTime=datetime.now().time(), punchDate=datetime.now().date() ) elif r == "PUNCH OUT": now = datetime.now() p = Punch.objects.filter(employee=request.user, punchDate=now.date()).last() p.punchOutTime=now.time() # Converting punch times to … -
Django TypeError: Field 'id' expected a number but got <homeworkForm bound=True, valid=Unknown, fields=(title;descripiton;due)>
I have been trying to allow staff users to post homework to a database however I keep running into the issue above. I've tried setting data['id'] = 0/'' as well as dropped the table and makemigrations/migrate. models.py from django.db import models from teachers.models import Teacher class Homework(models.Model): title = models.CharField(max_length=100) descripiton = models.CharField(max_length=500) due = models.DateField() teacher = models.OneToOneField( Teacher, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.title form.py from django import forms class DateInput(forms.DateInput): input_type = 'date' class HomeworkForm(forms.Form): title = forms.CharField(label='Title', max_length=100) descripiton = forms.CharField(label='Descripiton', max_length=500) due = forms.DateField(label='Due', widget=DateInput) views.py def homework(request): if request.user.is_authenticated & request.user.is_staff: if request.method == 'POST': data = request.POST.copy() data['teacher'] = request.user.username request.POST = data print(request.POST) form = HomeworkForm(request.POST) if form.is_valid(): post = Homework(form) post.save() messages.info(request, 'Form sent') print('worked') return render(request, 'index/index.html') else: print('error in form') form = HomeworkForm() return render(request, 'dashboard/setHomework.html', {'form': form}) else: form = HomeworkForm() return render(request, 'dashboard/setHomework.html', {'form': form}) else: return redirect('index') -
Django contenttype : Is it possible to create generic relation dynamically without explicitly defining GenericRelation(X) in a model?
Say if we want to define generic relation from Bookmart to TaggedItem, we would define in the model as follow: class Bookmark(models.Model): url = models.URLField() tags = GenericRelation(TaggedItem) and if we want more than one generic relations to models. we would have to explicitly define multiple GenericRelation(x) statements. I was reading Django permissions documentation and stumble upon this code: content_type = ContentType.objects.get_for_model(BlogPost) permission = Permission.objects.create( codename='can_publish', name='Can Publish Posts', content_type=content_type ) As far as I see from the docs, BlogPost doesn't explicitly specify its generic relation(s). How is it doing it? -
Django, ERP/CMS software and E-commerce site on different servers
hope someone can help me with this. I am new to python and django, but already took some tutorials on how to create your own ERP/CMS and eCommerce projects on Django. My questions are... or what I want to do is: I want to install the ERP/CMS in my own local server (also it's gonna be the admin part for the eCommerce site) Install the eCommerce site on a Webhosting server Suppose that you have a business and you manage your operation with the ERP/CMS (inventory, employee, invoicing, etc) software created on Django. Then you realize that you want to create a website and sell online. So you create your eCommerce site on Django and deploy it in your preferred Webhosting. Questions: Considerations: Have to be in 2 separate servers and database For security reasons, both databases can not see each other or have any relation between them. In a situation your site gets hack, your primary database(ERP/CMS) will not be compromised. On the eCommerce site, the info the will be upload are Category, subcategory, products(description, attributes, availability[quatity > 0]), image, selling price, client, address. I know that Django can handle multiple databases. What will be the easiest and efficient … -
When I am writing the URL in browser the URL is not working- only the admin page is ascessed . Please show me a path
The name of my project is firstproject and web application is testapp. I am attaching urls.py , views.py and installed apps ` `` from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('hello/',views.greeting), path('admin/', admin.site.urls), ] from django.shortcuts import render from django.http import HttpResponse def greeting(request): s="<h1> hello this is greeting page</h1>" return HttpResponse(s) INSTALLED_APPS = [ 'testapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
_wrapped() missing 1 required positional argument: 'request': Issue with method decorator. (Django, Ratelimit Library)
I am attempting to use a method decorator so I can apply a decorator to the get_queryset method. My main goal is to limit the number of GET requests per minute to avoid query spam. Although, the problem is the decorator keeps throwing an error as written in the title. I've tried switching the order of and adding the self and request parameters, but so far no luck. Thanks! Ratelimit Library: https://django-ratelimit.readthedocs.io/en/stable/usage.html (Ctrl-F to class-based views section.) class ConnectMe(ListView, LoginRequiredMixin): model = Profile template_name = 'users/connect_me.html' context_object_name = 'profiles' paginate_by = 10 @method_decorator(ratelimit(key='ip', rate='1/m', method='GET')) def get_queryset(self): # original qs qs = super().get_queryset() .... -
Django Rest Framework & React Js ( Axios API Request ): After Incorrect authentication attempt, api returns 400
I'm creating a login system and basically, I have two inputs, one for username and the other for password. So when the user enters the correct credentials the API returns 200 response with some data but after incorrect credentials the django-rest-framework marks the request as 400 Bad Request and returns the response with 400 status code and no data, but this happens only when I'm sending a request from react js, after trying bad credentials from postman, the API returns: { "non_field_errors": [ "Incorrect credentials" ] } My Axios code: axios.post('http://192.168.0.29:8000/api/auth/login', { headers: { 'Content-Type': 'application/json' }, username: username, password: password }) .then((response) => { console.log(response.data); }) .catch(err => { console.log(err.data) alert('zjbs eroras') }); } -
What is the difference between the __lte and __gte in Django?
I am trying to figure out the difference between the __lte and __gte in Django. The reason being that I am trying to create a function with dates that can work only with a time frame, so I've been researching between Field Lookups Comparison. I've looked up several documentations https://docs.djangoproject.com/en/3.0/ref/models/querysets/#exclude but didn't reach a conclusive answer. -
update fields in a table of instances and had a default value
I m trying to had a template in which I populate list of payables and a field I can fill in with an amount I want to pay for each invoice this is my code: forms.py # class form without a model class paymentForm(forms.Form): #Note that it is not inheriting from forms.ModelForm number = forms.CharField(max_length=20) clientid = forms.IntegerField(widget=forms.HiddenInput()) clientname = forms.CharField(max_length=50) duedate = forms.DateField() montant = forms.DecimalField(max_digits=12, decimal_places=2) solde = forms.DecimalField(max_digits=12, decimal_places=2) payment = forms.DecimalField(max_digits=12, decimal_places=2, initial=0) def __init__(self, *args, **kwargs): super(paymentForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['number'].widget.attrs['readonly'] = True self.fields['clientname'].widget.attrs['readonly'] = True self.fields['duedate'].widget.attrs['readonly'] = True self.fields['montant'].widget.attrs['readonly'] = True self.fields['solde'].widget.attrs['readonly'] = True views.py with first line is a query and payables is a dictionary of payables (it works fine. but in this dictionnary payment field is not present as I just want to populate it in my template def updatepayables(request): count, payables = Payablesquery() form = paymentForm() # manage save if request.method == "POST": form = UpdateClientForm(request.POST) pass return render(request, 'payment/updatepayables.html', { "form": form, "payables": payables}) my template: <div class="container"> <h2>{{title}}</h2> <table class="table"> <thead> <tr> <th>client Name</th> <th>duedate</th> <th>number</th> <th>montant</th> <th>solde</th> <th>payment</th> </tr> </thead> <tbody> <form method="post" action=""> {% for payable in payables %} … -
Django: Is it possible to use a user model value as a db_table name
I am trying to assign each user a database table based on their location. I tried the following in my app and user models.py files. user models.py from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) zip_code = CharField(_("zip code"), max_length=5, default="78661") def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) app models.py from django.db import models from project1.users.models import User zipcode =User.objects.filter(zipcode=User.zip_code) class Data(models.Model): index = models.BigIntegerField(blank=True, null=True) temperature_surface = models.FloatField(db_column='Temperature_surface', blank=True, null=True) wind_speed= models.FloatField(db_column='Wind_speed_gust_surface', blank=True, null=True) class Meta: managed = False db_table =zipcode There are two problems I have with this method. I get the following attribute error for zip_code even though I am able to store the users zipcode in that variable. zipcode =User.objects.filter(zipcode=User.zip_code) AttributeError: type object 'User' has no attribute 'zip_code' The second problem is identifying which user is logged in and assigning that value to the db_table = zipcode. Is there a better way to accomplish this? I would ultimately like for the db_table value to match the users zip code. -
Best hosting solution for Django application with low volume but large storage needs
I'm developing a Django app for an archaeological database. The actual traffic to the site will be very small (think 100 unique visitors a day) so using a cheap low powered VPS seems sufficient. But there is a very large amount of media (photos/pdfs) to host and make available. Looking at Digital Ocean and Amazon (EC2 + EBS) seems to make hosting large amounts of content very expensive. Is there an answer for low powered large volume hosting? -
django: Primary key issue when saving modelform into postgresql
I have a model with au autofield, which has the primary key as such: class historical_recent_data(models.Model): id = models.AutoField(primary_key=True, auto_created = True) Id = models.CharField(max_length=100, verbose_name= 'references') Date = models.DateField() Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) def __str__(self): return self.reference Now, when I want to input data into the db table with a form in template, Django tries to give the id field a 1 value resulting in the following error: duplicate key value violates unique constraint "dashboard2_historical_recent_data2_pkey1" DETAIL: Key (id)=(1) already exists. there is more than 11,000 values in this db table, why django does not automatically generate the pk to be 11,001 when a new form is being posted into the table? -
How to make dynamic listdir in Django forms?
I need to be able to pick files from server using forms. Now im using os.listdir but its doesn't actualize when new file in folder shows up. List is updating only on server reboot. How can I make updating list of files without server restart? Thanks Im using Python 2.7 and Django 1.7. forms.py class OutFileForm(forms.Form): file_list = os.listdir(PATH) file_list_done = [("", "---")] for element in file_list: file_list_done.append((element, element)) outbound_file = forms.ChoiceField(label="Outbound", choices=file_list_done, required=True) -
How to hide and show SummerNote toolbar in response to focus and blur events
How do you hide or show the SummerNote toolbar in response to focus or blur events? I have a few forms with 3 or more textareas and I'd like to see the toolbar only on the focused area. I'm using Bootstrap and SummerNote on Django forms. I've tried with: // Select all textarea tags in the form var elements = $( "textarea" ); // Loop through all textarea elements for (var i = elements.length - 1; i >= 0; i--) { var element = elements[i]; $( '#' + element.id ).summernote({ airMode: false, // <-- False: Show toolbar; True: Hide toolbar toolbar: [ ['style', ['style']], ['font', ['bold', 'italic', 'subscript', 'superscript', 'clear']], ['color', ['color']], ['para', ['ol', 'ul', 'paragraph']], ['table', ['table']], ['insert', ['hr']], ['view', ['fullscreen']] ], callbacks: { onFocus: function() { $( '#' + this.id ).summernote({ airMode: false }); }, onBlur: function() { $( '#' + this.id ).summernote({ airMode: true }); } } }); } without results -
Call data without for loop from database
how do I call data from the database without the for loop in a HTML file? I'm a beginnger and in all tutorials I could find they use the for loop. But I want to get a url from my database and post it only once in the HTML file, but I dont want to hardcode it in the file. So in my models.py my class looks like this class Weburl(models.Model): source = models.URLField(max_length=200) In my views.py I call this from django.shortcuts import render def index(request): songs = Songs.objects.all() contacts = Contacts.objects.all() url = Weburl.objects.all() context = {'songs': songs, 'contacts': contacts, 'url': url} return render(request, 'index.html', context) Of course you need to import the stuff in views.py. Now I can call the songs, contacts and url in a for loop. But I don't want to call url as a for loop. So what needs to be changed? Other question, does it make senses to save the songs and contacts in the context variable? If anyone knows what to do, it would be great. Thanks in advance.