Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page 2 elements not clickable after implementing infinite scroll in Django
I used waypoints to implement an infinite scroll by follow this guide. The infinite scroll works fine but for some reason, page 2 elements are not clickable while page 1 elements are clickable. In other words the page loads and works fine until I scroll down to page 2 and suddenly all the "href" and other clickable elements are no longer clickable. Here is my code. <div class="mt-5 ads_container"> <div class="container-fluid infinite-container"> {% for ad in ad_list %} {% if forloop.counter0|divisibleby:4 %} <div class="row infinite-item"> <div class="col-sm-12"> <div class="latest-magazine clearfix"> <div class="latest-ads-space clearfix"> {% endif %} <div class="late-ad"> <div class="inner"> <a href={% url 'advert' ad_pk=ad.id %}> <!-- <img data-src="{{ ad.profile_pic }}" class="img-responsive lazyloaded"--> <!-- src="{{ ad.profile_pic }}"/>--> <div class="pic_div" style="background-image: url({{ ad.profile_pic }}); background-size: contain; background-repeat: no-repeat; background-position: center;"></div> </a> <div class="p-a" style="height: 70px;"> <em>{{ ad.Ad_title|capfirst|shorten_title }}</em> <div class="clearfix"> <em></em> <em class="text-success">R{{ad.price}}</em><em> {% timezone "Africa/Johannesburg" %}{{ ad.date_created|timesince }}{% endtimezone %}</em> </div> </div> </div> </div> {% if forloop.counter0|add:"1" in break_pts or forloop.counter0|add:"1" == ad_list|length %} </div> </div> </div> </div> {% endif %} {% endfor %} </div> {% if ad_list.has_next %} <a class="infinite-more-link" href="?page={{ ad_list.next_page_number }}"></a> {% endif %} <div class="d-flex justify-content-center" style="display:none;"> <div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> </div> … -
Django convert local time to utc time
This is my code using this i am converting my time to in utc time : pickup_time = "03:00 PM" local_time = pytz.timezone("Asia/Kolkata") naive_datetime = datetime.datetime.strptime (pickup_time, "%I:%M %p") local_datetime = local_time.localize(naive_datetime, is_dst=None) utc_datetime = local_datetime.astimezone(pytz.utc) print(utc_datetime) print(utc_datetime.strftime("%I:%M %p")) In result i am getting like : 1900-01-01 09:07:00+00:00 09:07 AM but according to me it should be 09:30 AM .in IST offset of UTC+05:30 but i am getting 6 hours. can anyone please suggest me what i am doing wrong here . -
How to filter option in Django?
i have 3 models involved in this issue Category, Survey and Question Category.py from django.db import models from django.utils.translation import gettext_lazy as _ class Category(models.Model): name = models.CharField(_("Name"), max_length=400) description = models.CharField(_("Description"), max_length=2000, blank=True, null=True) class Meta: verbose_name = _("category") verbose_name_plural = _("categories") def __str__(self): return self.name def slugify(self): return slugify(str(self)) Survey.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.urls import reverse from django.conf import settings from django.utils.timezone import now # from .category import Category # Create your models here. class Survey(models.Model): ALL_IN_ONE_PAGE = 0 BY_QUESTION = 1 BY_CATEGORY = 2 DISPLAY_METHOD_CHOICES = [ (BY_QUESTION, _("By question")), (BY_CATEGORY, _("By category")), (ALL_IN_ONE_PAGE, _("All in one page")), ] name = models.CharField(_("Name"), max_length=400) description = models.TextField(_("Description")) is_published = models.BooleanField(_("Users can see it and answer it"), default=True) editable_answers = models.BooleanField(_("Users can edit their answers afterwards"), default=True) display_method = models.SmallIntegerField( _("Display method"), choices=DISPLAY_METHOD_CHOICES, default=ALL_IN_ONE_PAGE ) category = models.ManyToManyField("Category", verbose_name=_("Category"), blank=True, related_name="surveys") template = models.CharField(_("Template"), max_length=255, null=True, blank=True) publish_date = models.DateField(_("Publication date"), blank=True, null=False, default=now) class Meta: verbose_name = _("survey") verbose_name_plural = _("surveys") @property def safe_name(self): return self.name.replace(" ", "_").encode("utf-8").decode("ISO-8859-1") def latest_answer_date(self): """Return the latest answer date. Return None is there is no response.""" min_ = None for response in self.responses.all(): if … -
why is this error coming "Unexpected EOF" ? in my django- Ajax project
I'm trying to make a django sheet there using ajax so that I can change it without refreshing the page. but I faced such a problem Unexpected EOF, and I don't know what to do. and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and it is base.html file: … -
Queryset AttributeError: the 'dict' object has no attribute '_meta'
models.py class keywords(models.Model): user = models.ForeignKey(User,related_name="users",on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add = True) searchedword = models.CharField(max_length=50) class keywordsProxy(keywords): class Meta: proxy = True admin.py @admin.register(keywordsProxy) class keywordsProxyAdmin(admin.ModelAdmin): list_display = ('searchedword','get_cword') def get_queryset(self, request): qs = super().get_queryset(request) return qs.values('searchedword').annotate(cword=Count('searchedword')) def get_cword(self, instance): return instance.cword get_cword.short_description = "count" I want to display count of searched words like this: searchedword count python 3 java 2 . . . . . . But I got : 'dict' object has no attribute '_meta' if I change query to: return qs.annotate(cword=Count('searchedword')) or return keywordsProxy.objects.all().annotate(cword=Count("searchedword")) result will be not correct: searchedword count python 1 python 1 python 1 java 1 java 1 Any help on how to solve this is welcome. Thank you in advance -
Django DRY - How to extend two .html files inside a Django Template?
What do I want? I want to extend cards/apps.html inside addstudents.html so that I don't need to write the chucks of codes multiple times. What can I do to extends multiple .html files inside DJANGO template? Error I am getting 'extends' cannot appear more than once in the same template WHAT TO DO? NOTE: I don't want to use {% include %}, because the situation/condition isn't suitable. SOME INFORMATION YOU MAY NEED... Inside cards/apps.html <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">{{card_title}}</h6> </div> <div class="card-body"> {% block card_body %} {% endblock %} </div> Inside addstudents.html {% extends 'layouts/panel.html' %} {% extends 'apps/card.html' %} {% load static %} {% block content %} {% with card_title='My Card TITLE' %} {% block card_body %} ...SOME FORM, .... SOME PARAGRAPH {% endblock %} {% endblock %} What's inside layouts/panel.html layouts/panel.html contains some menu and navbars items [including CSS, bootstrap and JS dependencies]. What's apps/card.html? apps/card.html contains the code-snippet of HTML and Bootstrap CARD. And I don't want to write this code multiple times. That's why I want it to be manipulated via Django Template Tags. HOPE YOU UNDERSTOOD -
How to disabled field with if-else condition in JS
I have a problem on disabled input field on certain condition. In this case, user can add multiple row in a form. But, the number of row is greater than four, then some of the field will be disabled. Here my segment of JavaScript. In order to know the number of row already exceed or not, I check using index number. But the problem is, the code seems like didn't check the if-else condition. var valIndex =0; for (var i=0, formCount=forms.length; i<formCount; i++) { valIndex = i+1; $(forms.get(i)).find('.assign_label_number').text(" - " + valIndex + nth(valIndex)); console.log(valIndex); document.getElementById("gift").addEventListener("click", function(){ var gift = $(forms.get(i)).find('input[id^=id_Phone1][id$=less_tax_examption]'); if(valIndex => 4){ console.log('disabled') gift.prop("disabled", true); } else{ console.log('enable') gift.prop("disabled", false); } }); }); Actually it work just fine if I remove the document.getElementById. But since there is few field with different condition, so I need to differentiate each of the button by Id. I already tried to used .attr("disabled", true) also didn't work Please correct me if I'm wrong. Thank you in advanced for your help and time. -
load content of one HTML template on div of another HTML template using DJANGO
am new to django concept , so i want to include one html template inside div of another html template . i tried using iframe but when i load the page it says localhost refused to connect , then i referred some of the stack answers and i did it with include but when i give include the page is not loading . IndexPage.html <section id="testimonial" class="testimonial section-padding"> <div class="overlay"></div> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-7 col-md-12 col-sm-12 col-xs-12"> <div id="testimonials" class="owl-carousel wow fadeInUp" data-wow-delay="1.2s"> <div class="item"> <div class="testimonial-item"> <div class="info"> <!-- <iframe id="encoder_iframe" height=75% width="50%" src='/templates/index.html'></iframe> --> {% include "index.html" %} </div> </div> </div> </div> </div> </div> </section> index.html {% extends 'base.html' %} {% block content %} <h1 class="page-header"></h1> <p class="lead"></p> <p class="lead"><a href="/products">Customer ListList</a>.</p> {% endblock %} so have to include index.html inside div of indexpage.html structure of folder -
How to merge two models into one single form?
Is it possible to merge two different models into a single form? if yes then please provide me with the solution. basically, I want to create a form in which I can also add images but it is not working as I want to make it work. models.py: class Mobile(models.Model): brand = models.CharField(max_length=30) price = models.IntegerField(default=1) color = models.CharField(max_length=30) screen_size = models.IntegerField(default=5) os = models.CharField(max_length=30, default='Samsung') def __unicode__(self): return self.brand class MobileImage(models.Model): device = models.ForeignKey(Mobile, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images/') def __unicode__(self): return self.device forms.py: from django import forms from .models import Mobile, Laptop, MobileImage class AddMobileForm(forms.ModelForm): class Meta: model = Mobile fields = '__all__' views.py: def addmobile(request): if request.method == 'POST': mobileform = AddMobileForm(request.POST) if mobileform.is_valid(): mobileform.save() return redirect('mobile') else: mobileform = AddMobileForm() context = { 'mobile_form': mobileform } return render(request, 'device/mobile_form.html', context) -
Best way to detect new objects in Django?
Although I have a decent understanding of Django and how to work with exchanges using HTTP I am still very naive when it comes to websockets, channels, ajax, etc. My notification system is built on a custom notification model, so I would like to be able to detect when a new object is created under certain filters. My question is: How can I go about detecting when a new object is created and update the webpage without refreshing? Thanks! -
How to get products according to User in Django?
I have relation between Customer and Products, and customer_id is saving in Product model table, but I want to display products on my view page according to customer, suppose if a customer logged in using his details then he can see only his products, but currently he can see all products. Please let me know How I can do it. Here is my models.py file... class Customer(models.Model): name=models.CharField(default=None) class Product(models.Model): name=models.CharField(default=None) customer=models.Foreignkey(Customer, related_name='customer_product', on_delete=models.CASCADE) here is my views.py file... def display_data(request): test_display = Product.objects.all() context = { 'test_display': test_display } return render(request, 'page.html', context) here is my page.html file...here i am trying to display products according to loggedin customer.. <p>{{test_display.count}}</p> -
how to resize of multiple images in Django models and also payment integration problem
**how can i resize of this all my image fields...photo_main to photo_8 ** another one problem is when user submit payment but payment was invalid than post will save problem... another one is user select one by one image input fields is there any way to user select multiple images at a same time... class Post(models.Model): post_id = models.CharField(default=abc, max_length=14) ages = models.IntegerField(null=True, default=0, validators=[ MaxValueValidator(120), MinValueValidator(18) ] ) zip_codes = models.IntegerField(null=True) address_user = models.CharField(max_length=400, null=True) title = models.CharField(max_length=200) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) phone = models.CharField(max_length=14, null=True) phone_code = models.CharField(max_length=7, choices=phone_codes, default=+91) # description = RichTextField(blank=True, null=True) description = models.TextField(blank=True, null=True) photo_main = models.ImageField(upload_to=upload_path) photo_1 = models.ImageField(upload_to=upload_path, blank=True) photo_2 = models.ImageField(upload_to=upload_path, blank=True) photo_3 = models.ImageField(upload_to=upload_path, blank=True) photo_4 = models.ImageField(upload_to=upload_path, blank=True) photo_5 = models.ImageField(upload_to=upload_path, blank=True) photo_6 = models.ImageField(upload_to=upload_path, blank=True) photo_7 = models.ImageField(upload_to=upload_path, blank=True) photo_8 = models.ImageField(upload_to=upload_path, blank=True) is_publice = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=False) today_date_time = models.CharField(default=d2, max_length=50) plan = models.ForeignKey(Plans_info, on_delete=models.CASCADE, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.category) # def get_absolute_url(self): # return reverse('post_detail', kwargs={'pk': self.pk}) class Meta: # managed = True db_table = 'Skoapp_post' i'm also using this save function … -
Django | Redirect View after "liking" without scrolling
I'm making a simple blog app. I have added the ability to "like" a post on your feed. However, the only way I can figure out closing a view is by returning some form of redirect. The problem is, if the post you're "liking" is halfway down the page, I don't want it to reset the zoom to the top of the page again. Is there a way simply to redirect to the same page without affecting zoom? Here's my post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author") likes = models.ManyToManyField(User, related_name="likes", blank=True) def like(self, post): self.likes.add(post) def unlike(self, post): self.likes.remove(post) I have the following setup in Views: @login_required def like(request, pk): post = Post.objects.get(id=pk) Post.like(post, request.user) return HttpResponseRedirect(reverse('Home')) @login_required def unlike(request, pk): post = Post.objects.get(id=pk) Post.unlike(post, request.user) return HttpResponseRedirect(reverse('Home')) Here's how I'm calling the Views from my URLs: path('like/<int:pk>', views.like, name='Like'), path('unlike/<int:pk>', views.unlike, name='Unlike'), I'm using a form on my template to trigger the URL: {% if user in post.likes.all %} <form action="{% url 'Unlike' post.pk %}" method="POST"> {% csrf_token %} <button type="submit" value="{{ post.id }}" class="unlike">UNLIKE</button> </form> {% else %} <form action="{% url 'Like' post.pk %}" method="POST"> {% csrf_token %} <button … -
JS funtion returning empty value to input box
when the list-item-action class button is select or is active I want to appear a name in the skill_category input box and then send it to the models of my website this code is not giving a name of list-item it is returning an empty value in the skill_catgeory input in my form $(document).ready(function() { $('.list-group-item-action').click(function() { if ($('.list-group-item-action').hasclass('active')) { var cat_txt = ""; $('.list-group-item-action').each(function() { cat_txt += $(this).val() }); $('#cat_txt').val(txt); } }); }); <div class="row"> <div class="col-4"> <div class="list-group" id="list-tab" role="tablist"> <a class="list-group-item list-group-item-action active" id="list-lead_generator-list" data-toggle="list" href="#list-lead_generator" role="tab" aria-controls="lead_generator" value="Lead generator"><i class='fas fa-users'></i>Lead generator</a> <a class="list-group-item list-group-item-action" id="list-content_creator-list" data-toggle="list" href="#list-content_creator" role="tab" aria-controls="content_creator" value="Content Creator"><i class='fas fa-pen'></i>Content Creator</a> <a class="list-group-item list-group-item-action" id="list-social-social_media_handler-list" data-toggle="list" href="#list-social_media_handler" role="tab" aria-controls="social_media_handler" value="Social Media Handler"><i class='fas fa-icons'></i>Social Media Handler</a> </div> </div> <div class="col-8"> <div class="tab-content" id="nav-tabContent"> {% comment %} <input class="bg-white rounded border border-gray-400 focus:outline-none focus:border-indigo-500 text-base px-4 py-2 mb-4" placeholder="Skill" name="Skill" type="text"> {% endcomment %} <div class="tab-pane fade show active" id="list-lead_generator" role="tabpanel" aria-labelledby="list-lead_generator-list"> <label class="container">Lead Generator <input type="checkbox" name="lead_generator" value='Lead Generator' class="lead_generator"> <span class="checkmark"></span> </label> </div> </div> </div> </div> <form method="post"> {% csrf_token %} <input type='text' name="user" class="user" value="{{user.username}}" /> <input type="text" name="skill_category" id="cat_txt" class="skill_category"> <input type="text" name="skill" id="txt" class="skill"> <div class='container nxtbtn'> <button … -
property can not read of undefined when using datatable()
I am using DataTable() to generate dynamic table. The table header is dynamic. The headers will change on the basis of month. There is nav buttons for changing the months. On the changing of the the months the table is also changed. i have written an ajax funstion for fetching data and to show in the table. The function is called when the document is ready and on the onClick() event the buttons $("#month-next-btn").click(function(){ $("#selected-month").html(incrementDecrementMonth(1)); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; // setTimeout(function(){fetchMonthlyAttendanceStatus()},10); fetchMonthlyAttendanceStatus(); setNavBtnState(year, month); }) $("#month-prev-btn").click(function(){ $("#selected-month").html(incrementDecrementMonth(-1)); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; // setTimeout(function(){fetchMonthlyAttendanceStatus()},10); fetchMonthlyAttendanceStatus(); setNavBtnState(year, month); }) function fetchMonthlyAttendanceStatus(){ var dateSelected = $("#selected-month").html(); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; $.ajax({ type: 'GET', url: '{% url "attendance:ajax-monthly-attendance-status" %}', data: { 'month': month, 'year': year }, dataType: 'json', success: function (data) { $("#monthly-attendance-status-table-header").empty(); $("#monthly-attendance-status-table-rows tr").remove(); $("#monthly-attendance-status-table-header").append(`<th class="text-center" style="border-bottom: 2px solid #EAEAEA; font-weight:normal;">ID</th> <th class="text-center" style="border-bottom: 2px solid #EAEAEA; font-weight:normal;">Name</th>`); var monthS = month.slice(0, 3); var dayLst = data.day_lst; for (var i = 0; i < dayLst.length; i++) { if (dayLst[i] < 10) { dayLst[i] = '0' + dayLst[i]; } var date = dayLst[i] + '-' + monthS; $("#monthly-attendance-status-table-header").append(`<th class="text-center" … -
i want create constraint in django
I want to create a constraint of the form code = <min_weight> - <max_weight> <weight_unit> how do i do that i just learned it class Size(models.Model): code = models.CharField(max_length=200, primary_key=True) uni = [("GC", "Gram/Con"), ("KC", "Kg/Con")] min_weight = models.IntegerField(blank=False, null=False) max_weight = models.IntegerField(blank=False, null=False) weight_uni = models.CharField(max_length=10, choices=uni, default="KC") def __str__(self): return self.code -
Get the current URL of another specifi user in Django
I have a chat application and I'm using django-webpush to push notifications. Here is how I push notifications # Web push content = message.filename() if message.text: content = message.text payload = {"head": f"A new message from {room.title()}", "body": content, "icon": "/static/chat/img/favicon.png", "url": f"https://orgachat.pythonanywhere.com/chat/room/{room.id}/"} for chatter in room.chatters.all(): if chatter != request.user and True: #todo check for chatter url send_user_notification(user=chatter, payload=payload, ttl=1000) Now what I want to do is not to push the notification if the other user (chatter) is already in the payload url "/chat/room/roomId". Is there any way to do so? -
django+xterm.js: why I get "failed: Error during WebSocket handshake: Unexpected response code: 200" when I run the website on server?
Currently I built a webssh demo based on django and xterm.js. I have successfully run the website on localhost. But when I deployed the project on my server, everytime I try connection it retured "failed: Error during WebSocket handshake: Unexpected response code: 200". I have no idea what the problem is... the code I used is from github: https://github.com/huyuan1999/django-webssh -
How do I make custom filters work in django_filters?
So I've made this custom filter in filters.py with django-filters and when I'm submitting the "YEARCHOICE", the page refreshes but it doesn't work. I think I'm having a problem with my "year_filter_method" also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers! *Note it doesn't work with or without pagination. models.py from django.db import models import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): Song = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.Song filters.py import django_filters import datetime class MusicFilter(django_filters.FilterSet): YEARCHOICES = [] for r in range(2010, (datetime.datetime.now().year + 1)): YEARCHOICES.append((r, r)) year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method") def year_filter_method(self, queryset): expression = Music.Year return queryset.filter(expression) views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) filters.html {% load static %} <link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <div class="container"> <form method="get"> <span class="label">{{filter.form}}</span> <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span> </form> </div> music.html {% include 'main/includes/navbar.html' … -
html files in django
Someone told me that it is good practice to put django html files from a scpecific app into a templates folder in which there is still another folder inside with the name of the app? I tried doing it like this and I keep getting an error. How should I go about it? enter image description here -
Django StreamingHttpResponse() is causing server to stop working
I am trying to implement StreamingHttpResponse but came across a tedious issue. The connection appears to be established then after around 2 page requests the webserver stops responding. I am truly bewildered about what is causing this issue. If it was associated with an infinite loop, the time.sleep() method should have prevented the server from overloading. I'd appreciate any help, thanks! views.py: def event_stream(): initial_data = "" while True: data = json.dumps(list(Notification.objects.filter(to_user=1).order_by("-created_date").values("info", "return_url", "from_user","to_user","created_date")), cls=DjangoJSONEncoder) if not initial_data == data: yield "\ndata: {}\n\n".format(data) initial_data = data time.sleep(1) class PostStreamView(View): def get(self, request): response = StreamingHttpResponse(event_stream()) response['Content-Type'] = 'text/event-stream' return response base.html var eventSource = new EventSource("{% url 'stream' %}"); eventSource.onopen = function() { console.log('We have open connection!'); } eventSource.onmessage = function(e) { console.log(e) } eventSource.onerror = function(e) { console.log(`error ${e}`); } </script> Server Log: 2020-10-20 19:25:51 Tue Oct 20 19:25:51 2020 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /AP%20Psychology/ (ip 10.0.0.124) !!! 2020-10-20 19:25:51 Tue Oct 20 19:25:51 2020 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET /AP%20Psychology/ (10.0.0.124) 2020-10-20 19:27:33 Tue Oct 20 19:27:33 2020 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /post/12/ (ip 10.0.0.124) !!! … -
Django admin list view prevent choices lookup
class CustomerChoices(object): def expensive_lookup(self): .... def __iter__(self): yield from [(a.number, a.display) for a in self.expensive_lookup()] class CustomerProfile(models.Model): account_number = models.IntegerField(unique=True, choices=CustomerChoices()) ... from django.contrib import admin from .models import CustomerProfile @admin.register(CustomerProfile) class CustomerProfileAdmin(admin.ModelAdmin): list_display = ('account_number', ...) Given above code, while I am happy with the add/edit admin to use the choices, how do I prevent django admin list view using the choices, so it doesn't make an expensive lookup? Please note that I am aware of caching methods, but what if I just want to display the account number? -
How to close django channel redis connections manually?
I have a server that has a webhook and a websocket service. They send messages to each other using channel redis layer, similar to the chatroom example online that uses channel names, but without using groups. (1 to 1 using channel names) For my use, my websocket is always connected to the server, while webhooks are requests that is on demand from users. When a user sends a webhook request, the server would find the corresponding websocket channel name via a database. The webhook service would then send message to websocket, the websocket would find the webhook channel name (from said database) and send a message back. Then finally, the webhook service would generate a response. This webhook instance would then disappear. (it is based on AsyncHttpConsumer). The problem I found out is that when it's on Heroku, I have limited redis connections (20), and they timeout. Every user that uses my service would have their own redis connection, and after 20, I would get an error message (ERR max number of clients reached). Since the webhook request-response only takes around several seconds, I don't need the redis connection to stay alive for the default 300 seconds. But if I … -
Configurating the Width of Columns in Django Admin
I am trying to adjust width of one of the columns in Django Admin so I found several answers like this but it didn't solve my issue Is this the best way to do it? if not what is another better solution? here is the admin.py class PostAdmin(admin.ModelAdmin): list_display = ['id','design'] class Media: css = ('/css/fancy.css'.format(settings.STATICFILES_DIRS[0]+ '/css/fancy.css'),) here is the fancy.css .column-design { width: 20px; } -
Configured ec2 amazon aws and the webapp is not being showed
After configured zone at Route 53 pointing my ec2 instance to my domain, my web application is not being showed, only "Welcome to nginx" message. My web application is a Django web app, deployed using gunicorn and nginx. At Route 53, the only record I created was a www A record, pointing to the ec2 instance ip. $ dig imobiliarianossapraia.com.br ; <<>> DiG 9.11.3-1ubuntu1.13-Ubuntu <<>> imobiliarianossapraia.com.br ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 31542 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 65494 ;; QUESTION SECTION: ;imobiliarianossapraia.com.br. IN A ;; ANSWER SECTION: imobiliarianossapraia.com.br. 300 IN A 54.172.168.83 ;; Query time: 97 msec ;; SERVER: 127.0.0.53#53(127.0.0.53) ;; WHEN: Wed Oct 21 01:00:59 UTC 2020 ;; MSG SIZE rcvd: 73