Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to fix this issue? [closed]
I'm developing a website for an online store with Django and I want to show users a review of their cart while they are filling their billing addresses and stuff. I have my cart on another directory, so how do I bring that cart in my html form for checkout? I tried to do the same thing that I did with my cart.html but it is not working. Can anyone please help me out? My checkout.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yno" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <!-- Custom styles for this template --> <link href="./css/form-validation.css" rel="stylesheet" /> </head> <div class="container"> <div class="row"> <body class="bg-white"> <div class="container"> <div class="py-5 text-center"> <img class="d-block mx-auto mb-4" src="https://getbootstrap.com/assets/brand/bootstrap-solid.svg" alt="" width="" height="" /> <h2>Checkout</h2> <p>Enter your billing address</p> </div> <div class="row"> <div class="col-md-4 order-md-2"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted">Your cart</span> <span class="badge badge-secondary badge-pill">{{ request.session.items_total }}</span> </h4> <ul class="list-group mb-3"> {% for item in cart.cartitem_set.all %} <li class="list-group-item d-flex justify-content-between lh-condensed" > <div> <h6 class="my-0">{{ item.product.name }}</h6> <small class="text-muted">Brief description</small> </div> <span … -
Django -Page not found (404) Request Method: GET Method
I am very new to Django ,I am trying to run a URL ,however I get this error of page not found.I went through almost 90% of the posts here but nothing worked for me. Here are three .py files views.py..... from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('Hello world....') **products\urls.py**** from django.urls import path from . import views #.means current folder ,we are importing a module urlpatterns=[ path(' ', views.index), ] pyshop\urls.py....... from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('products/',include('products.urls')) ] Error I get..... Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/ Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order: admin/ products/ The current path, products/, didn't match any of these. -
Django JsonResponse lose precision
I have a big int such as 6222600820001059483 in python int type. When I send to browser use JsonResponse I found that the value was changed to 6222600820001060000. I think this caused by the precison lose when JsonResponse send it to browser. So how to prevent this precision lose? I'm using django 2.2.12. -
Why i am getting error while running Django manage.py migrate command
When running python manage.py migrate getting error (MyDjangoEnv) srijan@srijan:~/Desktop/django/first_project$ python manage.py syncdb --migrate Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/core/management/init.py", line 337, in execute django.setup() File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 985, in _gcd_import File "", line 968, in _find_and_load File "", line 957, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 693, in exec_module File "", line 799, in get_code File "", line 759, in source_to_code File "", line 222, in _call_with_frames_removed File "/home/srijan/Desktop/django/first_project/first_app/models.py", line 24 return (str)self.date ^ SyntaxError: invalid syntax -
Can't forward or skip video on Django website
I am trying to create a website for myself. It is kind of a Youtube on a local network. I am using video.js (have also tried Plyr.io) to play the video, but i can not fast forward the video. Or go back in the video. I can only play it from begining to the end. If i try to skip forward it only resets. What am I doing wrong? Thanks in advance! -
Django Redirect to a view with ajax call
I have a Django application. Inside it, I use some Ajax calls to a function when I would like to manipulate backend, without affecting the front end. In one function I would like to redirect the user to a home page. I have: def some_function(request, param_one): other_function(request.user, param_one) return redirect('mypage:home') and in JS I have: $.ajax({ type : "GET", url : '/url to my function/', error: function(){ console.log('Error complete'); } }); I see that I get the right page in chrome developer tools But nothing happened... So js get the HTML page but didn't render it. -
Django REST framework: how to combine the same type of model
How to combine many models in one query set so that it would be possible to use HyperlinkedModelSerializer using pagination? I need to connect many models with the same fields. That's what I did, but it doesn’t suit me.: **"models.py"** class Merketing(models.Model): question = models.CharField(max_length=500, unique=True) answer = models.CharField(max_length=500) class Management(models.Model): question = models.CharField(max_length=500, unique=True) answer = models.CharField(max_length=500) **"serializers.py"** class MerketingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Merketing fields = ['id','question', 'answer'] class ManagementSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Management fields = ['id','question', 'answer'] class FiltersSerializers(serializers.Serializer): model_1 = MerketingSerializer(read_only=True,many=True) model_2 = ManagementSerializer(read_only=True,many=True) **"viesw.py"** class MerketingViewSet(viewsets.ModelViewSet): queryset = Merketing.objects.all().order_by('question') serializer_class = MerketingSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [filters.SearchFilter] search_fields = ['question'] class ManagementViewSet(viewsets.ModelViewSet): queryset = Management.objects.all().order_by('question') serializer_class = ManagementSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [filters.SearchFilter] search_fields = ['question'] class FiltersView(APIView): def get(self, request, *args, **kwargs): filters = {} filters['model_1'] = Merketing.objects.all().order_by('question') filters['model_2'] = Management.objects.all().order_by('question') serializer = FiltersSerializers(filters) return Response (serializer.data, status=HTTP_200_OK) -
django rest framework and redis
I'm working on a project where there are like 30 to 40 gps trackers, I want to give the client the ability to select any tracker and then track its location. I was able to get the trackers to communicate using a django rest framework, being a real time application I'm using channels. The database is divided such that the one table is for the trackers, and another table for tracking their current location. Using the seconds table I'm able to server the requested trackers location to the user. I wanted to know if there is a way for me to implement django rest framework with redis, such that the post request from the tracker is directly cached, instead of inserting or updating in the database. The historical location of the trackers is not important to me, just their current location. -
How to return Django project's error messages when I use nginx in production mode
I have developed the Django project and deployed it to the Amazon's free tier EC2 services. Everything is fine except errors message that are not returning back. I am using the project in production mode. Here is my nginx.conf upstream app { server web:8000; } server { listen 80; location / { proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range, Authorization'; # # Tell client that this pre-flight info is valid for 20 days # add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = GET) { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range, Authorization'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; } if ($request_method = POST) { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range, Authorization'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; } ... } location /static/ { alias /home/user/web/staticfiles/; } location /media/ { alias /home/user/web/media/; } } Explanation for above image [Console Log]: Successful request and response - it was … -
Django multiple formsets and form with CreateView - form_valid()
I am Django beginner and trying to modify https://dev.to/zxenia/django-inline-formsets-with-class-based-views-and-crispy-forms-14o6 to support multiple formsets of the same type using prefix. The form is displayed fine but clicking "Save" a POST is initiated but nothing happens. The POST is larger than the GET (which reflects my added data) but nothing is saved/created. class BudgetCreate(CreateView): model = Budget template_name = 'budget/budget_create.html' form_class = BudgetForm success_url = '/location' def get_context_data(self, **kwargs): data = super(BudgetCreate, self).get_context_data(**kwargs) if self.request.POST: data['cat1'] = LineItemFormSet(self.request.POST, prefix='cat1') data['cat2'] = LineItemFormSet(self.request.POST, prefix='cat2') data['cat3'] = LineItemFormSet(self.request.POST, prefix='cat3') data['cat4'] = LineItemFormSet(self.request.POST, prefix='cat4') data['cat5'] = LineItemFormSet(self.request.POST, prefix='cat5') data['cat6'] = LineItemFormSet(self.request.POST, prefix='cat6') data['cat7'] = LineItemFormSet(self.request.POST, prefix='cat7') else: data['cat1'] = LineItemFormSet(prefix='cat1') data['cat2'] = LineItemFormSet(prefix='cat2') data['cat3'] = LineItemFormSet(prefix='cat3') data['cat4'] = LineItemFormSet(prefix='cat4') data['cat5'] = LineItemFormSet(prefix='cat5') data['cat6'] = LineItemFormSet(prefix='cat6') data['cat7'] = LineItemFormSet(prefix='cat7') return data def form_valid(self, form): context = self.get_context_data() cat1 = context['cat1'] cat2 = context['cat2'] cat3 = context['cat3'] cat4 = context['cat4'] cat5 = context['cat5'] cat6 = context['cat6'] cat7 = context['cat6'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if cat1.is_valid() and cat2.is_valid() and cat3.is_valid() and cat4.is_valid() and \ cat5.is_valid() and cat6.is_valid() and cat7.is_valid(): cat1.instance = self.object cat1.save() cat2.instance = self.object cat2.save() cat3.instance = self.object cat3.save() cat4.instance = self.object cat4.save() cat5.instance = self.object cat5.save() cat6.instance = self.object cat6.save() cat7.instance … -
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' in django save function
I have these model: class Event(models.Model): """ Event Model """ day = models.DateField(u'Day of the event', help_text=u'Day of the event', null=True) start_time = models.TimeField( u'Starting time', help_text=u'Starting time', null=True) end_time = models.TimeField( u'Final time', help_text=u'Final time', null=True) end_day = models.DateField( u'End Day of the event', help_text=u'End Day of the event', null=True) total_minutes = models.DecimalField(default=0.00, max_digits=19, decimal_places=2) I want to calculate diffrence between the minutes of two TimeFields So I have done the following: from datetime import date, datetime, timedelta def save(self, *args, **kwargs): start = datetime.combine(self.day, self.start_time) end = datetime.combine(self.end_day, self.end_time) diffrence = end - start self.total_minutes = diffrence.total_seconds() / 60 super(Event, self).save(*args, **kwargs) but getting the error TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time. Can anyone tell me why I am getting the error? -
How to use update_fields in Django signals
I'm trying to use an the 'update_fields' argument passed to signals in Django. I've got something very simple for now, namely: @receiver(pre_save, sender=models.UserAdmin) @receiver(pre_save, sender=models.UserGroupAdmin) def update_timestamps(sender, instance, update_fields, **kwargs): print(f'Update fields: {update_fields}') update_fields shows as None no matter what is being updated, which indicates I've not understood something. What am I missing? -
Django path not working and it direct me to wrong websites
I'm build my first website and i got stuck because paths to siedes are wrong. I will show you at a example: I have a website: '' When i click "Search" on the nav bar i want to go "/search" (search is added as a block in base.html) But when im in "/search"and i click "register" on nav bar i want to go "/register" (register is a block either) The problem is that when i click "register" when i am on "/search" its direct me to "/search/register" and such a site doesnt exist. Going to home ('') from every site is working. My urls: from django.contrib import admin from django.urls import path, include from users import views as users_views from polls import views as polls_views urlpatterns = [ #path('', include('polls.urls')), path('', polls_views.home, name='home'), path('ListSearch/', polls_views.ListSearch, name='ListSearch'), path('register/', users_views.register, name='register'), path('admin/', admin.site.urls), ] My nav bar: <nav> <div class="nav-wrapper" style="background-color:#174c9c;"> <div class="container"> <a href="/" class="brand-logo">ShoppingList</a> <ul class="right hide-on-med-and-down"> <li><a href="ListSearch">Search for list </a></li> <li><a href="/">Log in</a></li> <li><a href="register">Register</a></li> </ul> </div> </div> </nav> With "setup" is showed you above it is working as i described it, if i change "register/" to "register" adn do the same with "ListSearch" it gives me 404: … -
React Router changing URL, but component not rendering
I have been trying to learn React over the past couple of weeks and started working on a site which displays art works. I would like for the user to be able to click on one of the images displayed and for a new component to be loaded with information about the work. I have the implementation below of the gallery view, but when I click on an image the URL changes, but the WorkPage component never loads. Would anyone be able to spot what I am doing wrong? The links and images are generated in the renderItems() function. import React, { Component } from "react"; import Masonry from 'react-masonry-css'; import WorkPage from "./WorkPage" import axios from "axios"; import { Link, Route, Switch, useRouteMatch, useParams } from "react-router-dom"; import { BrowserRouter as Router } from "react-router-dom"; class Works extends Component { constructor(props) { super(props); this.state = { viewPaintings: true, workList: [] }; axios .get("http://localhost:8000/api/works/") .then(res => this.setState({ workList: res.data })) .catch(err => console.log(err)) }; displayPaintings = status => { if (status) { return this.setState({ viewPaintings: true }) } return this.setState({ viewPaintings: false }) }; renderTabList = () => { return ( <div> <ul className="tab-list-buttons"> <li onClick={() => this.displayPaintings(true)} className={this.state.viewPaintings ? … -
Pass data to django view with ajax
I am very new to django and the whole world of jquery, ajax, etc. I am having a page that when a function (javascript, jquery) function is run, I use the POST method to pass some data to my django view. My jquery function is: function handleClick(e) { var myDataVariable = Variable var url = window.location.href var obj = {'Cellid': myDataVariable } $.ajax( {type:'POST', url: url, data: JSON.stringify(obj), contentType: 'application/json; charset=utf-8', success: function (data) {} }); } and in my django views I have: def Main(request): if request.method == 'POST': params = json.loads(request.body) Cellid = params['Cellid'] CellData = cellData.cell_Data(int(Cellid)) else: CellData =[] context = { 'CellData':CellData, } return render(request, 'Main/Main.html', context) Although the page works fine, when the function is called I am getting an error: Forbidden (CSRF token missing or incorrect.): /Main/Main Can someone please help me with this error? It is probably something simple but as I said I am very new to this and it is killing me! I would really appreciate a simple and easy to understand explanation. Many thanks! -
WHEN I DELETE A SINGLE RECORD INTO A TEMPLATE ALL RECORDS ARE DELETED
I have two models child and academy by which these two models have relationship to each other here is child models from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) def __str__(self): return self.Firstname And here is academy model from django.db import models from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Average_grade = models.CharField(max_length = 10) def __str__(self): return str(self.Student_name) Here is my views.py file that contain delete functionality,instead of delete a single academy record of that specific child it delete all academic details of that specific child def delete_academy(request,pk): child=get_object_or_404(Child_detail,pk=pk) academy=Academic.objects.filter(Student_name=child) if request.method == 'POST': academy.delete() return redirect('more',pk=pk) context={ 'child':child, #'form':form } return render(request,'functionality/more/academy/delete.html',context) -
Setting ArrayField to null or []
files = fields.ArrayField(models.UUIDField(null=True), blank=True, default=None) So I have this line in my model, the task is to keep array of UUIDs of files in the field "files", but i still get an error The array field was imported from postgres fields like so from django.contrib.postgres import fields and models was imported from django.db import models Here is the error File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 447, in add_field self.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 137, in execute cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: column "files" contains null values -
Why a speciffic CSS class in not applied?
I have recently started learning Django framework with Python. I've been doing a course on YouTube. Unfortunately, one of the steps did not go as on the course. The CSS and JS features does not apply to my page. Do you have some suggestions to make it apply to my page? I was using the starter template. <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <meta charset="UTF-8"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django blog</title> {% endif %} </head> <body> <div class="container"> {% block content %}{% endblock %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> ``` -
Dynamically How to arrange bootstrap grid vertically for mega menu categories
I am using Django for may backend, I have render a list of categories in an ordered sequence. I want to display the categories mega-menu using the bootstrap grid system, but in vertical sequence HTML : <div class="menu-sub" id="mega_id"> <div class="col-md-8" style=""> <div class=""> {% for category in cateogries %} <div class="masonary-grid-item menu-col col-right-33 col-box-category" style=""> <h3 class="menu-category"> <a style="text-transform: uppercase;" href="#0" target="_blank" {{category.name}} </a> </h3> <ul class="ul-height"> {% category_child category.id as childs %} {% for child in childs %} <li><a class="child-a" href="#0" target="_blank">{{child.name}}</a></li> {% endfor %} </ul> </div> {% endfor %} </div> </div> <div class="col-md-4" style="text-transform: uppercase !important;"> <div class="menu-col col-r-100"> <!- Other siderbar --> </div> </div> check the image for reference. -
Share data from host to docker container
I have an application that writes correctly a file generated on a docker container to the host machine. Using the same approach, I was thinking that the problem would be similar if I want to read a file on the container but coming from the host. I use volumes in the docker-compose file: volumes: - /home/qcuci/dockerized_apps/unidosi_logs:/app/unidosi/data/unidosi_logs # here I want to read from the host - /home/qcuci/dockerized_apps/unidosi_silicon:/app/unidosi/data/unidosi_silicon # here I write to host Why I can't read the file? In fact, if I use the bash command I can see that the files aren't copied from the host to the container accordingly -
How can I solve the problems of Testing that are not in the same model?
In my model, there are fields as follows. class Home(TitleSlugDescriptionModel): seller= models.ForeignKey("data.seller", null=True, on_delete=models.SET_NULL) date = models.DateField() picture = models.ImageField(upload_to="images") In my test.py class HomeTestCase(TestCase): def test_random(self): with open("img/no-image.jpg", "rb") as f: for home in range(10): G(Home, picture=ImageFile(f), seller=F(name="test1"), I have a problem when I test. It alerts that: django_dynamic_fixture.ddf.InvalidConfigurationError: ('homes.models.Home.seller', BadDataError('data.models.Seller', ValidationError({'data': ['This field cannot be blank.']}))) I know that This field cannot be blank, And I solved the problem as follows. [add name data] class HomeTestCase(TestCase): def test_random(self): with open("img/no-image.jpg", "rb") as f: for home in range(10): G(Home, picture=ImageFile(f), seller=F(name="test1"), data=F(name="test2") It does not work and alerts that django_dynamic_fixture.ddf.InvalidConfigurationError: Field "data" does not exist. I don't know how to fix it. Can someone recommend me? Thank you very much -
PermissionError: [Errno 1] in collectstatic in django
I have use command python manage.py collectstatic But I got permission error -
Django objects error in view, why I got this error? It looks like my model does not exist
This is my view code: class Planificare_concedii(AllView): template_name = "pep/planificare_concedii.html" def get_context_data(self, *args, **kwargs): magazinu = self.request.GET.get('magazinul') queryset = Planificare_concedii.objects.filter(magazin=magazinu) context = context = super(Planificare_concedii, self).get_context_data( *args, **kwargs) return context This is the error that I got in view page: AttributeError at /planificare_concedii/ type object 'Planificare_concedii' has no attribute 'objects' -
how to create unique id for each department in django model
i created a model in django for student information <!-- language: python --> class student(models.Model): department_choices=(('cse','cse'),('mech','mech'),('EEE','EE')) name=models.CharField(max_length=35) department=models.CharField(max_length=30,choices=department_choices) i want id to be generated unique for department for example if i chose cse department id should be cse0001, cse002 or if mech means id should be mech001 , mech002 what should i do -
Django ajax error: net::ERR_TOO_MANY_REDIRECTS
I want to implement search with django and ajax. HTML: <form class="form-horizontal action-form filter-form" method="get" id="search-form-panel"> {% csrf_token %} <div class="form-group"> <div class="col-lg-6"> <input type="text" name="product-title" class="form-control" placeholder="products" id="search-text-panel"> </div> <div class="col-lg-6"> <button type="button" class="btn btn-success search-btn">search</button> </div> </div> </form> <div class="table-responsive" id="manager-list-container"> <table class="table table-striped table-bordered table-hover" id="basic_list" style="width:100%"> <thead> ... <script> let updateProductSearchUrl = '{% url "update-product-search-item" %}'; </script> <script type="text/javascript" src="/static/product/panel-update-product.js?v={{ SITE_VERSION }}"></script> and in JS: $(document).ready(function () { console.log('it is calling JS part'); $('.search-btn').click(function () { submitSearch(); }); $("#search-text-panel").keyup(function (e) { if (e && e.keyCode === 13) { submitSearch(); } else if (e) { let searchText = $('#search-text-panel').val().trim(); if (searchText.length > 3) submitSearch(); } e.stopPropagation(); e.preventDefault(); return false; }); function submitSearch() { let searchText = $('#search-text-panel').val().trim(); console.log(updateProductSearchUrl); $.get({ url: updateProductSearchUrl, data: {'q': searchText}, method: 'GET', success: function (res) { if (res) { $('#basic_list').find('tbody').empty().append(res.res); } } }); } }); ursls.py: path('update-product-search-item/', views.update_product_search_item, name='update-product-search-item'), and in views.py: @staff_only(url_name='panel/product-type/update') def update_product_search_item(request): print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2') print('it is calling this funciton') try: products = ProductType.objects.first() res = render_to_string('product/panel_update_product_type.html', {'products': products}, request=request) return HttpResponse(json.dumps({'res': res}), content_type="application/json") except Staff.DoesNotExist: return HttpResponseForbidden() by using these codes, when I click on search box it returns : jquery-3.1.1.min.js:4 GET http://127.0.0.1:8082/admin/login/?next=/admin/update-product-search-item/%3Fq%3Dproducts net::ERR_TOO_MANY_REDIRECTS what is this error and how can …