Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stream a file in a request?
We have a react application communicating with a django backend. Whenever the react application wants to upload a file to the backend, we send a form request with one field being the handle of the file being upload. The field is received on the Django side as an InMemoryUploadedFile, which is an object with some chunks, which can be processed for example like this: def save_uploaded_file(uploaded_file, handle): """ Saves the uploaded file using the given file handle. We walk the chunks to avoid reading the whole file in memory """ for chunk in uploaded_file.chunks(): handle.write(chunk) handle.flush() logger.debug(f'Saved file {uploaded_file.name} with length {uploaded_file.size}') Now, I am creating some testing framework using requests to drive our API. I am trying to emulate this mechanism, but strangely enough, requests insists on reading from the open handle before sending the request. I am doing: requests.post(url, data, headers=headers, **kwargs) with: data = {'content': open('myfile', 'rb'), ...} Note that I am not reading from the file, I am just opening it. But requests insists on reading from it, and sends the data embedded, which has several problems: it can be huge by being binary data, it corrupts the request it is not what my application expects … -
Create custom models from html in Django
I want from a html page create a custom model from existing models. For example I have a generic model called Object : Model Object: Name Description Date When a user create a new Object, I want him to be able to choose fields from a list to add them in the new Object. In the list I have for example : List: - Temperature - Humidity And he can add as many fields as he wants (maybe add user custom fields ?). If he creates a new Object with Temperature but not with Humidity the object should be : Model Object: Name Description Date Temperature Is there a way to do this with Django ? Thank you for your help. -
When using Django the save() function does not work using model forms
Im trying to learn Django. I believe my form is working properly but the data is not saved into the database. This is my model: from django.db import models # Create your models here. class parameters(models.Model): interval_1 = models.PositiveIntegerField() interval_2 = models.PositiveIntegerField() interval_3 = models.PositiveIntegerField() interval_4 = models.PositiveIntegerField() interval_5 = models.PositiveIntegerField() interval_6 = models.PositiveIntegerField() cost_1 = models.DecimalField(max_digits=19, decimal_places=2) cost_2 = models.DecimalField(max_digits=19, decimal_places=2) cost_3 = models.DecimalField(max_digits=19, decimal_places=2) cost_4 = models.DecimalField(max_digits=19, decimal_places=2) cost_5 = models.DecimalField(max_digits=19, decimal_places=2) cost_6 = models.DecimalField(max_digits=19, decimal_places=2) This is my form: from django import forms from django.forms import ModelForm from .models import parameters # Create your forms here. class set_parameters(forms.ModelForm): class Meta: model = parameters fields = "__all__" This is my view: from django.shortcuts import render # Create your views here. from .models import parameters from .forms import set_parameters def frequence_create_view(request): form = set_parameters(request.POST or None) if form.is_valid(): form.save() print(request) print(form) form = set_parameters() else: print (form.errors) context = { 'form': form } return render(request, 'settings/settings.html', context) These are my templates: <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> {% block frequence %} {% endblock %} {% block cost %} {% endblock %} </body> </html> {% extends 'base.html' %} {% block frequence %} <form action='.' method='POST'> {% csrf_token %} … -
How to remove from manytomany field
I'm Django beginner. How do I remove a field from manytomany field. Implementing my code I got 'QuerySet' object has no attribute 'likes' class Image(models.Model): imageuploader_profile=models.ForeignKey(settings.AUTH_USER_MODEL) upload_image=models.ImageField() likes=models.ManyToManyField(User, related_name='image_likes') def block_users(request, id) user = get_object_or_404(User, id=id) images = Image objects.filter(imageuploader_profile=user) if images.likes.filter(id=request.user.id).exists(): images.likes.remove(request.user) -
How to split rows in excel with Python?
If you need to split rows in excel you can use this python code. This code's usage very easy. You need this libraries on below. xlrd --> https://pypi.org/project/xlrd/ xlsxwriter --> https://pypi.org/project/XlsxWriter/ uuid --> https://pypi.org/project/uuid/ ( If you want to generate random string ) import xlrd import xlsxwriter import uuid uniqueKeys = { } file_location = r'file-location' # for mac wb = xlrd.open_workbook(file_location) sh = wb.sheet_by_index(0) for key in uniqueKeys: inputKey = key randomNumber = uuid.uuid4() fileName = ''+str(randomNumber)+'-'+str(inputKey)+'.xlsx' workbook = xlsxwriter.Workbook('file-location'+fileName) worksheet = workbook.add_worksheet() worksheet.write(0, 0, 'Header 0') worksheet.write(0, 1, 'Header 1') worksheet.write(0, 2, 'Header 2') worksheet.write(0, 3, 'Header 2') workSheetRow = 1 for col in sh.get_rows(): col0 = int(col[0].value) col1 = str(col[1].value).strip(".0") col2 = str(col[2].value) col3 = float(col[3].value) if sellerIds == inputSeller: worksheet.write(workSheetRow, 0, col0) worksheet.write(workSheetRow, 1, col1) worksheet.write(workSheetRow, 2, col2) worksheet.write(workSheetRow, 3, col3) workSheetRow = workSheetRow + 1 workbook.close() If you want to visit github Repository you can click this url --> https://github.com/emreatadl/splitexcel/blob/master/split-row-excel.py -
why isn't it being displayed properly?
I'm currently developing an online store where people can add products to carts. In my home html file I want to display the button 'Add to cart' if the product is not added to cart, and 'Remove from cart' if the product is added. But it is not working properly. I'm getting 'Remove from cart' button now. My index.html: {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="container-md"> <div class="row"> {% for product in products %} <div class="col"> <div class="card-deck" style="width: 18rem;"> <img src="{{ product.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <a class="card-title" href="{% url 'detail-view' product.slug %}">{{ product.name }}</a> <p class="card-text">${{ product.price }}</p> {% if product in Cart.products.all %} <a href="{% url 'add-to-cart' product.slug %}" class="btn btn-primary">Add to Cart</a> {% else %} <a href="{% url 'add-to-cart' product.slug %}" class="btn btn-primary">Remove from Cart</a> {% endif %} </div> </div> </div> {% endfor %} </div> </div> {% endblock %} My cart's views.py: from django.shortcuts import render, redirect, HttpResponseRedirect from products.models import Product from .models import Cart from django.contrib import messages from django.urls import reverse def cart(request): cart = Cart.objects.all()[0] context = {"cart":cart} template = 'shopping_cart/cart.html' return render(request, template, context) def add_to_cart(request, slug): cart = Cart.objects.all()[0] try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: … -
How to get value of an attribute from django model
I have a list of products: product_list = ['A', 'B', 'C', 'D', 'E', 'F'] and I want to know the total quantity of these product that I have in my AllotmentDocket Model Models.py class AllotmentDocket(models.Model): transaction_no = models.IntegerField(default=0, blank=True, null=True) product1 = models.CharField(max_length=500, default=0, blank=True, null=True) product1_quantity = models.IntegerField(default=0, blank=True, null=True) product2 = models.CharField(max_length=500, default=0, blank=True, null=True) product2_quantity = models.IntegerField(default=0, blank=True, null=True) product3 = models.CharField(max_length=500, default=0, blank=True, null=True) product3_quantity = models.IntegerField(default=0, blank=True, null=True) product4 = models.CharField(max_length=500, default=0, blank=True, null=True) product4_quantity = models.IntegerField(default=0, blank=True, null=True) product5 = models.CharField(max_length=500, default=0, blank=True, null=True) product5_quantity = models.IntegerField(default=0, blank=True, null=True) product6 = models.CharField(max_length=500, default=0, blank=True, null=True) product6_quantity = models.IntegerField(default=0, blank=True, null=True) product7 = models.CharField(max_length=500, default=0, blank=True, null=True) product7_quantity = models.IntegerField(default=0, blank=True, null=True) product8 = models.CharField(max_length=500, default=0, blank=True, null=True) product8_quantity = models.IntegerField(default=0, blank=True, null=True) How can I do that ? -
Field 'id' expected a number but got <built-in function id>
i want to delete and edit notes in my django app, but i am struck on this error for long Error : "TypeError at /delete/1/ Field 'id' expected a number but got ." models.py from django.db import models from django.utils import timezone # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name = ("Category") verbose_name_plural = ("Categories") def __str__(self): return self.name class ToDoList(models.Model): title = models.CharField(max_length=200) content = models.CharField(max_length=500) created_on = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) category = models.ForeignKey(Category,on_delete=models.DO_NOTHING,default="general") class Meta: ordering = ["-created_on"] def __str__(self): return self.title class Note(models.Model): text = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add = True) class Meta: verbose_name = ("Note") def __str__(self): return self.text my todoapp/urls.py urls.py from django.contrib import admin from django.urls import path, include from todolist.views import index,note,del_note,edit_note urlpatterns = [ path('admin/', admin.site.urls), path('',index,name = 'ToDoList'), #path('',note,name = 'Note'), path('note/', note, name='Note'), path('delete/<note_id>/',del_note ,name = 'del_note'), path('edit/<note_id>/',edit_note,name='edit_note'), ] my todolist/views views.py def del_note(request, note_id): x = Note.objects.get(id = id) print (x) // tried for degugging x.delete() return redirect("/") def edit_note(request, note_id): x = Note.objects.get( id = id) print (x) return redirect("/") here is my html note.html <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">ToDo/Notes</a> </div> <ul class="nav navbar-nav"> <li><a href="{% … -
"module 'django' has no attribute 'VERSION'" error when setting up PostgreSQL for Saleor
I am using Saleor, a Django ecommerce backend template, and am trying to get it set up as given here. I downloaded all the packages at the top, but am struggling to get Postgres working. Originally, I downloaded Postgres from EnterpriseDB, and when trying to "createuser" I would get a "postgres psql: fatal: could not find own program executable" error. Then, I uninstalled postgres because it seemed like the trouble may be coming from a weird file path, and downloaded it again, this time using homebrew. I then seemed to have overlapping files, and Postgres was now, for some reason, downloaded to my Applications folder instead of /Library. At this point, when I tried to "createuser", I got "permission denied" and briefly spent some time trying to do it with root access, to no avail. So, I clean uninstalled both versions of Postgres on my computer, and downloaded it via homebrew again. Then I went into the PSQL shell and physically typed out SQL commands to create both the 'saleor' user and DB, which is now done. I am now downloading PgAdmin and will connect it to the Postgres downloaded via Homebrew to manage these users/DBs. Then, when trying to … -
TypeError: expected string or bytes-like object - Django
I've deployed my Django application to DigitalOcean server via nginx, gunicorn. Today I wanted to add the script models.DateTimeField(auto_now_add=True) for saving the date when message from user was sent, but during migration (after pulling the entire repository from github on ubuntu server) I'm getting following error. And I guess the problem is in migration files, but don't know how can I manipulate them on server and how to do it safely, without losing any data. Error: Applying pragmatechapp.0004_auto_20200328_1036...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards field, File "/home/kerimov/pragmatechproject/env/lib/python3.5/site-packages/django/db/backends/base/schema.py", line … -
How to update change history for a User object from backend view function instead of Django admin panel?
I understood that the change history for a specific object gets updated when we do something on django admin panel. Like for a user, if we add or remove the groups from admin panel, it will be part of change history for that particular user object. I have a case where I need to upload a CSV file containing a list of users and their Titles. Based on these titles, I need to add specific groups to the user. I was able to achieve that adding and removing of groups for the user. The issue here is that I don't see the change history for the user object getting updated when I assign groups to the user from backend instead of admin panel. Is there any thing that would be helpful for me to achieve this? I have gone through this Tying in to Django Admin's Model History . But it's adding a record in Log Entries and not in the change history of the object. Is there any place I can look at for the change history of objects like any table in database where in I can create a new record after every modification of the user etc? -
python to get the root url on which the exe is running
i want to get the root url on which server is running after i started the server through python script i have started my exe with this code import os os.system(f'start cmd /k {path of the exe}') it starts the server giving this message enter image description here i need to get 'http://127.0.0.1:8088/' from this message -
Django HTML form not populating variables
I am trying to get the input of the forms by just using requests and no actual django form(I do not need to store this data in a database.) So I am trying to use request.GET.get() method, but so far I have had no luck with it. I am pretty sure that it is something wrong with my HTML, but I could be wrong. -
Virtualenvwrapper : While trying to make a new virtual environment, Fatal error in launcher : Unable to create process
Here is the complete error : D:\Django>mkvirtualenv test1 Fatal error in launcher: Unable to create process using '"c:\program files\python38\python.exe" "C:\Program Files\Python38\Scripts\virtualenv.exe" test1 --prompt="(test1) "' The system cannot find the path specified. The system cannot find the path specified. The system cannot find the path specified. Any help is appreciated. Thanks. -
Runserver python django error when using python manage.py runserver
i am using Django/python as a framework , when i started to open my server on cmd by using code python manage.py runserver, this bug happened. -
expected str, bytes or os.PathLike object, not InMemoryUploadedFile while sending the file from postman in django drf
I am trying to create app with rest api and i want to upload a file using postman i have tried with the python it runs without any error but when i try to run in django it shows this error expected str, bytes or os.PathLike object, not InMemoryUploadedFile -
how to decode the image/gif url by using in python
How to decode base64 in image url formate.when i print decoded data it show an output like GIF89a � ���!� , D ; ,how to solve this issue code from base64 import b64decode data_uri = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" header, encoded = data_uri.split(",", 1) data = b64decode(encoded) print data output GIF89a � ���!� , D ; -
Wagtail Stream Image Ignoring HTML File
I've set up a stream file and all the blocks work except image. I know I must have overlooked something obvious. The image is displayed. It just ignores the html. In my models.py, I have: content = StreamField( [ ("title_and_text", blocks.TitleTextBlock()), ("full_rich_text", blocks.RichTextBlock()), ("simple_rich_text", blocks.LimitedRichTextBlock()), ("image_float_left", blocks.ImageChooserBlock()), ], null=True, blank=True, ) In my page html, I have: {% for block in page.content %} {% include_block block %} {% endfor %} All the other blocks display correctly. In my blocks.py, I have: class ImageFloatLeftBlock(ImageChooserBlock): """Float an image to the left""" class Meta: template = "streams/image_float_left_block.html" icon = "doc-full" label = "Float Image Left" The html file is ignored. I put and h1 in it just to be sure. The image is being displayed. I assume it isn't looking at the streams/image_float_left_block.html file. It does work for the other fields that are set up the same way. For example, this one works: class TitleTextBlock(blocks.StructBlock): """Title and text and nothing else.""" title = blocks.CharBlock(required=True, help_text="The heading for the block") text = blocks.TextBlock(required=True, help_text="The body of the block") class Meta: template = "streams/title_text_block.html" icon = "edit" label = "Title & Text" I suspect it's the parent class in the invocation: class ImageFloatLeftBlock(ImageChooserBlock): I can't … -
How to get only first "N" elements from postgres through views in Django using jinja
I am using Django and postgres. My views.py looks like: def home(request): title = Scrap.objects return render(request, 'index.html', {'headlines': headlines}) My index.html looks like: <div class="content" style="background:white; color: white; font-family: Verdana;font-weight: 5;text-align: center;"> {% for headline in headlines.all reversed %} <a href="{{ headline.url }}" target="_blank" style="color:black; font-size: medium;" />{{ headline.headlines }}</a> <hr style="border-bottom: dotted 1px #000" /> {% endfor %} </div> With the above code I am getting all the rows from the databse. How can I get only "N" rows? I have tried: {% for headline in headlines.all[:5] reversed %} but it throws an error. -
Can you someone explain 'query_string' vs 'headers' in this situation
Can you someone explain 'query_string' vs 'headers' in this situation. This is from a consumers.py file from a Django project. query_string = parse_qs(scope['query_string']) query_string = parse_qs(scope['headers']) Also how do I know how I am passing a token when trying to connect a websocket. -
OperationalError at / could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1)
error while deploying on heroku, I watched many videos and blogs but cannot find solution Its working well on the local server but problem only while hosting the app trying to fix this bug from a long time.I would be thankful for help' thanks in advance I spent 5 hours trying to debug this code settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Doc_Help.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates'), os.path.join(BASE_DIR,'register'), os.path.join(BASE_DIR,'pages')], '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', ], }, }, ] WSGI_APPLICATION = 'Doc_Help.wsgi.application' # Databas # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD':'advitya', 'HOST': 'localhost', 'PORT': '5432', } } prod_db = dj_database_url.config(conn_max_age=500,ssl_require=True) DATABASES['default'].update(prod_db) # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), … -
Django inline formset with multiple foreign keys
I have 2 models as below: models.py from django.contrib.auth.models import User #(with groups = 'admin','student','faculty') class Course (models.Model): name = models.CharField(max_length=100) class Course_Faculty (models.Model): course = models.ForeignKey(Course,on_delete=models.CASCADE) faculty = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) And my motive is to add/remove only Users with has group name 'faculty' to a course using inline formset as follows, but I got a list of all users in the result. views.py def viewCourse (request,pk): course = Course.objects.get(id=pk) FacultyFormset = inlineformset_factory(Course, Course_Faculty, fields=('faculty',)) formset = FacultyFormset(queryset=Course_Faculty.objects.filter(faculty__groups__name='faculty'), instance=course) if request.method == 'POST': formset = FacultyFormset(request.POST, instance=course) if formset.is_valid(): formset.save() return redirect('view_course', course_id=course.id) formset = FacultyFormset(instance=course) context = { 'course':course, 'formset': formset } return render(request,'myapp/courseProfile.html',context) Please suggest how to achieve. -
Partially using Vue with nginx
I'm trying to use both vue.js and Django with nginx. The issue is, that it still redirect my /subscriptions/ url to Django. Removing the '/' rule would make it work though. Is there a way to "skip" Django when the url matches 'custom'? Basically, I would like to specify which links would be used with vue, and the rest with Django. location = /custom/ { root /home/django/project/frontend/dist; index /index.html; } location / { include proxy_params; proxy_pass http://unix:/home/django/project/project.sock; } -
Django Tutorial Constant 404 error urlpattern recognition
I have searched endlessly for a solution and I can't seem to find it, even though I know this has been asked before. I am encountering a perpetual 404 error from the django tutorial. It appears to me that the 'urlpatterns' isn't recognizing another option of than admin. backend/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('test/', include('meat.urls')), path('admin/', include(admin.site.urls)), ] backend/meat/urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), ] backend/meat/views.py from django.shortcuts import render from django.http import HttpResponse def index(requests): return HttpResponse('Hello Wold') -
Question about Django InMemoryUploadedFile
When i was using Postman for API test. I found that if the file uploaded containing any Chinese character, the filename of the object InMemoryUploadedFile received server-side would be appended with an double quotation mark: ". I can not figure it out. I do not know why this happend.