Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do I disable the formating symbols like ! @ # $% ^ & * () on django forms?
for example, I want the slug form to be disabled with a symbol! @ # $% ^ & * (> <_ + {} ":?> and how do I do it in django? django 2.2 -
How to cache x-icon forever?
Consider this view that renders favicon: from django.http import HttpResponse from io import BytesIO from somewhere import Favicon # View URL: `/icon.<str:colour>.ico` def favicon( request, colour ): bs = BytesIO() Favicon \ .render( colour ) \ # Returns PIL image. .save( bs, 'ICO' ) response = HttpResponse( bs, status=200 ) response['Content-Type'] = 'image/x-icon' response['Cache-Control'] = 'public, max-age=31536000' return response Here is my HTML document: <!DOCTYPE html> <html> <head> <link rel=icon href=/favicon.7f9fa4.ico> </head> <body> <p>Hello, World?</p> </body> </html> Why each time I reload the page, my browser (Chromium 73.0.3683.86) makes request to /favicon.7f9fa4.ico, instead of retrieving cached image? How to make browser always retrieve icon from cache instead of making request to the server? -
I am trying to implement rowdata deletion using django view and checkbox
I am trying to implement rowdata deletion using django view. At this time I try to delete the checked row. I want to implement a delete view like this. Getting an id using JQuery Send to view To delete the row corresponding to id I do not know all 1,2,3. Can you tell me? I searched for this and there were several ways. ex) Use ajax, use the view function I'd like to know more about the above 1,2,3. It is a difficult request, but please let me know in more detail. Thank you html code {% for p in object_list%} <tr> <td> <input type = "checkbox" id={{p.id}}> </ td> <td> {{p.classification}} </ td> <td> <a href="" id={{p.id}}class="title_for_list"> {{p.title}} </a> </ td> <td> {{p.now_diff}} </ td> </ tr> {% endfor%} -
Django retrieve key of group ChoiceField
retrieve key of group ChoiceField MEDIA_CHOICES = ( ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ) class ressource(models.Model): .... media = models.CharField(max_length=50, choices=MEDIA_CHOICES) in field media i have vinyl or cd or vhs or dvd...but how retrieve audio,video, unknown ? -
How does redirect and reverse work with kwargs in Django 2?
PaymentView function works correctly and redirects correctly to updateTransactions function if I do not include the locations variable. Can you explain why adding locations variable as a kwarg breaks my function, and how to fix. views.py def PaymentView(request): if request.method == "POST": try: user_id = get_user_id(request) locations = 4 except: messages.info(request, "Something went wrong pt 1") try: return redirect(reverse('memberships:update-transactions', kwargs={ 'sub_id': user_id, 'locations': locations, })) except: messages.info(request, "Something went wrong pt 2") return render(request, "stuff/stuff.html") def updateTransactions(request, sub_id, locations): user_membership = get_user_membership(request) user_membership.locations = locations user_membership.sub_id = sub_id user_membership.save() return redirect(reverse('courses:list')) urls.py from django.urls import path from .views import PaymentView, updateTransactions app_name = 'memberships' urlpatterns = [ path('payment/', PaymentView, name="payment"), path('update-transactions/<subscription_id>', updateTransactions, name="update-transactions"), ] -
Django Rest Framework: Use DELETE on GenericAPIView without implementing Retrieve
I'm using Django Rest Framework and want to be able to delete a Content instance via DELETE to /api/content/<int:pk>/. I don't want to implement any method to respond to GET requests. When I include a .retrieve() method as follows, the DELETE request works: class ContentViewSet(GenericViewSet): def get_queryset(self): return Content.objects.filter(user=self.request.user) def retrieve(self, request, pk=None): pass #this works, but I don't want .retrieve() at all def delete(self, request, pk=None): content = self.get_object() #look up some info info here content.delete() return Response('return some info') If I replace .retrieve() with RetrieveModelMixin it also works. However, if I remove both of these, which is what want to do, I get the following error. django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name. I haven't tested, but I assume the same thing would happen with PUT and PATCH. My questions are: How can I allow DELETE without implementing a .retrieve() method, and Why can't DRF create the urlconf without .retrieve() implemented? -
Apache default page is opening when i try to open my ip address
Recently i have hosted a webapp in linode using apache2. It was working fine but some thing happened suddenly, it starts opening apache default page when i try to open my webpage. If any one has faced it, can you please help me in getting out of this. Thank you all. ! https://i.stack.imgur.com/1NOHl.jpg -
Limiting the lenght of response with python requests
I'm setting up a Views that save data from an API into my database on a button click and I'm having a hard time trying to figure out how to limit the size of the requests response for product descriptions in the following way: If the lenght of a description is higher than 2000, delete some of the letters at the end of it until it reaches the limit of 2000, but don't remove it completely from the request. As of now, what I've been able to achieve is to completely remove the product infos if the lenght is higher than 2000 as you can see below. My django views function: def api_data(request): if request.GET.get('mybtn'): # to improve, == 'something': resp_1 = requests.get( "https://www.test-headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD", headers={ "Headout-Auth": HEADOUT_TEST_API_KEY }) resp_1_data = resp_1.json() base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/" for item in resp_1_data['items']: # concat ID to the URL string url = '{}{}'.format(base_url_2, item['id'] + '?language=fr') # make the HTTP request resp_2 = requests.get( url, headers={ "Headout-Auth": HEADOUT_TEST_API_KEY }) resp_2_data = resp_2.json() if len(resp_2_data['contentListHtml'][0]['html']) < 2000: #represent the description of a product Product.objects.get_or_create( title=item['name'], destination=item['city']['name'], description=resp_2_data['contentListHtml'][0]['html'], link=item['canonicalUrl'], image=item['image']['url'] ) return render(request, "form.html") But I remove way to much rows by doing this so I would … -
How to make response be cache-immutable?
How to make favicon response be immutable, so browser will not make a request each time I reload a page? from django.http import HttpResponse from io import BytesIO from somewhere import Favicon def favicon( request ): bs = BytesIO() Favicon.render( request.GET.get('colour') or 'FF0000' ).save( bs, 'ICO' ) response = HttpResponse( bs ) response['Cache-Control'] = 'immutable' # Doesn't work. return response Favicon.render returns PIL image. -
Line breaks in Django rest response
I see the in JSON response "\n" doesn't work for string values as below. Is there any specific way for this in Django-rest Framework, ''' { "count" : "10", "results" : [ { "id" : "10", "output" : "line1 \n line2 \n line3" }, ] } ''' -
how to update my django website with PSQL DBMS that uploaded in heroku
I uploaded my website that created with django 2.0 and PostgreSQL DBMS to heroku, then i added other apps and other fields to my existing models and i want to update my website that exist in heroku, So please how can i update my website without losing the data that stored by the users of my website -
How to implement Django users referred by other users relationship?
I want to implement a way to keep track of referrals in my django application. I am using the default Users table. A user can 'refer' multiple people, but a referred user can only be referred by one user. I have tried adding this to my models.py but it is causing errors. class Referral(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) referredBy = models.ForeignKey(User, on_delete=models.CASCADE) this causes the below error: ERRORS: RateManager.Referral.referredBy: (fields.E305) Reverse query name for 'Referral.referredBy' clashes with reverse query name for 'Referral.user'. HINT: Add or change a related_name argument to the definition for 'Referral.referredBy' or 'Referral.user'. How do I go about implementing this? -
Having trouble to complete Unittest class based views in DJANGO
How can I complete this views unittest with django? I am getting started with unittest and for some reason i am not able to complete the first class based views test successfully. models.py class BookListView(ListView): model = Book context_object_name = 'books' template_name = 'snippets/list.html' urls.py from django.contrib import admin from django.urls import path, include from .views import (BookListView) from . import views app_name = 'snippets' urlpatterns = [ path('', views.index, name='book_list'), views.py from django.test import TestCase, Client from django.urls import reverse from snippets.models import Book import json class TestViews(TestCase): def setUp(self): self.client = Client() def test_book_list_GET(self): response = self.client.get('snippets:book_list') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'snippets/list.html') Below is the feedback crashing from the terminal self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.061s FAILED (failures=1) Destroying test database for alias 'default'... -
Better way to change background color based on element's property
I'm working on a project using Django, some JavaScript and Tachyons. I have the following in a template file: <tbody class="lh-copy"> {% for alarm in alarm_list %} <tr> <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.agent.name }}</td> <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.profile_name }}</td> <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.is_active }}</td> <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.created }}</td> <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.message }}</td> <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.alrmtype }}</td> <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.acknowledged }}</td> <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.is_hidden }}</td> {% if alarm.is_active %} <script language="javascript"> const alarmValElementList{{ alarm.id }} = document.getElementsByClassName("{{ alarm.id }}-td"); for (let i=0; i < alarmValElementList{{ alarm.id }}.length; i ++) { alarmValElementList{{ alarm.id }}[i].classList.remove("bg-light-green"); alarmValElementList{{ alarm.id }}[i].classList.add("bg-light-red"); }; </script> {% endif %} </tr> {% endfor %} </tbody> I'm accessing the element alarm from alarm_list and using a template "if" to insert JavaScript code that tells the HTML element to remove the current background color and add another one. I'm not happy to use alarmValeElementList{{ alarm.id }} as a dynamic variable … -
Django now working channels with ASGI + WSGI in Heroku
I am trying to setup a Django + Heroku app with Channels (V.2). I tried to follow all the tutorial but most of them are not updated. App must use WSGI for HTTP request and ASGI for websockets requests. So far I found that it is almost working, the last missing piece is for the websockets endpoints to be visible for web app. At this point whenever I try to create a new websocket: Error during WebSocket handshake: Unexpected response code: 404 Here is the Settings: ASGI_APPLICATION = 'app_xxx.routing.application' ASGI_THREADS = 5 WSGI_APPLICATION = 'app_xxx.wsgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { 'hosts': [os.environ.get('REDIS_URL')], }, }, } Here is the Procfile: web: gunicorn app_xxx.wsgi --log-file - web2: daphne app_xxx.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channel_layer -v2 Here is the asgi: import os from channels.layers import get_channel_layer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_xxx.settings") channel_layer = get_channel_layer() Here is the routing: from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter from django.urls import path from apps.booking.consumers import BookingConsumer application = ProtocolTypeRouter({ "websocket": URLRouter([ path('ws/booking_review/<room_name>', BookingConsumer), ]), }) -
template tag slice won't work while truncatechars works
season1-theOffice. I want to remove -theOffice. Thus I did season1|truncatechars: "9" but with this it gives season 1... I don't want to see ... So I used season1|slice:" :9" but this does nothing. Here's my code. <a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season|slice:":5" }} -
{{ form.id }} not saving formset
I am trying to manually render formset fields in a template, but the fields are not being saved when I submit. My method works for a different formset based on another model, and as far as I can tell I haven't done anything differently. I tried a number of changes, but the issue seems to be {{ form.id }} in the template; when I change it to {{ form }}, I am able to save the fields. As mentioned, this same set up works for another model/formset; when I make changes to a field and save, the page is refreshed and the model shows as updated. The code below is for the model/formset that is not working. models.py class Call(models.Model): name = models.CharField(max_length=200, null=True, blank=True) customer_number = models.CharField(max_length=200, null=True, blank=True) tracking_source = models.CharField(max_length=200, null=True, blank=True) tracking_number = models.CharField(max_length=200, null=True, recorded_date = models.DateTimeField(default=timezone.now) def publish(self): self.recorded_date = timezone.now() self.save() def t_number(self): return self.tracking_number[-4:] def __str__(self): return str(self.name) forms.py class CallForm(forms.ModelForm): class Meta: model = Call fields = ('name', 'customer_number', 'tracking_source', 'recorded_date') CallFormSet = modelformset_factory(Call, fields=('name', 'customer_number', 'tracking_source', 'recorded_date')) view.py def call_list(request): if request.method == 'GET': formset = CallFormSet(queryset=Call.objects.all()) elif request.method == "POST": formset = CallFormSet(request.POST) if formset.is_valid(): for form in formset: … -
how to solve problem with loading large amount of data in django?
I'm trying to write an app like imdb for my work project. in this app i need to store 8700 of imdb movies and also about 40k directors and actors/actresses in mysql database, when i was trying to post a new movie, the movie creation page took a long time (about 20s) to render. first, i did make a model named "persons" with person name, gender, "is_director" and "is_actor" boolean fields. then, i did create a model named "movies" with 2 ManyToManyFields for is_director and is_actor persons. after that, i did import about 40k persons to my database with django fixture. my problem started from here. when i was trying to post a new movie from django admin, the movie creation page took a long time (about 10s) to render. I know this is for a large amount of persons data. i did use django built-in autocomplete but the problem was still there. I'm new to Python/Django. so I think I'm doing this in a wrong way. maybe my database structure is wrong or my model has a problem, i don't know how to solve it! # Person Model: class Person(models.Model): name = models.CharField(_('Person Name'), max_length=100) is_actor = models.BooleanField(_('is actor'), … -
Wagtail "schedule_published_pages" Management Command
I was wondering why my scheduled posts were not working automatically in Wagtail, but I see in the documentation that a management command is needed to make this happen. I am unfamiliar with management commands, and I am wondering how to make the python manage.py publish_scheduled_pages command fire off automatically every hour? Where would this code go in the document tree? Is there code that I just need to drop in and it runs from there? Or is something required on the server to run these commands on a schedule? Any help would be appreciated. I couldn't find any existing code anywhere for this functionality in Wagtail and I'm wondering why the button is in the admin to schedule a post, but the functionality is not already built in? -
how to fix django admin "You don't have permission to view or edit anything."?
for the sake of customizing the default admin site , i have made the following changes: admin.py: class CustomAdminSite(admin.AdminSite): def get_urls(self): urls = super(CustomAdminSite, self).get_urls() custom_urls = [ # re_path(r'^.*\.html', views.custom_admin_template_loader, name='custom-loader'), url(r'^.*\.html', self.admin_view(self.my_view), name="my-view"), ] return urls + custom_urls def my_view(self, request): context = {} load_template = request.path.split('/')[-1] template = loader.get_template('admin/' + load_template) request.current_app = self.name return HttpResponse(template.render(context, request)) apps.py: from django.contrib.admin.apps import AdminConfig class MyAdminConfig(AdminConfig): default_site = 'myproject.admin.CustomAdminSite' settings.py: INSTALLED_APPS = [ 'myproject.apps.MyAdminConfig', nothing changed in urls.py so if i access admin/ it works , but if i access another template using the view i made , it says You don't have permission to edit anything , how to fix it? for clarifications on WHY i m using that view, it is because i overrided the default admin templates and now i have a navigation bar , which means i need to navigate through different html files (templates) -
pytest django requires db access for a test that doesn't access the db
I've started to move some tests across to using pytest in a django project. However when testing on a simple test, pytest produces an error saying that that test needs access to a db. However the equivalent test in django testrunner used SimpleTestCase which doesn't use the django db. The original test class TestHomeView(SimpleTestCase): def test_uses_home_template(self): response = self.client.get(reverse('home')) self.assertTemplateUsed(response, 'pages/home.html') The test in pytest @pytest.mark.django_db def test_home_template(client): response = client.get(reverse('home')) assert 'home.html' in [t.name for t in response.templates] Removing the django_db mark makes the test fail. The only possible use of the db that I can think of is that we are using the session middleware (although we aren't actively using the session in that view). Why does pytest think it needs to access the db for this test? -
how to notify superuser to change the category of another user after he submits a form?
I have a django project with multiple types of users. At the base is a business user and he can upgrade to a 'professional' user or a 'novice' user. I want him to fill a form with his details and then any of the superuser or selected user shall get a notification to be able to view his form in a listview of all others who applied and allow them or reject them "professional" user status from the templates itself. i have tried of using Boolean values to assign with each user to their status and then other user can change that Boolean value but it did not work. Any references to such permissions or giving powers to users to give other users powers shall be highly appreciated. -
how to use iframe in admin
I want to use iframe in admin. I want to upload a video using iframe and the url. one way would be ckeditor and the source code functionality but I don't want to install ckeditor just for this purpose. is there a django model field I can use that I can simply put "" and the video shows up -
Update database from view
View.py @login_required def UnosPosudbe(request): if request.method == 'GET': forma = PosudbaForma() elif request.method == 'POST': forma = PosudbaForma(request.POST,request.FILES) if forma.is_valid(): #Dohvacanje Kolicine kolicinaKnjige = str(forma.cleaned_data['nazivKnjige']) IDKnjige = kolicinaKnjige kolicinaKnjige = kolicinaKnjige[-1:] IDKnjige = IDKnjige[:1] unesenaKolicina = forma.cleaned_data['kolicina'] if(int(kolicinaKnjige)>=unesenaKolicina and unesenaKolicina > 0): #update kolicine knjiga = Knjiga.objects.get(pk=IDKnjige) knjiga.kolicina = int(knjiga.kolicina) - int(unesenaKolicina) print(knjiga) knjiga_forma = KnjigaForma(request.POST, instance = knjiga) knjiga_forma.save() # forma.save() return redirect('pregledPosudbe') return render(request, 'unosPosudbe.html', {'forma':forma}) I am trying to update database with part of code but I am keep getting error: knjiga = Knjiga.objects.get(pk=IDKnjige) knjiga.kolicina = int(knjiga.kolicina) - int(unesenaKolicina) print(knjiga) knjiga_forma = KnjigaForma(request.POST, instance = knjiga) knjiga_forma.save() Error: ValueError at /UnosPosudbe/ The Knjiga could not be changed because the data didn't validate. I am not sure what I am doing wrong? Models.py class Knjiga(models.Model): naziv = models.CharField(null=False, blank=True, max_length=120) autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True) datumObjave = models.DateField(null=True, blank=False) izdanje = models.CharField(null=True, blank=True, max_length=120) slika= models.FileField(upload_to='images/', null=True, verbose_name="") #videofile kolicina = models.IntegerField(null=False, blank=False) def __str__(self): return str(self.id) + ', ' +str(self.naziv) + ', ' + str(self.autor) + ', Kolicina:' + str(self.kolicina) -
How to sort queryset based on two fields in django?
This is my serilizer class: class RankNewsChannelSerializers(serializers.ModelSerializer): class Meta: model = News_Channel fields = ('id', 'name','total_star', 'total_user') This is my views class NewsChannelRankApi(ListAPIView): queryset = News_Channel.objects.order_by('-total_star').all() serializer_class = RankNewsChannelSerializers I am getting reponse sorted based on total star as given below: [ { "id": 9, "name": "The Hindu", "total_star": 36, "total_user": 5 }, { "id": 1, "name": "NDTV", "total_star": 36, "total_user": 5 }, { "id": 10, "name": "Firstpost", "total_star": 35, "total_user": 6 }, { "id": 14, "name": "DD News", "total_star": 25, "total_user": 4 } ] But in my response I need response sorted based on total_star/total_user. Like this is my invalid method but it will give you a rough idea about what I want to achieve class NewsChannelRankApi(ListAPIView): queryset = News_Channel.objects.order_by('-total_star/total_user').all() serializer_class = RankNewsChannelSerializers Please help me if there is anyway to do so?