Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Setting attr on choices in CheckboxSelectMultiple widget
I have a field that I am trying to add data to each choice within my Form class. Form Class: class SubmissionAcceptForm(forms.Form): """ Form for individually accepting submissions. """ submissions = forms.ModelMultipleChoiceField( queryset=Submission.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): submission_choices = kwargs.pop("submission_choices") super().__init__(*args, **kwargs) self.fields["submissions"].queryset = submission_choices self.fields["submissions"].initial = [ submission.pk for submission in submission_choices.filter(status='accepted')] self.fields["submissions"].widget.attrs['avg_score'] = [submission.avg_score for submission in submission_choices] self.helper = FormHelper() self.helper.layout = Layout( 'submissions', HTML("""<hr>"""), ButtonHolder( Submit('submit', 'Submit', css_class='btn btn-primary') ) ) Problem self.fields["submissions"].widget.attrs['avg_score'] = [submission.avg_score for submission in submission_choices] That line loops over the the submission scores, and renders all of the scores as an avg_score attr on every choice with all of the scores. <input avg-score="[Decimal('5.00'), Decimal('4.67'), Decimal('4.33'), Decimal('4.00'))]"> Example: if there are 4 choices, then all 4 scores are set as an avg_score attr on each choice. Desired Result For each choice, I want that choice's avg_score to be set as a data attr. <input avg-score="5.00"> Question How can I loop over each choice to set the attr on each individually? -
django field select and text entry problem
I want to allow the user to expand (add additonal text in the same field) on the selected option for a django model field. I have a working select option field on the form but it does not allow addition or exapnsion of the selected item. This is as expected. In the real world i want to add some information to the option selected. Can this be done? class MedicalForm(forms.ModelForm): OPTIONS = ( ("COLD", "Common cold"), ("FLU", "Flu strain"), ("VIRUS", "Unknown virus"), ) illness = forms.CharField(max_length=60, label='What is wrong?', widget=forms.(choices=OPTIONS)) I would like the user to describe the symptoms for example after selecting the option. I allow 60 chars for the illness field. -
After spawned uWSGI worker,django did not run without the error hint
I am running a python app on the centos server whose environment is django + uwsgi + nginx. After I use uwsgi --ini uwsgi.ini to init the uwsgi, the django did not run without the error hint in logs.The log is show as below: *** Starting uWSGI 2.0.17.1 (64bit) on [Fri May 24 00:41:29 2019] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-16) on 14 January 2019 13:09:48 os: Linux-3.10.0-693.2.2.el7.x86_64 #1 SMP Tue Sep 12 22:26:13 UTC 2017 nodename: iz8vbbvd4vh19pkxsm09q0z machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 2 current working directory: /home/firstWeb writing pidfile to uwsgi.pid detected binary path: /root/anaconda3/bin/uwsgi uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** chdir() to /home/firstWeb/ your processes number limit is 15088 your memory page size is 4096 bytes detected max file descriptor number: 65535 lock engine: pthread robust mutexes thunder lock: enabled uwsgi socket 0 bound to TCP address :8000 fd 3 uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** Python version: 3.7.0 (default, Jun 28 2018, … -
grid lines with for loop
so I want to have three grid lines, such that <div class="col-6 col-md-4"> each grid line has a content of course. so the code will probably tell what I'm trying to achieve <div class="row"> <div class="col-6 col-md-4"> {% for all_episode in episode %} <div class="card"> <a href="{% url 'episode_detail' slug=all_episode.slug %}"><img class="card-img-top" src='{{all_episode.image.url}}'></a> <div class="card-body"> <h5 class="card-title"> <a href="{% url 'episode_detail' slug=all_episode.slug %}">{{ all_episode.title }}</a> </h5> <p class="card-text">{{ all_episode.story |slice:":100" }}...</p> </div> <div class="card-footer"> <small class="text-muted"> <span class="h5"> <a href="{% url 'series_detail' slug=all_episode.series.slug %}">{{ all_episode.series }}</a> </span> / <span class="h6"><a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season }}</a></span></small> </div> {% endfor %} </div> </div> </div> but with the above code i get the cards in align vertically. so one card takes the whole line while there should be three cards. -
Sum of related objects across 2 FK to the same table, with conditions
I have two models: class User(Model): ... class Message(Model): sender = ForeignKey(User, CASCADE, 'sent_msgs') receiver = ForeignKey(User, CASCADE, 'rcvd_msgs') ignored = BooleanField() I'm trying to annotate a queryset of Users with a sum total of their related messages, i.e. sum of both sent_msgs and rcvd_msgs. Additionally, any Message with ignored=True should be ignored. I can do this with RawSQL fairly simply, using a subquery: SELECT COUNT("messages_message"."id") FROM "messages_message" WHERE "messages_message"."ignored" = FALSE AND ( "messages_message"."sender_id" = "users_user"."id" OR "messages_message"."receiver_id" = "users_user"."id" ) queryset = queryset.annotate(msgs_count=RawSQL(that_query_above)) Is there a way to do this without using RawSQL? -
pymongo.errors.OperationFailure: unsupported type in filter
I am working on Project Django with MongoDB (djongo) and I am using mongo atlas But when I am running this command python3 manage.py runserver python3 manage.py makemigrations this show this type error pymongo.errors.OperationFailure: unsupported type in filter But if I use my local mongod then it's works fine. Please help me My Db Setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'leverrage', 'HOST': 'mongodb+srv://xxxxxxx:xxxxxxxx@cluster0-dqfd1.mongodb.net/test?ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=true', 'USERNAME': 'xxxxxxx', 'PASSWORD': 'xxxxxx', 'ENFORCE_SCHEMA': True, } } -
How to handle a join of a variable number of incoming?
Is there a way to handle "partial Joins" in viewflow? For example: an order is received, and after checking and booking-in then each line item is manufactured in parallel (Split). Normally these would all join before the customer required-by date, and then the order will be dispatched with everything in one shipment. But sometimes there is an unexpected hold on one or more items because of a manufacturing issue that could not be known at the time the order is accepted. Is there a way to describe a "join" of the items that are ready for shipment to be joined into a partial shipment, and leaving the other manufacturing tasks to complete in however long it takes and be joined into another shipment later? Or is this too complex for viewflow, and should I be looking at several separate business processes? One process to book in an order which starts N manufacturing processes, and then code run by Celery to pick out completed manufacturing which needs to be dispatched, either because everything for that order is ready, or because the order requires partial shipment. I'm still teaching myself viewflow and working through the cookbook examples (and also Celery) so apologies … -
How to build a Serializer for a Normalized DataBase
Maybe my question has already been answered, but I could not find anything. Lets say that Im building a stock inventory system using Django + Django REST for the backend. To supply this I have this two models: class Shoe(models.Model): _id = models.AutoField(primary_key=True) description = models.CharField(null=False, blank = False) provider = models.CharField(null=False, blank=False) category = models.CharField(choices=CATEGORIES, null=False, blank=False) class Sizes(models.Model): shoe_id = models.ForeignKey(Shoe, on_delete=models.CASCADE) size = models.IntegerField(choices=SIZE_LIST, null=False, blank=False) amount = models.IntegerField(null=False,default=0) My doubt is, how can I (using ModelViewSet, cause based on my experience with DRF is the easiest way) serve JSON files like this: [ { "_id": "1", "description": "Air Max Black", "provider": "NIKE", "category": "Casual", "available_sizes": {36: 400, 37: 250}, #size: amount "amount": "650" #total amount }, ] Based on what I understand of DRF to "join" the two models in a JSON I should write a custom serializer right? Usually my serializers are like class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ['some_stuff_here'] Please help me or recomend me reading material for do that, I have read the DRF docs about Serializers but cant understand how to do stuff like this. -
Integrate or Embed Node Red into Django app
How i can integrate into my app the Node Red web application? is there any specific strategy that excludes the iFrame way? -
TypeError: the JSON object must be str, not 'DetailedResponse'
I have set up a Jupyter Notebook that connect my Postgresql database, call the datas within a table and apply a Machine Learning model from an API to these datas, but I keep getting a TypeError: the JSON object must be str, not 'DetailedResponse'. My Notebook is set up in 3 cells but I put them together below for clarity: from watson_developer_cloud import NaturalLanguageClassifierV1 import pandas as pd import psycopg2 import json conn_string = 'host={} port={} dbname={} user={} password={}'.format('119.203.10.242', 5432, 'mydb', 'locq', 'Mypass***') conn_cbedce9523454e8e9fd3fb55d4c1a52e = psycopg2.connect(conn_string) data_df_1 = pd.read_sql('SELECT description from public."search_product"', con=conn_cbedce9523454e8e9fd3fb55d4c1a52e) natural_language_classifier = NaturalLanguageClassifierV1( iam_apikey='F76ugy8hv1s3sr87buhb7564vb7************' ) classes = natural_language_classifier.classify('7818d2s519-nlc-1311', data_df_1.to_json()) print(json.loads(classes, indent=2)) And the full error output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-b6b7d122a500> in <module>() 2 3 classes = natural_language_classifier.classify('7818d2s519-nlc-1311', data_df_1.to_json()) ----> 4 print(json.loads(classes, indent=2)) /opt/conda/envs/DSX-Python35/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 310 if not isinstance(s, str): 311 raise TypeError('the JSON object must be str, not {!r}'.format( --> 312 s.__class__.__name__)) 313 if s.startswith(u'\ufeff'): 314 raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)", TypeError: the JSON object must be str, not 'DetailedResponse' I've tried so many things to get there and now I'm totally stuck and I can't find a way to fix this … -
How to give read/write permissions to dynamic sub-directory?
I have a FileNotFoundError after deployment when I run one of my python processes on the web server. I have a feeling this is a simple fix but I am not seeing what is happening here. restart apache (yes) test that database is working (yes) test that files are saving to media/DavidAlford directory (yes) do ls -la on project level directory to check read/write permissions (yes) do ls -la on ./media directory to check read/write permissions (write permissions not enabled to dynamic directory [DavidAlford]). It shows drwxr-xr-x 2 www-data www-data 4096 May 23 16:12 DavidAlford I do not want to start throwing random permissions lines at the directories on my production server but if I were to guess the fix would be sudo chmod 775 django_website/media/*? -
Append anchor tag in Django template with Jquery append method
anchor href is not working with jQuery append method and throwing an exception 'NoReverseMatch at /under_filter/' var card = `<a href="{% url 'index_phone' name=key %}">demo</a>` $("#container").append(card) -
With Django, how can I ensure manage commands use a different logging configuration?
Scenario I want to ensure (guarantee) that all manage command invocations generate logs to a custom location, based on the name; e.g. the command appends to a file named for the command: $ bin/django changepassword ... $ ls /var/log/django/changepassword.log $ bin/django shell $ ls /var/log/django/shell.log Options I have a custom logging configuration which I'm registering in settings.py, but that's not the place I'd expect to get such custom behavior. Monkey patch something? But what, and where? -
Django Rest Framework - Query for exact match on two fields in a mapping table
I'm using DRF and trying to search a mapping table for exact matches so I can update that record. I have the following tables: site - id - location - address circuit - id - name - ref sitecircuits - site_id - circuit_id - active_link my current DRF config as below: view class MonitoringConnectivitySet(viewsets.ModelViewSet): queryset = SiteCircuits.objects.all() serializer_class = MonitoringSerializerConnectivity permission_classes = (IsAdminUser,) filter_class = SiteCircuits filter_backends = (filters.SearchFilter,) search_fields = ('site__id','circuit__id') serialiser class MonitoringSerializerConnectivity(serializers.ModelSerializer): class Meta: model = SiteCircuits fields = ('site_id','circuit_id','active_link',) url router.register(r'conn_set', views.MonitoringConnectivitySet) this url http://localhost:8100/api/conn_set/?site__id=8&circuit__id=7 returns all the results (as I doesn't search at all) ive also tried using the below url: path('conn_set/<int:site_id>/<int:circuit_id>/', views.MonitoringConnectivitySet) serialiser: class MonitoringSerializerConnectivity(serializers.ModelSerializer): class Meta: model = SiteCircuits fields = ('site_id','circuit_id','active_link',) def get_queryset(self): site_id = self.kwargs['site_id'] circuit_id = self.kwargs['circuit_id'] return SiteCircuits.objects.filter(site_id=site_id,circuit_id=circuit_id) view: class MonitoringConnectivitySet(viewsets.ModelViewSet): queryset = SiteCircuits.objects.all() serializer_class = MonitoringSerializerConnectivity permission_classes = (IsAdminUser,) which also fails when using the url (indicating it only takes one value not two http://localhost:8100/api/conn_set/8/7 does anyone know the right combination here? is there any special needed to be done to filter and update the mapping table? Thanks -
Gerar Pdf no admin do django
Como eu gero um pdf no admin do django? eu ja tenho as views, consigo gerar no frontend com html tudo certinho, mas como coloco um botao no admin pra gerar ou redirecionar para o link do pdf? estou perdido nisso. class EmpresaAdmin(admin.ModelAdmin): list_display = ('nome', 'telefone', 'cnpj',) search_fields = ('nome', 'cnpj',) list_filter = ( 'nome', 'cnpj', 'telefone', ) class AssociadoAdmin(admin.ModelAdmin): list_display = ('nome', 'endereco', 'telefone', 'cpf', 'data_filiacao', 'data_nascimento' ) search_fields = ('nome', 'cpf',) list_filter = ( 'nome', 'cpf', 'telefone', ) class AgendamentoAdmin(admin.ModelAdmin): list_display = ('nome','inicio', 'fim','assunto', ) search_fields = ('nome', 'cpf',) list_filter = ( 'nome', 'inicio', 'assunto', ) #views class Render: @staticmethod def render(path: str, params: dict, filename: str): template = get_template(path) html = template.render(params) response = io.BytesIO() pdf = pisa.pisaDocument( io.BytesIO(html.encode("UTF-8")), response) if not pdf.err: response = HttpResponse( response.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'attachment;filename=%s.pdf' % filename return response else: return HttpResponse("Error Rendering PDF", status=400) -
Why I dont get response after successfully saving a serial number using ModelForm?
I am sending a post request from a scanner with scanned serial numbers to django server. {"serial_number": "70:B3:D5:A9:C8:62", "bom": "2019/05/08"} views.py def camera_register(request): form = forms.RegisterCamerasForm(data=request.POST) if form.is_valid(): instances = form.save(commit=False) # instances.serial_number = instances.serial_number.lower() instances.last_sighting_ip = request.META.get('REMOTE_ADDR') instances.last_sighting_time = datetime.datetime.now() form.save() form.save_m2m() return JsonResponse(1, safe=False) else: return JsonResponse(form.errors, status=200) forms.py class RegisterCamerasForm(forms.ModelForm): def clean(self): super().clean() class Meta: fields = '__all__' exclude = ['group'] model = camera_models.Camera models.py class Camera(TimeStampedModel): public_identifier = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) serial_number = models.CharField(max_length=100, unique=True, null=True) name = models.CharField(max_length=50, blank=True, null=True) group = models.ForeignKey('CameraGroup', on_delete=models.SET_NULL, null=True, related_name='cameras', related_query_name='cameras') # last seen at ip last_sighting_ip = models.CharField(max_length=50, blank=True, null=True) last_sighting_time = models.DateTimeField(null=True, blank=True) objects = CameraQuerySet.as_manager() def __str__(self): return self.name or self.serial_number or str(self.public_identifier) def as_json(self): return { 'serial_number': self.serial_number } I am sending the request and I save it to the database, but I do not get a response and I need that to be able to make a pytest and merge it to develop. I tried saving it with form.save() form.save_m2m() since I am modifying some datata. I add time and IP adress.(Have to make it all lowercase but one thing a a time) When I am not saving it with form.save() I get a … -
Action decorators kwargs not passed on when retrieving the view with "as_view" method on a ViewSet
In one app, I have the following ViewSet: class MyViewSet(MyGenericViewSet, ListModelMixin): queryset = MyModel.objects.all() serializer_class = MyModelSerializer @action(detail=False, methods=["post"], accepted_renderers=(MyJsonRenderer,)) def custom_action(request, *args, **kwargs): # Do some stuff here MyViewSet is routed with a DefaultRouter. I need to specify MyJsonRenderer because it comes second in my DEFAULT_RENDERERS setting (I have an HTML renderer first) and this particular action is not meant to be used with a web browser. It works fine when I hit the routed URL with a POST request, and always returns JSON content. However I also need to adapt my site to an old AJAX API, so in another adapter app, I have the following function-based view: @csrf_exempt def ajax(request, *args, **kwargs): custom_action_view = MyViewSet.as_view({"post": "custom_action"}) return custom_action_view(request, *args, **kwargs) If my request does not specify that it is expecting JSON content in its header or params, content negotiation fails because the default HTML renderer is used (500 Internal Server Error). The action is performed on the server but the response is not rendered. How can I make the view obtained with as_view to use the proper renderer class ? -
how to implement ajax/jquery in checkbox?
Here i have a form to add students with the courses and teachers value.Students can have multiple courses and teachers .But i want to make this form little more effective in a way that if a user check one/multiple course from checkbox then in the teacher's checkbox field only the teachers that have these courses should be displayed .How can i do that ?? how can i implement ajax/jquery here? models class Course(models.Model): title = models.CharField(max_length=250) class Teacher(models.Model): name = models.CharField(max_length=50) courses = models.ManyToManyField(Course) class Student(models.Model): name = models.CharField(max_length=100) courses = models.ManyToManyField(Course) teacher = models.ManyToManyField(Teacher) add_student.html <h5>Courses</h5> {% for course in courses %} <input name ="courses" type="checkbox" id="course-{{course.id}}" value="{{course.id}}"> <label for="course-{{course.id}}">{{course.title}}</label> {% endfor %} </div> <div class="form-group"> <h5>Teachers</h5> {% for teacher in teachers %} <input name ="teacher" type="checkbox" id="teacher-{{teacher.id}}" value="{{teacher.id}}"> <label for="teacher-{{teacher.id}}">{{teacher.name}}</label> {% endfor %} </div> -
Is there any free and ready to use python + django shopping website, I want to start my online shop and to code
I am a python engineer who would start his fisrt Django online shop. I have an experience with cherrypy, a litle Framework. I am asking if there is a ready to use Django website for shopping, which I will put it in production (raspberrypi server) with code changes then I will impove it add functionalities. Thanks I have looked into github I found some example but they are far to be ready to use application (frontend + backend) -
How to pass value for django forms.SplitDateTimeField?
I'm trying to pass value for django form's SplitDateTime field. But it keeps showing me This field is required error. >>> from django import forms >>> class F(forms.Form): ... a = forms.SplitDateTimeField() ... >>> f = F(data={'a': ['2020-04-04', '12:12']}) >>> f.is_valid() False >>> f.errors {'a': ['This field is required.']} where as upon passing the same value to clean method of SplitDateTime object, it works. >>> b = forms.SplitDateTimeField() >>> b.clean(['2020-04-04', '12:12']) datetime.datetime(2020, 4, 4, 12, 12, tzinfo=<UTC>) >>> Is there anyway to overcome form field required error? or Am I missing any? -
Django, crear token persistente para dispositivos móviles
Desde Django como backend, quiero crear un token que expire normalmente como trabaja JWT pero cuando las peticiones sean de un dispositivo movil, que el token no caduque, alguien tiene alguna idea? -
How to display the image(imagefield) on the web page in django
I'm writing some codes about uploading and showing pictures by django,but I can not show the picture on the web page,the uploading function might be correct.I've tried many solutions,but none of them can work. class IMG(models.Model): resumeImg=models.ImageField(upload_to='img') CompanyName=models.CharField(max_length=200) These are uploading and showing functions: def uploadImg(request): if request.method=='POST': new_img=IMG( resumeImg=request.FILES.get('resumeImg'), CompanyName=request.FILES.get('resumeImg').name ) new_img.save() return render(request,'lib/uploading.html') def showImg(request): imgs=IMG.objects.all() content={'imgs':imgs} for i in imgs: print (i.resumeImg.url) return render(request,'lib/showing.html',content) Is there anything wrong with url? It's lib\urls.py,lib is the name of my app: urlpatterns = [ .......... path('upload/',views.uploadImg), path('show/',views.showImg), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'lib/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static') MEDIA_ROOT = os.path.join(BASE_DIR,'lib\media').replace('\\','/') MEDIA_URL='/media/' STATICFILES_DIRS = ( ('css', os.path.join(STATIC_ROOT, 'css').replace('\\', '/')), ('js', os.path.join(STATIC_ROOT, 'js').replace('\\', '/')), ('images', os.path.join(STATIC_ROOT, 'images').replace('\\', '/')), ('upload', os.path.join(STATIC_ROOT, 'upload').replace('\\', '/')), ) Here is the code about Html.Is there anything wrong with img.resumeImg.urls?? <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for img in imgs %} <img src="{{ img.resumeImg.url }}"/> {% endfor %} </body> </html> can not see the image -
How to integrate the bokeh server INTERACTIVITY with django?
I already know how to display standalone bokeh plots on Django. What I'm looking for now is a high-level explanation on how to connect the interactive bokeh server (the sample I'm using is https://demo.bokeh.org/weather) to my Django project. The key word here to stress is interactive. When I use the dropdowns on my Django page the Bokeh server should respond interactively as it normally does when I run bokeh serve --show app.py for example. As you can see below, I've already thrown most of the tutorial's code into my django view. It all displays perfectly, however there's no interactivity happening - when I select to view Seattle's data, for example, nothing happens - because the bokeh server isn't being activated or something? # all my imports up here... def homepage(request): return render(request, 'pages/landing.html') def alerts_dashboard(request): # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # THE FOLLOWING CODE FROM HERE ON DOWN IS PURE COPY-PASTED FROM # THE BOKEH DEMO LINK ABOVE STATISTICS = ['record_min_temp', 'actual_min_temp', 'average_min_temp', 'average_max_temp', 'actual_max_temp', 'record_max_temp'] def get_dataset(src, name, distribution): df = src[src.airport == name].copy() del df['airport'] df['date'] = pd.to_datetime(df.date) # timedelta here instead of pd.DateOffset to avoid pandas bug < 0.18 (Pandas issue #11925) df['left'] = df.date - datetime.timedelta(days=0.5) df['right'] = df.date … -
Django Rest Framework Pagination: Cleaner way to return the page containing the requested data
I have a CustomPagination class that can search for a given post data and return the page containing that data. This does work. However, when dealing with tons of data, this might cause performance issues. I need to implement a cleaner way to search for a post data without iterating through the pages and refrain from using constants like number = 1 pagination.py class CustomPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): page_size = self.get_page_size(request) if not page_size: return None paginator = self.django_paginator_class(queryset, page_size) page_number = request.query_params.get(self.page_query_param, 1) if page_number in self.last_page_strings: page_number = paginator.num_pages id = request.query_params.get('id', None) if id: post = Post.objects.get(pk=id) number = 1 while number <= paginator.num_pages: self.page = paginator.page(number) if post in list(self.page): break number += 1 else: self.page = paginator.page(page_number) if paginator.num_pages > 1 and self.template is not None: self.display_page_controls = True self.request = request return list(self.page) def get_paginated_response(self, data): return Response({ 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'total_pages': self.page.paginator.num_pages, 'results': data }) -
Ajax does not see the function?
There is a CBV (JointProductsDetail) that is responsible for rendering the template. In the template I am trying to execute an ajax request (get type). I specify the url. The request does not come to the specified function, but I get success in the response. template <form> <a href='#' class='add_to_cart'> <button class='btn btn-danger' id="make_an_order" type="button">abc</button> </a> </form> <script> $(document).ready(function(){ $('.add_to_cart').on('click', function(e){ $.ajax({ type: "GET", url: "{% url 'add_to_cart' %}", data: {}, success: function(data){ alert('Товар добавлен в корзину'); location.reload(); }, error: function(data){ alert('Произошла ошибка. Попробуйте позже') } }) }) }) </script> urls from django.conf.urls import url from products.views import ( Categories, ProductsOrderStatus, ProductsOrderCancel, Products, ProductsCreate, ProductsDetail, ProductsUpdate, ProductsDelete, ProductsCopy, ProductsReport, JointProducts, JointProductsCreate, JointProductsDetail, JointProductsUpdate, JointProductsDelete, JointProductsCopy, JointProductsReport, add_to_cart_view, orders_week_view, orders_month_view, orders_year_view, bills_week_view, bills_month_view, bills_year_view, basket_view, cart_true_view, remove_cart_view, BillDetail, privat24 ) urlpatterns = [ url(r'^(?P<section_slug>products|joint_products)/$', Categories.as_view(), name='products_categories_list'), url(r'^(?P<section_slug>products|joint_products)/orders/(?P<pk>[\d]+)/status/$', ProductsOrderStatus.as_view(), name='products_order_status'), url(r'^(?P<section_slug>products|joint_products)/orders/(?P<pk>[\d]+)/cancel/$', ProductsOrderCancel.as_view(), name='products_order_cancel'), url(r'^products/add/$', ProductsCreate.as_view(), name='products_create'), url(r'^products/(?P<slug>[-\w]+)/add/$', ProductsCreate.as_view(), name='products_create'), url(r'^products/(?P<slug>[-\w]+)/$', Products.as_view(), name='products_list'), url(r'^products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/$', ProductsDetail.as_view(), name='products_detail'), url(r'^products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/update/$', ProductsUpdate.as_view(), name='products_update'), url(r'^products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/delete/$', ProductsDelete.as_view(), name='products_delete'), url(r'^products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/copy/$', ProductsCopy.as_view(), name='products_copy'), url(r'^products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/report/$', ProductsReport.as_view(), name='products_report'), url(r'^joint_products/(?P<slug>[a-zA-Z0-9-][^_]+)/add/$', JointProductsCreate.as_view(), name='joint_products_create'), url(r'^joint_products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/$', JointProductsDetail.as_view(), name='joint_products_detail'), url(r'^joint_products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/update/$', JointProductsUpdate.as_view(), name='joint_products_update'), url(r'^joint_products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/delete/$', JointProductsDelete.as_view(), name='joint_products_delete'), url(r'^joint_products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/copy/$', JointProductsCopy.as_view(), name='joint_products_copy'), url(r'^joint_products/(?P<pk>[\d]+)/(?P<slug>[-\w]+)/report/$', JointProductsReport.as_view(), name='joint_products_report'), url(r'^joint_products/(?P<slug>[a-zA-Z0-9-][^_]+)/$', JointProducts.as_view(), name='joint_products_list'), url(r'^add_to_cart/$', add_to_cart_view, name='add_to_cart'), url(r'^remove_cart/$', remove_cart_view, name='remove_cart'), url(r'^orders_week/$', orders_week_view, name='orders_week'), url(r'^orders_month/$', orders_month_view, name='orders_month'), url(r'^orders_year/$', orders_year_view, …