Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO PostgreSQL Query Issue
I have the following query in my two views. Here is both my views code. The query works fine in my NHS view but in my K-8 View it will not pull K-8 & NHS events when I run the query. The interesting thing is this works fine on my development server running SQL-Lite. So this is obviously a PostgreSQL issue. Appreciate any help on this. Thank you. @login_required @allowed_users(allowed_roles=['Admin', 'Administration','Teachers']) def K8Calendar(request): if request.method == "GET": calendar_events = PendingApprovalEvents.objects.filter(calendar = "K-8", approved = 1).order_by("-start_date") or PendingApprovalEvents.objects.filter(calendar = "K-8 & NHS", approved = 1).order_by("-start_date") userid = request.user.id print(calendar_events) my_filter = K8CalendarFilter(request.GET, queryset = calendar_events) calendar_events = my_filter.qs return render(request, 'eventscalendar/k8calendar.html', {'userid': userid, 'calendar_events':calendar_events, "my_filter": my_filter}) @login_required @allowed_users(allowed_roles=['Admin', 'Administration','Teachers']) def NHSCalendar(request): if request.method == "GET": calendar_events = PendingApprovalEvents.objects.filter(calendar = "NHS", approved = 1).order_by("-start_date") or PendingApprovalEvents.objects.filter(calendar = "K-8 & NHS", approved = 1).order_by("-start_date") userid = request.user.id my_filter = K8CalendarFilter(request.GET, queryset = calendar_events) calendar_events = my_filter.qs return render(request, 'eventscalendar/nhscalendar.html', {'userid': userid, 'calendar_events':calendar_events, "my_filter": my_filter}) -
How get image from images model to home page in django?
I am developing an ecommerce website with django. In my home page displayed product cards as you see in below image. enter image description here This product image in each card I take from my Product model (image field). When I hover over this image in home page, image is changing to other image. That is for I need other image, and I want take next image (display when I hover over) from my Product_images model. But I dont know how do that. Please help me. urls.py from django.urls import path from . import views from django.conf.urls.static import static urlpatterns = path('', views.home_page, name='amd-home'), path('product/<int:id>/', views.product_detail, name='product-detail'), path('about/', views.about, name='amd-about'), ] views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView from django.http import HttpResponse from .models import Product, Product_image, Product_details def home_page(request): products = Product.objects.all() images = Product_image.objects.all() context = {'products':products, 'images':images} return render(request, 'product/home.html', context) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=200) parent_id = models.IntegerField(default=0) description = models.TextField() image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Brand(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=400) image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Product(models.Model): title = models.CharField(max_length=200) image … -
Trying to get JSON data from POSTGRESQL in Django in localhost
I and my friends are doing a project and now it is time to merge our postgresql databases and I need to grab everything from mine and send it as a JSON file. As a programming newbie, I do not wanna mess up my database since I have done it once and was wondering what would be the easiest way to grab everything from http://127.0.0.1:8000/admin/ as a JSON file. I currently have the home page and the footer information created and can be controlled from the admin page and need those data. def home(request): if request.method == 'POST': form = ContactForm(request.POST or None) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('New Enquiry', message, sender_email, ['warp.dev.group@gmail.com']) return HttpResponse('Thanks for contacting us!') else: form = ContactForm() context = { "homepage": HomePage.objects.filter(name="homepage").first(), "footer": Footer.objects.filter(name="footer").first(), 'form': form } return render(request, 'member/home.html', context) class Footer(models.Model): name = models.CharField(max_length=20, blank=True) description = models.CharField(max_length=50, blank=True) contact_number = models.IntegerField(blank=True) facebook = models.URLField(max_length=50, blank=True) twitter = models.URLField(max_length=50, blank=True) instagram = models.URLField(max_length=50, blank=True) email = models.EmailField(max_length=30, blank=True) footer_data = models.CharField(max_length=30, blank=True) terms_and_conditions = models.URLField(max_length=250, blank=True) faq = models.URLField(max_length=250, blank=True) def __str__(self): return f'{self.name}' class HomePage(models.Model): name = models.CharField(max_length=10, blank=True) … -
Django/jQuery- get submit button value from multiple buttons
I have the next submit buttons inside a post form: <div class="col-md-4 col-sm-4"> <button type="submit" class="btn btn-default btn-block" value="True" id="subButton" name="is_attending" onclick="FbotonOn()">Yes, i'm in!</button> </div> <div class="col-md-4 col-sm-4"> <button type="submit" class="btn btn-default btn-block" value="False" id="subButton" name="is_attending" onclick="FbotonOf()">Sorry, i can't!</button> </div> And this jQuery: $('#post-form').on('submit', function(e) { e.preventDefault(); $("#subButton").click(function(e){ e.preventDefault(); var my_button = $(this).val(); $.ajax({ type : "POST", url: "{% url 'guest_update' %}", data: { guest_id : "{{ guest.guest_id }}", invites_names : $('#name').val(), phone_no : $('#phone').val(), best_wishes : $('#wishes').val(), with_partner : $('#myCheck:checked').val(), partner_name : $('#partner_name').val(), is_attending : my_button, csrfmiddlewaretoken: '{{ csrf_token }}', dataType: "json", }, success: function(data){ $('output').html(data.msg) }, failure: function() { } }); }); }); Every time I try to submit a form and press the first button, it works, but the second one, it doesn't. I've tried also without the click function but if a press the second button, I receive the first one value. Where am I wrong? -
how to use 2dicts in a for loop in Django template?
I have context as below : context = { 'author': author, 'books':books, } Now I need to use author and books in One for loop like this : {% for each in ***author & books*** %} <tr> <td>{{ each.author.name }}</td> <td>{{ each.book.name }}</td> <td>{{ each.book.pubishDate }}</td> </tr> {% endfor %} How to make such a for loop in Django template? Thanks all. -
Django: Starting explicit transaction while creating/saving objects
I've got a Django application, which has an form to order stuff. When the form is submitted, I am creating a new user and new order. The username should be the same as the order pk/id (which has an auto-increment) and 1:1 relation between user and order is required by business. And this brings me to my problem: Model looks like this (simplified). User is from django.contrib.auth.models class Order(models.Model): user = models.OneToOneField(User) comment = models.TextField order_status = models.CharField price = models.DecimalField(..) In order to get this id/pk of the order, I need to create and save it. But as a User is required, I need to create and save it even before the order is created. According to the documentation of Django, it creates transactions automatically. Instead I would like to open it by myself then fetch the next ID for the order and then create and save user and order. Is this the right way to do? And how would I accomplish this with Django? I am fairly new to Django and asking for advice. Thanks! -
Not Found: /addTodoItem/
i work on todo project and have a error. my models :: class TodoList(models.Model): content = models.TextField() my urls :: urlpatterns = [ path('', views.TodoappView , name = "todoappview"), path('', views.addTodoItem, name = 'Add Todo Item'), path('todoapp/<int:i>/', views.deleteTodoView, name = 'deleteTodoView') ] and my views:: def TodoappView(request): all_todo_items = models.TodoList.objects.all() return render(request, 'todoapp/todolist.html', {'all_items':all_todo_items}) def addTodoItem(request): x = request.post['content'] new_item = models.TodoList(content = x) new_item.save() return HttpResponseRedirect('/todoapp/') def deleteTodoView(request, i): y = models.TodoList.objects.get(id= i) y.delete() return HttpResponseRedirect('/todoapp/') and i have this error :: (Not Found: /addTodoItem/) Can anyone help me ????!!!!!!!!! -
How to control whether an object is related to a model or not in Django?
There are several models that are related to User model: class User(AbstractUser): # Its fields class Model_1(models.Model) user = models.OneToOneField('User', on_delete=models.CASCADE) # other fields class Model_2(models.Model) user = models.OneToOneField('User', on_delete=models.CASCADE) # other fields class Model_3(models.Model) user = models.OneToOneField('User', on_delete=models.CASCADE) # other fields class Model_4(models.Model) user = models.OneToOneField('User', on_delete=models.CASCADE) # other fields and in the view: def index(request): # If the user is related to model one, do something # If the user is related to model two, do something # If the user is related to model three, do something # If the user is related to model four, do something # Otherwise return to the home page After the user sends the request to View, how do I determine which of these models it belongs to? Thank you in advance. -
Getting "page not found" error while trying to go back to the previous page after successful deletion using DeleteView in django
So I'm deleting an object of a model using DeleteView and redirecting to homePage after successful deletion, works fine. But the problem is when I try to get back to the previous page after deletion(using the left arrow button in the browser). I get "page not found" error which makes total sense because I'm trying to get back to the deletion page of an object which no longer exist. How do I prevent this from happening? -
Django: Sending e-mails asynchronous
I've got a Django application, which has an form to order stuff. After the form is submitted you should be forwarded to a confirmation site, while two e-mails should be send as well. Sending an e-mail with Django is not the problem send_mail(subject, plain_message, from_email, [order.customer.email], html_message=html_message) but it seems not happening in a asynchronous way as it takes some time. I would just like call my send_email method, let the sending be handled asynchronous and then proceed with forwarding. How would I accomplish this, what kind of possibilities do I have? I am fairly new to Django/Python but I imagine creating a Thread or sth like it? Whats best practise for this case? -
Django - pre_delete signal not updating instance's foreign key
I am trying to use a pre_delete signal for a Like model. Inside the signal handler, I try to update the num_of_likes field of one of Like's foreign keys, Book. My problem is that changes to a_book.num_of_likes inside my pre_delete signal handler do not reflect outside pre_delete. My code will make what the problem is very clear, I think (please pay special attention to the comments and print statements): books/models.py: class Book(models.Model): num_of_likes = models.IntegerField() likes/models.py: class Like(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book) likes/views.py: class DeleteLikeView(APIView): def post(self, request, book): book = get_object_or_404(Book, id=book) print(book.num_of_likes) # Prints, say, 10 like = Like.objects.get(user=request.user, book=book) like.delete() # triggers signal handler below (should update `book.num_of_likes`) print(book.num_of_likes) # Still prints 10, expected 9 <------ PROBLEM return ... likes/signals.py: @receiver(pre_delete, sender=Like) def delete_book_like(sender, instance, **kwargs): print(instance.book.num_of_likes) # Prints 10 instance.book.num_of_likes -= 1 instance.book.save() print(instance.book.num_of_likes) # Prints 9, as expected Why does book.num_of_likes get updated inside delete_book_like but then changes don't show up in DeleteLikeView? -
Queryset to max value for group
I'd like to select the row with the max value, group them by line_nm and get the fields of this lines. In My models.py I have the follow fields: class SmdDropRateCe(models.Model): sumr_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) shift_code = models.CharField(max_length=10, blank=True, null=True) model_code = models.CharField(max_length=30, blank=True, null=True) equip_id = models.CharField(max_length=30, blank=True, null=True) mat_code = models.CharField(max_length=30, blank=True, null=True) reel_no = models.CharField(max_length=10, blank=True, null=True) err_num = models.IntegerField(blank=True, null=True) pckp_num = models.IntegerField(blank=True, null=True) plac_num = models.IntegerField(blank=True, null=True) err_ppm = models.FloatField(blank=True, null=True) I'd like to group then by model_code and recovery the data from the rows with the max err_ppm fields Example: recovery the fields: line_nm , equip_id , reel_no err_ppm I tried the follow: dropWorst1 = dropToday.values('line_nm').annotate(worst1=Max('err_ppm')).order_by('line_nm') However it only returns the fields: line_nm, worst1 I also tried: dropWorst1 = dropToday.order_by('-err_ppm','line_nm').distinct('line_nm') But it returns error: DISTINCT ON fields is not supported by this database backend Because I'm using mysql Someone knows how to fix this issue, I already look for many different solutions, without success. Tks in advance -
Django: Create view in admin panel for multi file upload
I have a model (MediaModel) with an imagefield, a description (charfield) and tags (manytomany with Tag model). The goal is to be able to upload an image with a description, some tags etc, in the admin panel. This part works fine. But I would like to be able to upload multiple file at a time. So, how can I have an admin page with an upload field (which allow multiple file upload), and with a tag list to select, which will create a MediaModel for each uploaded file. I don't want to create another model: I want to create a MediaModel with an empty description and the selected tags for each uploaded file. Any help is appreciated! -
Stop infinite loop in self-referencing models
I am writing a little utility which allows me to populate data models with a number of records. I used python faker to set the values for each field based on their field-type. What I do next, is that I use model._meta.get_fields to extract all the fields, remove all Rel types, and then populate non-relational fields with the correct values. For relational fields (where .re_relation = True) I follow the relation to the related model, then do the same for that model as well until I reach a model where there is no more relations to other models. Then create instances for each model. Basically a recursive process. My problem is with self-referencing models which cause an infinite loop. I thought of setting these instances to null but what about instances where null is set to False? Is there any clean way to handle situations like this? I couldn't find anything on the net or stackoverflow. ps: the code is pretty long so I didn't post anything. But I can if it's necessary. -
Django SIgnals Cannot assign... 'Mensagem.Chat' must be a "Chat" instance
I'm finishing a college project and I'm stuck on generating notifications whenever a user sends a message to another, I have a notification model, but I'm not able to send the message to the notification in django admin I can already insert the notification and display the screen, but only manually, when the user sends the message, it is not sent to the notification model :'( I'm not able to create a chat instance to put here stream = Mensagem(texto=message, chat=chat) stream.save() from users.models import MyUser from Chat.models import Mensagem from products.models import Product class Notification(models.Model): title = models.ForeignKey(Product, null=True, blank=True,on_delete=models.CASCADE) message = models.ForeignKey(Mensagem, null=True, blank=True,on_delete=models.CASCADE) viewed = models.BooleanField(default=False) sender = models.ForeignKey(MyUser, null=True, blank=True, on_delete=models.CASCADE,related_name="noti_from_user") user = models.ForeignKey(MyUser, null=True, blank=True, on_delete=models.CASCADE, related_name="noti_to_user") from django.db import models from django.db.models.signals import post_save, post_delete class Chat(models.Model): codigoSala = models.CharField(max_length=20, unique=True) locador = models.CharField(max_length=50, blank=False, null=False) locatario = models.CharField(max_length=50, blank=False, null=False) nomeSala = models.CharField(max_length=200, blank=True, null=True) def __str__(self): super().__init__() return self.codigoSala def add_chat(self): sender_message = Chat( self.codigoSala, self.locador, self.locatario, self.nomeSala) sender_message.save() class Mensagem(models.Model): texto = models.CharField(max_length=80) chat = models.ForeignKey(Chat, on_delete=models.CASCADE) def __str__(self): return self.texto def add_message(sender, instance, created, **kwargs): message = instance chat = Chat.objects.create() stream = Mensagem(texto=message, chat=chat) stream.save() post_save.connect(Mensagem.add_message, sender=Mensagem) error: Cannot … -
KeyError at /api/login 'user'
This user keyword error is showing in my login api. I am not sure why. I am guessing user instance is not available in the login view. I am new and I dont know the reason. This is my login view: class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return response.Response({"token": token.key}, status=status.HTTP_200_OK) This is my serializers: class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(label='Email Address') class Meta: model = User fields = [ 'email', 'password', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # user = None email = data.get("email", None) password = data.get("password") if not email: raise serializers.ValidationError("Email is required for login") if not password: raise serializers.ValidationError("Password is required for login") user = authenticate(email=email, password=password) if not user: raise serializers.ValidationError("This email is not valid/already exists") return data -
django: pass formset data into another view
My issue kind of build on this one post How to pass data between django views. I am trying to do a similar thing which is to use the data inputed in view 1 into view2. However, the challenge is that with a formset, I need to be accessing multiple rows of data input and not just values. I don't know how to achieve this here is what I have so far: view 1: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount', 'customer_name')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #blank_form = formset.empty_form if formset.is_valid(): request.session['sale'] = request.POST['sale'] for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) return redirect('/dash22.html') return render(request, 'new_sale.html', {'formset':formset}) and view 2: def invoice_view(request): request = request.session.get('sale')) #... i need to get each row of the formset from the above view #and I am stuck!! I am hoping that someone would have a solution, I cannot find anything about this in django doc. -
Django: latest record for each value of another field
Let us say we have a TemperatureForecast model (see below for a Django definition). A forecaster will produce many forecasts of the same target period (say 2021-01-01 6AM UTC), because it will forecast the temperature for that period again and again (at 2020-12-31 8PM UTC, at 2020-12-31 9PM UTC and so on). Now say we would like to know the "latest" (to be defined after the model definition) temperature forecast, by a given forecaster, for each hour from 2021-01-01 1AM to 2021-01-31 10AM. That is, I need to retrieve the "latest" record for each target datetime. In this example, we would have (at most) 10 records. The Django model (with Postgres backend) would look as follows: from django.db import models from .forecaster import Forecaster class TemperatureForecast(models.Model): forecaster = models.ForeignKey(Forecaster, on_delete=models.PROTECT) temperature_in_c = models.FloatField() forecast_datetime = models.DateTimeField() forecast_time_delta_in_s = models.IntegerField() # the time of creation of the record # not the time of the forecast was actually made created_at = models.DateTimeField(auto_now_add=True) forecast_datetime is the field we would like to group by and forecast_time_delta_in_s is the field we would to minimize by ("latest" means min(forecast_time_delta_in_s)). (Assuming created_at was reliable, forecast_time_delta_in_s can be thought of as forecast_datetime - created_at. But created_at cannot be … -
fillter and get all the values greater than current date
I want to filter and get all the values greater than current date. I researched about it, but couldn't able to figure out what is wrong in my code. below is models.py class TrainingDetails(models.Model): code = models.CharField(max_length=60) name = models.CharField(max_length=60) description = models.TextField(default='') trainer_name = models.ManyToManyField(TrainerDetails, blank=True, related_name='trainer',default='') tutorial_image = models.ImageField(upload_to='media') agenda = models.FileField(upload_to='media') from_time = models.ManyToManyField(TrainingDate,blank=True, related_name='from_times', default='') trainingdate = models.ManyToManyField(TrainingDate,blank=True, related_name='dates', default='') to_time = models.ManyToManyField(TrainingDate,blank=True, related_name='to_times', default='') url = models.ManyToManyField(TrainingData, blank=True, related_name='links', default='') document = models.ManyToManyField(TrainingData, blank=True, related_name='files' ,default='') tutorial_name = models.ManyToManyField(TrainingData, blank=True, related_name='tut_name' ,default='') department = models.CharField(max_length=60) is_active = models.BooleanField() def __str__(self): return self.name class Meta: verbose_name_plural = "TrainingDetails" views.py class TrainingDetailsViewSet(viewsets.ModelViewSet): queryset = TrainingDetails.objects.all().order_by('code') serializer_class = TrainingDetailsSerializer def get_queryset(self): queryset = self.queryset today = datetime.date.today() trainingdate = TrainingDate.objects.values('trainingdate') query_set = queryset.filter(trainingdate__gte = today) return query_set -
how to fix import error in django project?
i have a django project, i want to import views from my app called projects from django.urls import path from . import views urlpatterns = [ path("", views.project_index, name="project_index"), path("<int:pk>/", views.project_detail, name="project_detail"), ] i got this error Traceback (most recent call last): File "d:/firstwebapp/mysite/projects/urls.py", line 2, in <module> from . import views ImportError: attempted relative import with no known parent package -
Method Not Allowed (POST): /
I'm new to Django. I am trying to use Django Tutorial , but when i click on the button to vote I've got this error: Method Not Allowed (POST): /hewramanapp/2/results/ Method Not Allowed: /hewramanapp/2/results/ [29/Oct/2020 10:56:33] "POST /hewramanapp/2/results/ HTTP/1.1" 405 0 everything was good til i change some views from function to generic view i don't know where i did a mistake, thanks for help. views: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from .models import Proverb, Choice from django.urls import reverse from django.views import generic # Create your views here. class IndexView(generic.ListView): template_name = 'hewramanapp/index.html' context_object_name = 'latest_proverb_list' def get_queryset(self): return Proverb.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Proverb template_name = 'hewramanapp/detail.html' class ResultsView(generic.DetailView): model = Proverb template_name = 'hewramanapp/results.html' def vote(request, proverb_id): proverb = get_object_or_404(Proverb, pk=proverb_id) try: selected_choice = proverb.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'hewramanapp/detail.html', { 'proverb': proverb, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('hewramanapp:results', args=(proverb.id,))) urls: from django.urls import path from . import views app_name = … -
Why Django project deployment does not work on Apache server?
I have a problem deploying the Django project. This project works well locally. But when deploying on the server, it has a problem. The project folder structure is as follows: project ├── api │ ├── __init__.py │ ├── requests.py │ └── urls.py ├── Services │ ├── __init__.py │ └── RequestService.py ├── DataAccess │ ├── __init__.py │ ├── sqlBase.py │ ├── sqlHelper.py │ └── sqlHelperBids.py ├── Model │ ├── __init__.py │ ├── GetActiveRequestsChangeByDestinationCountry_Result.py │ └── ..and so on.py ├── requirements.txt └── manage.py With repeated checks, I realize that this line has a problem: in requests.py : from Services.RequestService import RequestService and all calls are as follows: from django.http import HttpResponse from rest_framework.decorators import api_view from rest_framework.utils import json from DataAccess.sqlHelper import SqlHelper from Model.ApiResponse import ApiResponse from Services.RequestService import RequestService from Utility.Assistant import Assistant The project runs well when I clear this line The permissions of the folders were also checked, but there was no problem. -
502 Bad Gateway in google cloud using Django and postgresql
I deployed my Django app with postgresql db to google app. When I ran the app local it worked fine. After deploying the app everytime I tries to log-in to the site or retrieve data from the data base I get this error. 502 Bad Gateway nginx Django's data base settings If you need more information to solve this issue please let me know. Thanks! logs: 2020-10-29 10:43:25 default[20201029t122844] "GET / HTTP/1.1" 200 2020-10-29 10:43:26 default[20201029t122844] "GET /static/css/master.css HTTP/1.1" 304 2020-10-29 10:43:26 default[20201029t122844] "GET /static/css/home.css HTTP/1.1" 304 2020-10-29 10:43:26 default[20201029t122844] "GET /static/images/logo.png HTTP/1.1" 304 2020-10-29 10:43:26 default[20201029t122844] "GET /static/images/Yosemite.jpg HTTP/1.1" 304 2020-10-29 10:43:27 default[20201029t122844] "GET /accounts/login/ HTTP/1.1" 200 2020-10-29 10:44:09 default[20201029t122844] [2020-10-29 10:44:09 +0000] [10] [CRITICAL] WORKER TIMEOUT (pid:124) 2020-10-29 10:44:10 default[20201029t122844] [2020-10-29 10:44:10 +0000] [145] [INFO] Booting worker with pid: 145 -
How exactly do I use crispy_addon to prepend a form field?
I'm using Django crispy forms and modelform_factory to generate my form. It looks something like this: ModelForm = modelform_factory(Street) form = ModelForm(request.POST or None, instance=my_record) Then in the template I run this: {% crispy form %} And it generates my bootstrap4 form exactly as intended. However, I'd like to have a single field in my very long form to have a prepended text (@ for a Twitter handle). In the documentation it reads: templatetags.crispy_forms_field.crispy_addon(field, append='', prepend='', form_show_labels=True)[source] Renders a form field using bootstrap’s prepended or appended text: {% crispy_addon form.my_field prepend="$" append=".00" %} You can also just prepend or append like so {% crispy_addon form.my_field prepend=”$” %} {% crispy_addon form.my_field append=”.00” %} I've tried using this as follows in my template: {% crispy form %} {% crispy_addon form.url prepend=”@” %} But this returns the following error: Invalid block tag on line 12: 'crispy_addon', expected 'endblock'. Did you forget to register or load this tag? What am I doing wrong here? -
Copying text of <td> elements of table by clicking on text with javascript
I have a table with some of its columns containing text that is gonna be copied quite often. Despite knowing no javascript, I adventured myself into the challenge of making the content copyable on click and managed to get this working: function copy(event) { console.log("Triggered") var target = event.target || event.srcElement; console.log("Targeted") var copyText = target.innerText || target.textContent; navigator.clipboard.writeText(copyText) } var plist = document.querySelectorAll("p"); for (var i=0; i < plist.length; i++) { plist[i].addEventListener("click", copy) } <!DOCTYPE html> <html> <body> <h1>Copy selector Test</h1> <p>Hi There.</p> <p>I want to copy</p> <p>each of these p's</p> <p>by clicking them.</p> </body> </html> Well, considering my javascript knowledge, I'm pretty sure that isn't the most efficient or correct way of doing it (looping each element and adding an eventlistener to each one seems a bit of unnecesary work to me). Any correction is welcome. Now let's say I want each of the cells of the "Last" column to be copied in the same way that the p's were copied in my snippet. How could I get it done? It would be also cool to highlight the text that's been copied (I tried with .select() but apparently that only works with input elements). The table is gonna …