Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using variables across django templates 2
I have a program that i upload a word document and the document is converted into an html page. I'm using docx2txt to get the images and text from the document. This saves the images to a tempImages folder. I'm trying to then go through this folder and save the images to a django database. Everything else is working fine but django is not saving the images in the correct folder. please help -
Postgres suddenly raise error '/usr/lib/libpq.5.dylib' (no such file)
when I run Django project or any code related to Postgres : Referenced from: '/Users/mahmoudnasser/.local/share/virtualenvs/wyspp_backend-PwdII1PB/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so' Reason: tried: '/opt/homebrew/opt/postgresql/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file) I tried many solutions online but none of them worked. Note: I use MacOS -
I want to pass user upload image directly another function for extract text in dingo
views.py def index(request): # lastimage = Imageadd.objects.latest('image') # print(lastimage) # imagefile = lastimage.image # image = cv2.imread(imagefile) if request.method == 'POST' and request.FILES['pic']: image = request.FILES['pic'] # image = cv2.imread(image) # print(image) de = Detect_Text(image) # t = all_text(de) # print(t) obj = Imageadd(image=image) obj.save() return redirect('index') return render(request,'index.html') ex.py def Detect_Text(image_file): def rotate( image: np.ndarray, angle: float, background: Union[int, Tuple[int, int, int]] ) -> np.ndarray: old_width, old_height = image.shape[:2] angle_radian = math.radians(angle) width = abs(np.sin(angle_radian) * old_height) + abs(np.cos(angle_radian) * old_width) height = abs(np.sin(angle_radian) * old_width) + abs(np.cos(angle_radian) * old_height) image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) rot_mat[1, 2] += (width - old_width) / 2 rot_mat[0, 2] += (height - old_height) / 2 return cv2.warpAffine(image, rot_mat, (int(round(height)), int(round(width))), borderValue=background) image_0 = cv2.imread(image_file) grayscale = cv2.cvtColor(image_0, cv2.COLOR_BGR2GRAY) resize = cv2.resize(grayscale, None, fx=0.8, fy=0.8) angle = determine_skew(resize) rotated = ndimage.rotate(resize, angle, reshape=True) rotated2 = ndimage.rotate(rotated, -0.5, reshape=True) success, encoded_image = cv2.imencode('.jpg', rotated2) # cv2.imshow("", rotated2) # cv2.waitKey(0) content = encoded_image.tobytes() image = vision.Image(content=content) response = client.text_detection(image=image) document = response.full_text_annotation bounds = [] for page in document.pages: for block in page.blocks: for paragraph in block.paragraphs: for word in paragraph.words: for symbol in word.symbols: x = symbol.bounding_box.vertices[0].x y = symbol.bounding_box.vertices[0].y … -
django module installed by python pip not found for apache mod wsgi python version
my apache log shows AH00163: Apache/2.4.52 (Ubuntu) OpenSSL/3.0.2 mod_wsgi/4.9.0 Python/3.10 configured and when i start python3 repl Python 3.10.6 (main, Aug 10 2022, 11:40:04) [GCC 11.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django_tgbot >>> django_tgbot <module 'django_tgbot' from '/home/admin/.local/lib/python3.10/site-packages/django_tgbot/__init__.py'> but the python3.10 started by mod wsgi cannot load the module in django [Mon Sep 26 20:47:58.471013 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] mod_wsgi (pid=294801): Failed to exec Python script file '/var/www/django/tgweb/tgweb/wsgi.py'. [Mon Sep 26 20:47:58.471122 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] mod_wsgi (pid=294801): Exception occurred processing WSGI script '/var/www/django/tgweb/tgweb/wsgi.py'. [Mon Sep 26 20:47:58.473468 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] Traceback (most recent call last): [Mon Sep 26 20:47:58.473563 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] File "/var/www/django/tgweb/tgweb/wsgi.py", line 19, in <module> [Mon Sep 26 20:47:58.473579 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] application = get_wsgi_application() [Mon Sep 26 20:47:58.473599 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] File "/usr/local/lib/python3.10/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Sep 26 20:47:58.473610 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] django.setup(set_prefix=False) [Mon Sep 26 20:47:58.473628 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] File "/usr/local/lib/python3.10/dist-packages/django/__init__.py", line 24, in setup [Mon Sep 26 20:47:58.473639 2022] [wsgi:error] [pid 294801] [client 62.227.246.99:41236] apps.populate(settings.INSTALLED_APPS) [Mon Sep 26 20:47:58.473656 2022] [wsgi:error] … -
Inherit model or make separate ones?
I have a model called "Phones" which has: screen size, RAM, etc. I have another one called "Laptops" which has: screen size, RAM, and Keyboard (QWERTZ, QWERTY, etc.). I could make a main model with basic fields like Name and Price. I want to just select a "Laptop" or a "Phone", without having unnecessary fields (e.g.: keyboard type for phones, or rear camera for laptops). Should I make all fields and leave unneeded ones empty (would look silly to have "RAM" and "Keyboard type" and "Rear camera mpx" for a Mug)? Or should I make separate models for each? But then how could I combine query results (search for "Xiaomi" returning from the different models like phones, laptops, bikes, vacuum cleaners, etc.)? -
Why are my requests forbidden in production but works fine on my local server?
I deployed my website on railway.app just 2 days ago, but earlier today I noticed I can't submit any forms to the server. I just get a 403 error (Forbidden). But I can submit forms when it is running on my local host (127.0.0.1). I am using Django and this is how my html looks like: <form id="subscribe"> {% csrf_token %} <div class="mb-3"> <input id="email" name="email" type="email" placeholder="Enter E-mail"> </div> <input type="submit" value="subscribe"> </form> I submit the form using (pure) JavaScript, I do this so the page doesn't reload. Here's my JavaScript code: document.querySelector("#subscribe").onsubmit = event => { event.preventDefault(); subscribe(); } function subscribe() { if (document.querySelector("#email").value === "") { return false; } else { const email = document.querySelector("#email").value; } const aj = new XMLHttpRequest; const csrfToken = document.querySelector("input[name='csrfmiddlewaretoken']").value; aj.onreadystatechange = () => { if (aj.readyState === 4) { if (aj.status === 409) { // Do something console.log("Conflict"); } else if (aj.status === 200) { // Do something console.log("Success") } else { // Do something console.log(`${aj.status} error occurred!`); } } } data = JSON.stringify({ email: email }); aj.open("POST", "/subscribe", true); aj.setRequestHeader("Data-type", "json"); aj.setRequestHeader("Content-type", "application/json"); aj.setRequestHeader("X-CSRFToken", csrfToken); aj.send(data); } I do not think it is necessary for me to share my code … -
Django How to see the session data insted of the object reference
Im trying to start using session in django, Im trying to see the data in my session but im just getting the object reference not the data console: <cart.cart.Cart object at 0x7f6994753160> views.py def cart_view(request): cart = Cart(request) print(cart) if request.user.is_authenticated: return render(request, 'cart/cart_page.html') else: return redirect('account:login') cart.py class Cart: def __init__(self, request): self.session = request.session cart = self.session.get('cart') if not cart : cart = self.session['cart'] = {} #cria a sessão cart self.product = cart -
function print doesn't work in skulpt.min.js on django
I try to use skulpt in my django project i'm testing juste the instruction : print("hello") like this: <script src="{% static 'js/skulpt.min.js' %}" type="text/javascript"></script> <script src="{% static 'js/skulpt-stdlib.js' %}" type="text/javascript"></script> function runit(prog) { // var prog = document.getElementById("yourcode").value; // var mypre = document.getElementById("output"); // mypre.innerHTML = ''; prog = prog; prog = "print('hello')"; Sk.canvas = "mycanvas"; Sk.pre = "output"; Sk.configure({ output: outf, read: builtinRead, __future__: Sk.python3 }); try { var mypre = document.getElementById("output"); mypre.innerHTML = ""; eval(Sk.importMainWithBody("<stdin>", false, prog)); } catch (e) { // alert(e.toString()) var mypre = document.getElementById("output"); mypre.innerHTML = mypre.innerHTML + e.toString(); } } function outf(text) { var mypre = document.getElementById("output"); var bonneReponse = document.getElementById("trace_output").value.replace("&nbsp", " "); mypre.innerHTML = mypre.innerHTML + text; } } function builtinRead(x) { if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined) throw "File not found: '" + x + "'"; return Sk.builtinFiles["files"][x]; } ExternalError: TypeError: Cannot read properties of undefined (reading 'write') on line 1 when i switch to python 2 using skulpt.js instead of skulpt.min.js it works -
Live search in Django admin?
How would I implement live search in Django's admin panel? I want the change_list page to function with Ajax and return the search results without refreshing the page. Does Django expose any ModelAdmin methods that can implement such behaviour? I.e. change the response type from a regular HttpResponse to JsonResponse? -
DRF post nested object
I`m trying to post this json object { "name": "Country Name", "description": "Description here...", "generalInfo": { "capital": "Capital", "population": "Population", "highestPeak": "HighestPeak", "area": "Area" }, "timelineData": [ { "name": "Name 1", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" }, { "name": "Name 2", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" }, { "name": "Name 3", "ruler": "Ruler", "dateStart": "dateStart", "dateEnd": "dateEnd", "description": "description" } ] } But I`m receiving this error ValueError at /countries/ Cannot assign "OrderedDict([('capital', 'Capital'), ('population', 'Population'), ('highestPeak', 'HighestPeak'), ('area', 'Area')])": "Country.generalInfo" must be a "GeneralInfo" instance. Request Method: POST Request URL: http://127.0.0.1:8000/countries/ Django Version: 4.0.3 Here are my models.py: class GeneralInfo(models.Model): capital = models.CharField(max_length=200) population = models.CharField(max_length=200) highestPeak = models.CharField(max_length=200) area = models.CharField(max_length=200) class TimelineData(models.Model): name = models.CharField(max_length=200) ruler = models.CharField(max_length=200) dateStart = models.CharField(max_length=200) dateEnd = models.CharField(max_length=200) description = models.TextField(default='Description here...') class Country(models.Model): name = models.CharField(max_length=200, db_index=True) description = models.TextField(default='Description here...') generalInfo = models.ForeignKey(GeneralInfo, on_delete=models.CASCADE) timelineData = models.ManyToManyField(TimelineData) I have also overridden the create method for CountrySerializer and here are my serializers.py: class TimelineDataSerializer(serializers.ModelSerializer): class Meta: model = TimelineData fields= '__all__' class GeneralInfoSerializer(serializers.ModelSerializer): class Meta: model= GeneralInfo fields = '__all__' class CountrySerializer(serializers.ModelSerializer): timelineData = TimelineDataSerializer(many=True) generalInfo = GeneralInfoSerializer() class Meta: model= Country fields = … -
How to indexes ImageField in django-elasticsearch-dsl
Рello everyone! I am writing a site on Django. I am making a search system using django-elasticsearch-dsl. And I have a problem when I need to index an ImageField field in the BookDocument class in order to display a book image on the book search page Here is my Book model: books/models.py class Book(models.Model): title = models.CharField(max_length=120, default=' ', verbose_name='Назва') description = models.TextField(verbose_name='Опис') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категорія') date_at = models.DateField(auto_now_add=True, verbose_name='Дата створення') image = models.ImageField(upload_to='photos/%Y/%m/%d/') authors = models.ManyToManyField(Author, verbose_name='Автори') content = models.FileField(upload_to='contents/%Y/%m/%d/', blank=True) price = models.IntegerField(verbose_name='Ціна', default='0') Here is my BookDocument class: search/documents.py @registry.register_document class BookDocument(Document): image = FileField() class Index: name = 'books' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Book fields = [ 'id', 'title', 'description', ] but the images are not displayed on the search page, and since there is no ImageField field in django-elasticsearch-dsl, and only this file is suitable for storing file data, I do not know how to change this behavior Perhaps someone has encountered such a problem and knows how to make it work -
Pytest keep missing return line in the same function that has been ran multiple time
I'm doing a project in django and I have 2 serializer like this: parent_serializer.py class ParentSerializer(serializer.Serializers): action = ChildSerializer() child_serializer.py class ChildSerializer(serializer.Serializers): ... def validate(self, attrs): ... **return attrs** There is an if statement in the validate function and i wrote all the tests needed for the if statement, but pytest coverage keep saying that it missed the return statement line (return attrs), which imo, supposed to run in every test case. I did try everything possible but nothing works. Please help me on that one -
Unable to get through .is_valid() validation of Django for POST request for Images field
The POST request for images does not get validated on my form, when i created a new form it worked fine and was able to save the images. but going back to same old form i tried making the body part similar to the old one but got the same message even tried to check the console for form.errors but couldn't find anything.Still trying to figure out what is it that's missing in input as per the console log ValidationError[This field is required]. console log for the POST Request made View.py function used to validate and get post models.py form.py ModelForm main layout html template <!DOCTYPE html> <html lang="en"> <head> <!-- <title>Encyclopedia</title> --> <title>{% block title %} {% endblock %}</title> <link rel="stylesheet" href="..\..\static\mywikiapp\style.css"> {% block head %} {% endblock %} </head> <body> <div class="main"> <div class="leftpart"> <h2 id="leftheading">Wiki</h2> <div class="search_container_confinement"> <form> <div class="searchcontainer"> <input type="text" name="q" placeholder="Search Encyclopedia"> </div> </form> </div> <div class="listcontainer"> <ul id="left_col_li"> <li><a href="{% url 'mywikiapp:index' %}">Home</a></li> <li><a href="{% url 'mywikiapp:create_new' %}">Create New Page</a></li> <li><a href="{% url 'mywikiapp:add_images' %}">Upload Images</a></li> <li><a href="">Random Page</a></li> </ul> </div> <div class="navbar"> <div> {% block navbar %}{% endblock %} </div> </div> </div> <div class="rightpart"> <!-- <h1>All Pages</h1> <div> <ul> <li>Css</li> <li>Django</li> <li>Git</li> … -
Extracting case insensitive words from a list in django
I'm extracting values from a csv file and storing these in a list. The problem I have is that unless there is an exact match the elements/strings don't get extracted. How would I go about a case insensitive list search in Django/Python? def csv_upload_view(request): print('file is being uploaded') if request.method == 'POST': csv_file_name = request.FILES.get('file') csv_file = request.FILES.get('file') obj = CSV.objects.create(file_name=csv_file) result = [] with open(obj.file_name.path, 'r') as f: f.readline() reader = csv.reader(f) #reader.__next__() for row in reader: data = str(row).strip().split(',') result.append(data) transaction_id = data[1] product = data[2] quantity = data[3] customer = data[4] date = parse_date(data[5]) try: product_obj = Product.objects.get(name__iexact=product) except Product.DoesNotExist: product_obj = None print(product_obj) return HttpResponse() Edit: the original code that for some reason doesn't work for me contained the following iteration: for row in reader: data = "".join(row) data = data.split(';') data.pop() which allows to work with extracted string elements per row. The way I adopted the code storing the elements in a list (results=[]) makes it impossible to access the elements via the product models with Django. The above mentioned data extraction iteration was from a Macbook while I'm working with a Windows 11 (wsl2 Ubuntu2204), is this the reason that the Excel data needs … -
Django 3.2.3 Pagination isn't working properly
I have a Class Based View who isn't working properly (duplicating objects and deleting some) Tested it in shell from django.core.paginator import Paginator from report.models import Grade, Exam f = Exam.objects.all().filter(id=7)[0].full_mark all = Grade.objects.all().filter(exam_id=7, value__gte=(f*0.95)).order_by('-value') p = Paginator(all, 12) for i in p.page(1).object_list: ... print(i.id) 2826 2617 2591 2912 2796 2865 2408 2501 2466 2681 2616 2563 for i in p.page(2).object_list: ... print(i.id) 2558 2466 2563 2920 2681 2824 2498 2854 2546 2606 2598 2614 -
How do I use a DB procedure from the django ORM?
For example, in MySQL, I would write: SELECT id, my_calc(id, '2022-09-26') as calculated FROM items; How do I tell the ORM to use this DB procedure and pass the parameters? Would I have to define a Func? Items.objects.annotate(calculated=...) -
No Post Data - Testing Django View with AJAX Request
I'm currently testing my Django application in order to add some CI/CD to it. However, most of my views contain an AJAX section for requests sent by the frontend. I saw that for testing those I can only just do something like this: response: HttpResponseBase = self.client.post( path=self.my_page_url, content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest', data={ 'id': '123456', 'operation': "Fill Details" } ) The XMLHttpRequest is making most of the magic here (I think), by simulating the headers that an AJAX request would have. However, in my view I have a section where I do: request.POST['operation'], but this seems to fail during tests since apparently no data is passed through the POST attribute. Here's the code of the view that I'm using right now: MyView(request): is_ajax: bool = request.headers.get('x-requested-with') == 'XMLHttpRequest' if is_ajax: operation = request.POST['operation'] I checked and my data is being passed in request.body. I could include an or statement, but it would be ideal if the code for views was not modified because of tests. Is there any way to get the client.post method to pass the data through the POST attribute? -
Sending a message to a specific group in Django Channels
I would like to connect every user who visits a particular page. Let's call this the, 'Waiting Room' to a websocket. When the user connects to a websocket they are subscribed to a group. The group is named after the user's user_id. So User1 and User would connect to the websocket and be subscribed to the groups; 1 and 2 respectively. After the user is connected, I trigger a method that sends a user_id the user has been matched with and room_id to my server. Assuming User1 is matched with User2. User1 would send User2 and room_id to the server. I then send a message back to the group associated with the user_id received. Meaning I send a message from User1's websocket to User2's client. However, when I implement this logic no messages are received by User2. This is what I have in consumers.py: class PracticeConsumer(AsyncConsumer): username_id = None async def websocket_connect(self, event): username = self.scope['user'] username_id = str(await self.get_user(username)) group_name = username_id await self.channel_layer.group_add( '{}'.format(group_name), self.channel_name ) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): received = event["text"] invite_data = received.split() matched_user = invite_data[0] username = invite_data[2] user_id = str(await self.get_user(matched_user)) my_response = { "message": "!!!!the websocket is … -
How to set priority in CELERYBEAT_SCHEDULE config?
In my Django app, I am trying to set the priority value to 6 for a Celery beat task, but the below doesn't work. What's the right way to set this value? I have other tasks in this config and want to set different priority values. CELERYBEAT_SCHEDULE = { 'some_task_name': { 'task': 'app_name.tasks.some_task_name', 'schedule': crontab(hour=18, minute=30), 'options': {'priority': 6} } } -
combining two arrays in Django
I'm working on a web that displays posts (like twitter). In Django views.py I wrote a code that makes two arrays and assigned the arrays to be used in the HTML template. views.py: def arrays(request): allposts = posts.objects.all() m = ['empty', 'like', 'unlike', 'like', 'unlike'] aa = [0, 1, 2, 3, 4] return render(request, "network/index.html" ,{'allposts': allposts, 'm':m, 'aa':aa}) the (m) array represents whether each post is liked or not(each object in the array has the arrangement which is equal to the post id) while the (aa) represents the id of each post in the database in index.html I want to show 'like' or 'unlike' for each post according to the arrangement in the array. in index.html {% for post in allposts %} <div> {% for object in aa %} {% if object == post.id %} <p>{{m.object}}</p> {% endif %} {% endfor %} </div> {%endfor %} but the problem is that I can't match the aa array and the m array in the HTML template but I can display {{m.1}} instead of {{m.object}}. so how can I match those two arrays? -
TypeError Error during template rendering
I'm facing this error when I add ForeignKeys in my Order table enter image description here Here are my tables enter image description here But when I remove the those ForeignKeys it works fine without giving an error... enter image description here enter image description here ...But I also can't access other tables enter image description here -
Getting None instead of Value from HTML form (Django)
Here below my HTML-template <form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data"> {% csrf_token %} <h2> {{ result }} </h2> <div class="d-flex justify-content-center"> <button type="submit" class="btn btn-primary">Show</button> </div> </form> my View.py def show_result(request): if request.method == "POST": result = request.POST.get('test') return HttpResponse(result) By pressing the button 'Show' I got None instead of {{ result }} value. So, how I can get a Value inside curly brackets? Thanks a lot for any help. -
Unable to POST data with the Django REST Framework : Not Found
I'm trying to figure out why the Django REST Framework throws a 404 Not Found when I POST data with the code below, because when I load the browsable API with the URL it correctly displays the object list with the HTML form to POST data. The Django project that serve the API run in a Docker container as well as the client, but in a separate Docker host. How could I fix the issue ? Server Console logs django-1 | Not Found: /api/strategy/target/ django-1 | [26/Sep/2022 14:27:05] "POST /api/strategy/target/ HTTP/1.1" 404 23 project/project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("api/strategy/", include("strategy.urls")), ] strategy/urls.py from django.urls import path, include from rest_framework import routers from strategy.api.views import TargetViewSet router = routers.DefaultRouter() router.register("target", TargetViewSet, basename="targets-list") urlpatterns = [ path('', include(router.urls)), ] strategy/views.py from rest_framework import viewsets from strategy.api.serializers import TargetSerializer from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAdminUser # Create new model @permission_classes([IsAdminUser]) class TargetViewSet(viewsets.ModelViewSet): serializer_class = TargetSerializer queryset = Target.objects.all() Client res = requests.post("http://1.2.3.4:8001/api/strategy/target/", data=data, headers={'Authorization': 'Bearer {0}'.format(token)} ) -
Django Integrity Error at /accounts/login/ 1364, "Field 'id' doesn't have a default value"
I get the Django error when clicking on log in. Unfortunately I don't know which table is causing the problem. My complete error: IntegrityError at /accounts/login/ (1364, "Field 'id' doesn't have a default value") Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 4.0.6 Exception Type: IntegrityError Exception Value: (1364, "Field 'id' doesn't have a default value") Exception Location: c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\connections.py, line 254, in query Python Executable: c:\xampp\htdocs\django\ksfexpert\env\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\xampp\htdocs\django\ksfexpert\src', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\kit\AppData\Local\Programs\Python\Python310', 'c:\xampp\htdocs\django\ksfexpert\env', 'c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages'] Server time: Mon, 26 Sep 2022 14:46:52 +0000 Traceback Switch to copy-and-paste view c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\db\backends\utils.py, line 89, in _execute return self.cursor.execute(sql, params) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\db\backends\mysql\base.py, line 75, in execute return self.cursor.execute(query, args) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\cursors.py, line 206, in execute res = self._query(query) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\cursors.py, line 319, in _query db.query(q) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\connections.py, line 254, in query _mysql.connection.query(self, query) … Local vars The above exception ((1364, "Field 'id' doesn't have a default value")) was the direct cause of the following exception: c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\views\generic\base.py, line 84, in view return self.dispatch(request, *args, **kwargs) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\utils\decorators.py, line … -
How İs it possible apply filtering to the imported data while using django-import-export package
By applying Form (not using Admin Panel) it is possible for users to import their data in xlsx format to the models practically. I have two models Task & Item. Each Task object has many Item objects in it. When it is intended to import a data file which includes mixed data, namely more than one tasks created by different user with their items, Django-import-export utility import all of them. But in some cases it is required to limit the import process by allowing the tasks which are created by the user itself and not whole task data. Can I overcome this issue by appling filter to data? def importData(request,pk): if request.method == 'POST': #query = Item.objects.filter(task_id = pk) item_resource = ItemResource() dataset = Dataset() new_items = request.FILES['importData'] imported_data = dataset.load(new_items.read(), format='xlsx') result = item_resource.import_data(dataset, dry_run=True) if not result.has_errors(): item_resource.import_data(dataset, dry_run=False) converted = str(pk) return HttpResponseRedirect('http://127.0.0.1:8000/'+'checklist/task/'+ converted + '/') else: return HttpResponse('Your Data is not Proper ! Please Try Again...') return render(request, 'checklist/import.html')enter code here class Task(models.Model): user = models.ForeignKey(User, verbose_name="Kullanıcı", on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(verbose_name="Kontrol Listesi Başlığı", max_length=200) description = models.TextField(verbose_name="Açıklama", null=True, blank=True) complete = models.BooleanField(verbose_name="Tamamlandı mı?", default=False) created = models.DateTimeField(auto_now_add=True, verbose_name='Kayıt Tarihi') update_date = models.DateTimeField(auto_now=True, verbose_name='Son Güncelleme') …