Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Exception of 'method' object is not iterable when trying to disable authentication for a particular view
I need to disable authentication for a view I have. So I followed the instructions in this SO post: How Can I Disable Authentication in Django REST Framework So my code looks like this: class CompListView(APIView): """ This view class will return a list of specified Components. """ from rest_framework.decorators import authentication_classes, permission_classes from rest_framework.permissions import AllowAny @authentication_classes([]) @permission_classes([AllowAny,]) def get(self,request): Then I start my django server and point my browser to it but I get a long error trace ending in: File "/apps/comp/env/lib/python3.6/site-packages/rest_framework/views.py" in get_permissions 280. return [permission() for permission in self.permission_classes] Exception Type: TypeError at / Exception Value: 'method' object is not iterable I have also tried this ... @permission_classes((AllowAny,)) ... and get the same error. I suspect the solution I am using doesn't work for django 2 or python 3. What am I doing wrong here? -
What is the differences between between a blog created through coding and a wordpress?
What is the differences between between a blog created through python and a wordpress? -
How to pass to a session the result of a search. The result could be an object or many objects
how to pass multiple objects to a session? fil = Enseignant.objects.filter(matricule_enseignant=identifiant).values_list('niveau__filiere__nom_fiiere', flat=True) request.session = #? -
Django order by value returned from function?
I want get the list of my objects ordered from a function insidade my class model. it is possible to do that?? class Client(models.Model): num1 = models.IntegerField(default =0) num2 = models.IntegerField(default=0) def percent(self): return(self.num1 / self.num2) and then how i get the list ordered by that function?? -
Alloting a read replica to a particular app in Django?
The django project has multiple apps and they all right now access the same DB. If I want one app which has only read queries to read from read replica will I have to add routers for both DB or creating one router for read replica and alloting it to the app will work? Is there a better way to do this? -
I did not pass in models form tuples value
Dear how to add tuple data(EMPTY_CHOICES) in models field [pro_drive_name]?. i am passing this value but not showing in my admin page from django.db import models from django.contrib.auth.models import User import os,string drives_a = [chr(x) + ':' for x in range(65, 90) if os.path.exists(chr(x) + ':')] list_with_tuples = [(x, x) for x in drives_a] EMPTY_CHOICES = [('', 'All')] + list_with_tuples class pro_drive(models.Model): pro_drive_name = models.CharField(max_length=2,choices=EMPTY_CHOICES) def __str__(self): return self.pro_drive_name class pro_fol(models.Model): pro_drive = models.ForeignKey(pro_drive, on_delete=models.CASCADE) def __str__(self): return self.pro_drive_name class Person(models.Model): pro_drive = models.ForeignKey(pro_drive, on_delete=models.SET_NULL, null=True,choices=EMPTY_CHOICES) pro_fol = models.ForeignKey(pro_fol, on_delete=models.SET_NULL, null=True) def __str__(self): return self.pro_drive -
Django: View is not putting the value returned by a function
I have the bookingrecordsView view in which I fetch all reservations made by a user. I added another function checkIfPending() that fetches the reservations, checks whether the date_to field has passed or not, and returns a string. The view that fetches the reservations: def bookingrecordsView(request): rsv = Reservation.objects.filter(user=request.user) condition = checkIfPending(rsv) return render(request, 'booking_history_page.html', {'rsv': rsv, 'status': condition}) And the function that checks the date: def checkIfPending(rsv): for r in rsv: if r.date_to < datetime.date.today(): status = "Pending" else: status = "Over" return status This is my template snippet: {% for r in rsv %} <tr> <td>{{ r.id }}</td> <td>{{ r.date_from }} - {{ r.date_to }}</td> <td>{{ r.time_from }} - {{ r.time_to }}</td> <td>{{ r.chosen_vehicle }}</td> <td>{{ r.garage }}</td> <td>{{ r.destination }}</td> <td>{{ status }}</td> <-- Placed 'status' here </tr> {% endfor %} Now, for all the bookings, even those passed months earlier, this status is returning 'Pending'. One error I found is, even if I pass the fetched table values to the checkIfPending() function and expect to get the return value for every r in rsv, the returning isn't working that way. How do I get the return value of every r from checkIfPending() function and pass value accordingly … -
Is it possible to use django-tables 2 with infinte scroll?
I just started to write an application using Django 2 and the most recent version of django-tables2. So far everything works without any problems but now I have a question. I would like to display some data by using a sticky header and infinite scroll (so instead of having Page 1,2,3...,N at the bottom of the table I want to scroll down). I checked several pages(including the official documentation of django-tables2 https://django-tables2.readthedocs.io/en/latest/index.html). But I didn't find any solution which do the trick. I was thinking of using django-endless-pagination(https://django-endless-pagination.readthedocs.io/en/latest/start.html#quickstart) in combination with django-tables2 but I am not even sure if this would work. So my question would be is it possible to use infinite scroll with django-tables2 ? -
Problems with the django project migrating from macos to Windows
OSError: [WinError 123] 文件名、目录名或卷标语法不正确。: '' I migrate my django project from macos to windows.When I try to run python manage.py runserver. The following error occurred. -
Uploading excel(xlsx) file in a web application that analyses its data and exports other data in a different xlsx file
So i am trying to make a web application that does what the title says. The problem is i dont know exactly how to move on. I am thinking using pandas to get the data and maybe use django to make the web application. Any help would be appreciated. -
XMLHttpRequest with Django -> GET, ERROR 500
My method in views.py try get product_slug because he need product = Product.objects.get(slug=product_slug) and add this product in the cart. U try use XMLHttpRequest with JS but have error 500.What I'am doing wrong? urls.py url(r'^cart/create/$', views.cart_create, name='cart_create'), views.py def cart_create(request): cart = Cart(request) product_slug = request.GET.get('product_slug') product = Product.objects.get(slug=product_slug) cart.add(product=product) return JsonResponse({'200':'OK'}) product_list.html <a href="javascript:void(0);" class="add_to_cart" data-slug="{{ product.slug }}">Add</a> base.html var add_to_cart = document.getElementsByClassName('add_to_cart'); for(var i = 0; i < add_to_cart.length; i++) { product_slug = add_to_cart[i].getAttribute('data-slug') add_to_cart[i].onclick = function() { loadA(product_slug) } } function loadA(product_slug) { var xhr = new XMLHttpRequest(); url = "{% url 'cart:cart_create' %}" + product_slug xhr.open('GET', url); xhr.send(); if (xhr.status != 200) { console.log('no') } else { console.log('ye') } } In console.log output no and error (Internal Server Error). Help me, please. I try rewrite this code with clean javascript/XMLHttp > without jQuery/Ajax $(".add_to_cart").click(function() { product_slug = $(this).attr("data-slug") data = { product_slug: product_slug, }, $.ajax({ type: "GET", url: "{% url 'cart:cart_create' %}", data: data, success: function(data) { $(".cart_score").empty().append(data.cart_length + " товаров " + data.cart_total + " &#8381;") }, }); }); -
Saving data once (to be able to load to images to server) then updating the same instance after some changes
I'm saving the data from the post request a first time because I need the images to be uploaded to the server like the "upload_image" function suggests. At the same time I have a couple of fields that are null and need to have some values via some external functions. And then I need to save the whole object in the database. Any ideas, please? Thanks a lot! #VIEW class IdentityCheckView(CreateAPIView, generics.ListAPIView): serializer_class = IdentityCheckSerializer permission_classes = [permissions.AllowAny] def get_queryset(self): request = self.request qs = IdentityCheck.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter(name__icontains=query) return qs def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) if(serializer.is_valid()): res = self.create(request, *args, **kwargs) image = FaceRecognition.imageMatch(res.data['passengerPhoto'], res.data['passengerPassport']) wanted = WantedPro.criminalMatch(res.data['passengerPhoto']) passport_json = OCR.passportMatch(res.data['passengerPassport']) image_json = json.loads(image) firstName = passport_json['names'] lastName = passport_json['surname'] nationality = passport_json['country'] birthDate = passport_json['date_of_birth'] gender = passport_json['sex'] ableToBoard = bool(wanted) & bool(image_json['match']) & bool(passport_json['valid_expiration_date']) serializer.update( id=res.data['id'], firstName=firstName, lastName=lastName, nationality=nationality, birthDate=birthDate, gender=gender, ableToBoard=ableToBoard) return Response({"image": image_json, "passport": passport_json, "wanted": wanted}, status=200) def perform_create(self, serializer): res = serializer.save(agent=self.request.user) #SERIALIZER class IdentityCheckSerializer(serializers.ModelSerializer): class Meta: model = IdentityCheck fields = '__all__' read_only_fields = ['agent', 'id'] #MODEL def upload_image(instance, filename): return "media/check/{agent}/{date}/{filename}".format(agent=instance.agent,date=datetime.datetime.today().strftime('%d-%m-%Y'), filename=filename) class IdentityCheckQuerySet(models.QuerySet): pass class IdentityCheckManager(models.Manager): def get_queryset(self): … -
Django delete objects based on query with ManyToMany relation
I have 3 models Fileset, File & ContentBuild. File & Fileset have a many to many relation Contentbuild & Fileset have a one to many relation Models # models.py class File(models.Model): file_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) class ContentBuild(models.Model): content_build_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) content_build_name = models.CharField(max_length=50) rolled_out = models.BooleanField(default=False, editable=False) class Fileset(models.Model): fileset_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) files = models.ManyToManyField(File, related_name='fileset_files' content_build = models.ForeignKey(ContentBuild, on_delete=models.CASCADE, related_name='content_filesets') Goal When a Fileset is deleted, I want to only delete the related Files that are not used in a ContentBuild that is rolled out. I can filter Files that are eligible to be deleted like this: File.objects.filter( fileset_files__isnull=False, fileset_files__content_build__rolled_out=False ) Problem I have no idea how and where to implement the function that deletes the Files returned by the filter above. My idea was to create a function and pass it to on_delete but a ManyToManyField does not have on_delete. Where do I implement a delete function to delete some of the Files related to the Fileset that is being deleted? -
Setting debug = False makes the Django app crash with the following error, how to fix it?
It gives: internal server error when I try to acces the site/admin or any other app THis is a part of the log from the heroku: File "/app/.heroku/python/lib/python3.6/site-packages/django/template/defaultfilters.py", line 234, in stringformat 2019-05-08T14:11:38.555078+00:00 app[web.1]: return ("%" + str(arg)) % value File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 80, in repr return repr(self.__cast()) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 125, in __cast return self.__text_cast() File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 113, in __text_cast return func(*self.__args, **self.__kw) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/base.py", line 86, in reverse: raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'promotions' is not a registered namespace 10.145.115.115 - - [08/May/2019:14:11:38 +0000] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 0 "-" "-" 2019-05-08T14:11:38.556292+00:00 heroku[router]: at=info method=GET path="/admin/login/?next=/admin/" host=aapnik123.herokuapp.com request_id=173c557c-4bf5-48bb-a58f-18eb43ef72f1 fwd="103.232.241.185" dyno=web.1 connect=0ms service=3343ms status=500 bytes=244 protocol=https I have tried setting allowed hosts = "*" . this is my url.py in the main app I have tried using namepsace for resolving the NoReverseMatch error butit does not work. from django.contrib import admin from django.urls import path,include from oscarapi.app import application # from getdetail import * # app_name = "eshop" urlpatterns = [ # path('i18n',django.conf.urls.i18n), path('admin/', admin.site.urls), # ath('dashboard/', admin.site.urls), # path('GET_DET/', include('GET_DETAIL.urls',namespace='GET_DET')), # path('PUT_DET/', include('PUT_DET.urls',namespace='PUT_DET')), path('GET_DET/', include('GET_DETAIL.urls')), path('PUT_DET/', include('PUT_DET.urls')), # path('oscarapi/', application.urls), path('', application.urls), ] -
How can get all objects from ManyToMany field to django model's property field
Im new on Django. In my django model field I wanna a scheduled task. For example; I wanna send emails as scheduled task. And need crontab expression for api. I wanna send emails 0 10 * * 1,2 “At 10:00 on every Monday and Sunday.” on crontab expression first 10 digits are constant(0 10 * * ) and I wanna add values from own model's ManyToManyField. And I will add this values to my crontab expressions constants. (1,2,) And I will get final expression like (0 10 * * 1,2) How can I make this? (May days in Days model recorded as numbers: Sunday = 1 Monday = 2 ..... ) My Model; class SchulededExp(models.Model): days=models.ManyToManyField(Days) def _cronexperiossion(self): constantExp="0 10 * * " #do something return experission cronexp=property(_cronexperiossion) -
How to fetch API data as this. props?
I am trying to fetch data from API in react component as {this.props.buyer && this.props.buyer[0].phone_number[0].number} - it's throwing error "Cannot read property 'number' of undefined" {this.props.buyer && this.props.buyer[0].name} -it's working fine This is the API data Orders: { buyer: }, } [ { "id": 2, "name": "Qi Xiang", "type": "Consignee", "address": { "id": 2, "type": "shipping", "street": "China China", "city": "Beijing", "postal_code": "34343", "province": "23232", "country": "CN" }, "email": null, "phone_number": { "number": "323232", "type": "Phone" }, "id_image_url": "/api/files/24e49645-df42-4984-a } ] }, } -
How to create relation between 2 databases in Django 2.2 ORM (one unmanaged, and one managed)
I have two models: ciad_db - MySQL (db1), unmanaged class NormalizedData(models.Model): ticket_number = models.CharField(max_length=100, blank=True, primary_key=True, default='noticketid') status = models.CharField(max_length=45, blank=True, null=True) ticket_source = models.CharField(max_length=45, blank=True, null=True) summary = models.TextField(blank=True, null=True) conclusion = models.ForeignKey(DsrConclusions, on_delete=models.CASCADE, default=None) class Meta: managed = False db_table = 'normalized_data' indexes = [ models.Index( fields=[ 'status', 'ticket_source', 'summary', ] ) ] default - sqlite3 (db2), managed class DsrConclusions(models.Model): id = models.IntegerField(primary_key=True) ticket_number = models.CharField(max_length=100, blank=False, null=False, unique=True) explanation = models.TextField(blank=False, null=False) final_breach_conclusion = models.BooleanField(blank=False,null=False) last_owner = models.CharField(blank=False,null=False, max_length=50) class Meta: managed = True indexes = [ models.Index( fields=[ 'ticket_number', 'explanation', 'final_breach_conclusion', 'last_owner', ] ) ] in models.py, default comes in before ciad_db I use a database router because of the 2 databases, which looks like this: class CiadRouter(object): """ A router to control all database operations on models in the ciadseeweb application """ def db_for_read(self, model, **hints): """ Point all operations on ciadseeweb models to 'ciad_db' """ if model._meta.app_label == 'ciadseeweb': return 'ciad_db' return None def db_for_write(self, model, **hints): """ Point all operations on myapp models to 'other' """ if model._meta.app_label == 'ciadseeweb': return 'default' return None def allow_syncdb(self, db, model): """ Make sure the 'ciadseeweb' app only appears on the 'other' db """ if db … -
handle pagination recursively
I'm using requests lib to fetch data from remote server and I'm saving the data in the model, but I need to handle pagination, currently I'm only loading one page from server. I have a url for pagination like so "next": "https://pimber.ly/api/v2/products?sinceId=5c3ca8470985af0016229b5b", I've tried to use python generator to handle current situation but, that does not do anything _plimber_data = response.json() yield _plimber_data _next = _plimber_data['next'] print(_next) for page in _next: _next_page = session.get(_plimber_data, params={'next': page}).json() yield _next_page['next'] for _data in page: Product.objects.create( qr_id=_data['primaryId'], ean_code=_data['EAN'], description=_data['Description105'], category=_data['Category'], marketing_text=_data['Marketing Text'], bullet=_data['Bullet 1'], brand_image=_data['Brand Image'], image=_data['Images'] ) logger.debug(f'Something went wrong {_data}') print(f'This is the Data:{_data}') Can someone please explain me how to handle this so I can load all the data into the database, thanks. -
How to send a message using channels to a websocket client when a event occurs on the server side?
I'm building an RTS application using django, celery and (trying to) channels. Celery is constantly listening to a serial port and when it receive something important, it should be able to automatically push a message to the client, from there react will take over. The problem is: I'm new to all of this. I did try to push some random info to the client and print it to the console, but didn't work. What I did was set a periodic task in celery that would use the consumer class to send some data. For me it's clear why it didn't work: I have no idea of how to do it. All the guides that I've found show how to make a Chat application... I don't know, but that's quite a limited view on this. Also may be useful: didn't include channel layers yet. Please notice it is still very prototype-ish. The task is as follows. I know it's wrong. Ignore the imports, they have meaning just not yet. # Create your tasks here from __future__ import absolute_import, unicode_literals from .serialconnection import SerialConnection from celery import shared_task from .consumers import AlertConsumer from .models import Alert, Module @shared_task def test_websocket(): AlertConsumer.send_json(content={"text": 'teste'}) … -
Passing data with ajax to django with post method
I'm try to send data to a django view through ajax with POST method as I saw in one tutorial. The code I've made is the following (myURL is the URL where I call testview): $(document).on('submit','#form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/myURL/', data:{ HELLO: "I'm inside ajax data" }, contentType: "application/json", datatype: 'json', sucess:function(){ alert("Ajax pass data correctly"); } }) }); </script> And in django I'd call HELLO as following. test.html is where I have the html form if request.method == 'POST': takeHELLOfromajaxpost = request.POST['HELLO'] return render(request,'test.html',{'dataTakenfromAjax':takeHELLOfromajaxpost}) return render(request,'prueba.html',{}) Then I would template tagging in the same HTML {{ dataTakenfromAjax }} to verify if I'm taking that data , but nothing happens! I even get no error. -
Django Pagination not working in function based views
I am using the following function based view to create a pagination. There are no bugs in this views, but the way I am using the context in template creates problem specially when I am adding {% else page_num > topics.number|add:'-3' and page_num < topics.number|add:'3' %} in templates. This is view function: def board_topics(request, pk): board = get_object_or_404(Board, pk=pk) queryset = board.topics.annotate(replies_count=Count('posts') - 1).order_by( '-last_updated') page = request.GET.get('page', 1) paginator = Paginator(queryset, 10) try: topics = paginator.page(page) except PageNotAnInteger: topics = paginator.page(1) except EmptyPage: topics = paginator.page(paginator.num_pages) return render(request, 'board/board_topics.html', {'board': board, 'topics': topics}) and the template here: {% for page_num in topics.paginator.page_range %} {% if topics.number == page_num %} {{ page_num }} {% else page_num > topics.number|add:'-3' and page_num < topics.number|add:'3' %} <a class="page-link" href="?page={{ page_num }}">{{ page_num }}</a> {% endif %} {% endfor %} If in template I replace {% else page_num > topics.number|add:'-3' and page_num < topics.number|add:'3' %} with {% else %} it works totally fine, but I need the first one to work since I don't to show tons of pagination number in my page if there are thousands of topics. Can you help me out with this problem. Thank you -
send data from template to views through javascript in django
I want to pass a list from template to views in Django. here is the code for creating a ul's list in HTML function addLi() { var txtVal = document.getElementById('txtVal').value, listNode = document.getElementById('list'), liNode = document.createElement("LI"), txtNode = document.createTextNode(txtVal); liNode.appendChild(txtNode); listNode.appendChild(liNode); } function ComAction() { var items = document.querySelectorAll('#list li'); var container = []; for(var i=0;i<items.length;i++) { container.push(items[i].innerHTML); } console.log(container) } now I want to pass the container to the views. how can I archive that -
Auto creating model objects based on the relational model value
I have a model, which contains some fields, based on the one of the field value in the model, we need to create n number of objects in another model with default values. I have a model called Room and it contains a field called number_of_beds based on that field we need to create n number of objects in anothe model called Bed. Room(models.Model): room_no = IntegerField(primary_key=True,unique=True) number_of_beds = IntegerField() ''' and so on ''' Bed(models.Model): room_no = models.ForeignKey('Room', on_delete=models.SET_NULL, null=True) bed_no = models.IntegerField(blank=True,default='Increment value') ''' and so on ''' if number_of_beds =2, need to create two objects in Bed with default values under the same ForeignKey. Any help would be appreciated. -
No chat messages being sent in django-private-chat
I have set up django-private-chat as detailed in the official documents and this (how to implement Django-Private-Chat in Django 2) stack overflow answer. The app works and when i navigate to /dialogs/user I am presented with a chat page. However, when I send a message, it does not appear in the receivers page nor does it give any indication on my page that it was sent. Looking at my terminal I cannot see a post request and the message does not appear in the other users chat page. What could be the issue or how can I go about troubleshooting this app? -
How to pass a pattern through the reverse method
I get this error Reverse for 'coll.views.UpdateVote' not found. 'coll.views.UpdateVote' is not a valid view function or pattern name. to be honest i am jr and i don't know how to fix that ''' class CollDetailView(DetailView): if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(art=self.object,user=self.request.user) if vote.id: vote_form_url = reverse( UpdateVote, kwargs={'art_id':vote.art.id,'pk':vote.id}) class UpdateVote(LoginRequiredMixin, UpdateView): form_class = VoteForm queryset = Vote.objects.all() '''