Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How can i resize the svg in the html template
I just created a matplot figure from a csv in django (line graph) and rendering it to the html template and I can't modify its dimensions imgdata = io.StringIO() fig.savefig(imgdata, format='svg') imgdata.seek(0) data = imgdata.getvalue() return data data = isolate(selected_loc) return render(request, 'hello.html', {'data': data, 'locations' : list(locations)}) html template <div class="figure" style="">{{ data|safe }}</div> i tried styling the div in css .figure { width: 40%; height: 500px; } and it doesnt working only the div container expands but not the svg that just rendered enter image description here -
I get this error [assert image.thumbnail.read() == expected_content AssertionError] when testing my signals.py file
When a user inputs an image the function in signals.py is supposed generates a thumbnail of that image automatically. But when I run the test in test_signals.py to check if the thumbnail is created when the image is saved it fails on line 30: assert image.thumbnail.read() == expected_content this is the model.py file this is the signals.py file this is the test causing the error -
Revert some file/directory deletions from other Revert, Recover file and directory from Commit
I made a revert that deleted some files and directories... According to the The screenshot: The Red box shows the commit with my revert. The Blue arrow shows the position inside of my project The Green arrows shows the files that I would like to recover... I see this question, but that is recovering all, and this How do I reset or revert a file to a specific revision? shows only file. This Git revert just some files in commit is about single file. How I Could do the recovery with directory? Is it possible do this operation directly from IntelliJ? Is it possible do this operation interactively (in order to select what recover)? -
The annotation 'id' conflicts with a field on the model
In Annotate I am trying to get the count of quires for which is_healthy is True but I am getting an Error The annotation 'id' conflicts with a field on the model. Any solution to solve this? and why is this causing how can i resolve this? DeviceHealthHistory.objects.filter(**filter_data).values( id = F('id'), ).annotate( healthy_count=Count('id', filter=Q(is_healthy=True)), ) -
inconsistency between databases created with pandas and models.py in django
I am trying to generate a database in sqlite3 with pandas and so far everything is fine, it is generated as I need it, the problem is that when trying to access that database through a models created identical to the one created by pandas it breaks and django does not manages to access that database. I have the following file "output.txt" which was basically generated by a function in views.py Interface Status Protocol Description BE9 down down BE9.1 down down BE9.100 down down Lo0 up up Lo8 up up Lo30 up up Lo100 up up ***MERGE LOOPBACK 100**** Lo111 up up Configured by NETCONF Lo200 up up ***MERGE LOOPBACK 200**** Gi0/0/0/0 down down Gi0/0/0/1 down down Gi0/0/0/2 admin-down admin-down Gi0/0/0/3 admin-down admin-down Gi0/0/0/4 admin-down admin-down Gi0/0/0/5 admin-down admin-down Gi0/0/0/6 admin-down admin-down and through that same function there is a fragment that takes that info and transfers it to the database: #Converting txt to Detafrare df = pd.read_fwf("output.txt") #debugging df df["Description"] = (df.iloc[:, 3:].fillna("").astype(str).apply(" ".join, axis=1).str.strip()) df = df.iloc[:, :4] #Converting to SQLITE3 database,. If doesn't existe, a nre one will be created connection = sqlite3.connect("db.sqlite3") #Inserting data into SQLITE database df.to_sql( name = "Devices_App_interfaces", #this is the name format … -
How To Implement Dynamic Columns in Django models based on POST request
I have created a Django RestFramework with few models like Offers, Dailysubs and Requisitions to which I need add columns dynamically for a POST request. There should be 1-10 blank columns for a model and a Master table which has fields to configure the new column like name and other properties. I also need to implement an approach to add these dynamic columns into serializers. class Requisition(models.Model): skill = models.CharField(max_length=255) superClass = models.CharField(max_length=255) jobFamily = models.CharField(max_length=255) yearOfExp = models.CharField(max_length=255) grade = models.CharField(max_length=100) ... ... class Offer(models.Model): businessGroup = models.CharField(max_length=100) status = models.CharField(max_length=20) sNo = models.IntegerField() recruiter = models.CharField(max_length=100) manager = models.CharField(max_length=100) dateOfOffer = models.DateField() dateOfJoining = models.DateField() ... ... class MasterTable(models.Model): columnName = models.CharField(max_length=100) tableName = models.CharField(max_length=100) columnFieldType = models.CharField(max_length=100) I read another post related to this at Django Models (dynamic?) but I don't know if I should create another model to hold these blank columns or if I should add blank columns to each model. -
How can I make a user out of a model in Django?
I'm currently developing a web-application for managing driving licenses as a web development homework assignment. Instead of just storing information on every driver as a model I want to make a user for each driver. What is the easiest way to do so? What am I doing wrong? I updated a car owner model so that it is now inherited from djangdo Abstract User. # models.py class Car_owner(AbstractUser): id_owner = models.IntegerField(primary_key=True) last_name = models.CharField(max_length=30, null=False) first_name = models.CharField(max_length=30, null=False) birth_date = models.DateField(null=True) passport = models.IntegerField(null=True, blank=True) address = models.CharField(max_length=50, null=True, blank=True) nationality = models.CharField(max_length=15, null=True, blank=True) # username = models.CharField(max_length=16, unique=True, default=uuid4) # password = models.CharField(max_length=16, default='password') I also have forms.py file: from django import forms from project_first_app.models import Car_owner class CreateOwner(forms.ModelForm): class Meta: model = Car_owner fields = ['id_owner', 'last_name', 'first_name', 'birth_date', 'passport', 'address', 'nationality'] But when migrating I get the following issue: UNIQUE constraint failed: new__project_first_app_car_owner.username In migrations files I have: migrations.AddField( model_name='car_owner', name='username', field=models.CharField(default=uuid.uuid4, max_length=16, unique=True), ), and then: migrations.AlterField( model_name='car_owner', name='username', field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username'), ), Those are automatically generated. -
How to read URL parameters in a Wagtail model?
I am trying to read parameters from the URL in a Wagtail model function. However, the "request" parameter is not accepted in my model function. I also tried creating a fake function that doesn't read anything, just returns a constant to test that everything else was working fine. This fake function works properly but, as soon as the "request" parameter is added, the function value is not displayed. The problem is without request object, I can't get URL parameters. What am I missing? Do I have to import something for the request parameter to work in the model's functions? Why can't I use the request object in a models function? example of the URL would use: http://localhost/blog/?parameter=someValue MODELS.PY CONTENT from wagtail.core.models import Page from wagtail.core.fields import RichTextField class BlogIndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] def read_parameter(self, request): my_param = request.GET.get('parameter') return my_param HTML TEMPLATE CONTENT {% block content %} <h1>My page</h1> <p>This should be the parameter: {{ page.read_parameter }} </p> {% endblock content %} EXPECTED OUTCOME: My Page This should be the parameter: someValue ACTUAL OUTCOME My Page This should be the parameter: MODELS.PY WITH THE FAKE FUNCTION ADDED class BlogIndexPage(Page): intro = RichTextField(blank=True) … -
Why the request body is empty in Django when I send a request to it from Node JS?
I am writing an application using React Native for frontend, Node JS (express, axios) for backend and Python Django (v 4.1.4) for hosting a neural network. In this app I need to send a POST request containing some parameters in body, as well as a music file. This request goes from React to Node JS to Python server. The request is successfully processed on a Node JS server, however, when I send it to Python Django server from Node, I get an empty body in the python endpoint. Now, when Python server is hosted on amazon (I use Elastic Beanstalk), the request comes with populated body, it stops working once I try to host python server locally and send a request from node js to python django server. You might ask: why bother, just use amazon hosting then? I can't because my neural network is too heavy for free tier hosting and it requires power to respond quickly. The strangest thing is that requests comes to the Python server (it does not say something like CORS error) and the response is sent from Python server, but the request body is empty. I have tried to use another IP for Django … -
How to avoid the use of ManytoMany field in Django?
I have the Role model. Account model take the reference from Role model using ManytoMany Field. But, I don't want to use manytomany field. It's necessary to not use ManyToMany field. Is anyone can suggest something better. I don't want to use use ManyToMany field because, since many to many are a Django feature and not database The given below model works fine with ManyToMany Field, I want the same with it. from django.db import models from django.db.models.fields import proxy from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.utils.translation import gettext_lazy as _ from django.core.validators import RegexValidator import uuid from django.utils import timezone import math from django.core.validators import MinValueValidator, MaxValueValidator ADMIN = 0 CUSTOMER = 1 SELLER = 2 DELIVERY_PARTNER = 4 class Role(models.Model): ''' The Role entries are managed by the system, automatically created via a Django data migration. ''' ROLE_CHOICES = ( (ADMIN, 'admin'), (CUSTOMER, 'customer'), (SELLER, 'seller'), (DELIVERY_PARTNER, 'delivery'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class UserManager(BaseUserManager): ''' creating a manager for a custom user model https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-a-manager-for-a-custom-user-model https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#a-full-example ''' def create_user(self, mobile_number, password=None): """ Create and return a `User` with an email, username and password. """ if not mobile_number: raise ValueError('Users Must Have an email address') … -
Why urlparse is merging "'>>" to my string? [closed]
Does anyone know why urlparse is merging >> to my query parameter? If I use https://example.com?state=YYYY&code=OOOO is working perfectly but when I use request.get_full_path is merging >> to query string. authorization_url = str(request.get_full_path) parsed_url = urlparse(authorization_url) print(parsed_url) #output: ParseResult(scheme='', netloc='', path="<bound method HttpRequest.get_full_path of <WSGIRequest: GET '/", params='', query="state=YYYY&code=OOOO'>>", fragment='') -
building wheel for backports.zoneinfo
Trying to install a Django into my project. Installing from a requirements.txt file django>=4.1.0,<4.2.0 djangorestframework pyyaml requests django-cors-headers here is a stacktrace of the error creating build/temp.macosx-10.14-arm64-cpython-38/lib clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -iwithsysroot/System/Library/Frameworks/System.framework/PrivateHeaders -iwithsysroot/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/Headers -arch arm64 -arch x86_64 -Werror=implicit-function-declaration -I/Users/brendanahern/dev/drf/venv/include -I/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/Headers -c lib/zoneinfo_module.c -o build/temp.macosx-10.14-arm64-cpython-38/lib/zoneinfo_module.o -std=c99 lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found #include "Python.h" ^~~~~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Successfully built pyyaml Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects I am using a Mac with an M1 chip. Answers on a similar question suggested that the error came from numpy and I needed to install it differently due to me using an m1 chip, but did fix the issue. -
django.db.utils.ProgrammingError: relation "core_country" does not exist
This is a minimal example, here's the project structure, just run startproject and startapp and update the modules below missing-table ├── README.md ├── core │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── missing_table │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── static └── templates forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from core.models import Country class SignUpForm(UserCreationForm): country = forms.ChoiceField( choices=enumerate(Country.objects.values_list('name', flat=True)), label='' ) models.py from django.contrib.auth.models import User from django.db import models class Country(models.Model): name = models.CharField(max_length=255, unique=True) code = models.CharField(max_length=2, null=True, unique=True) dial_code = models.CharField(max_length=8, null=True) views.py from core.forms import SignUpForm and add core to INSTALLED_APPS in settings and that's it. You should get the error below which I'm getting on macOS 13.1, django 4.1.4, python 3.11.1. No matter what I run (runserver, makemigration, migrate, migrate core, ...), I get the same error. Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: no such table: core_country … -
Is it possible to add more fields to admin/auth/user?
models.py class UserProfile(User): bio = models.TextField(blank=True, null=True) pfp = models.ImageField(verbose_name='Profile Picture', blank=True, null=True, upload_to="images/profile") forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={"class":"form-control", "placeholder":"example@example.com"})) first_name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"})) last_name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"})) pfp = forms.ImageField(required=False, widget=forms.FileInput(attrs={"class":"form-control"})) bio = forms.CharField(required=False, widget=forms.Textarea(attrs={"class":"form-control", 'rows':5, "placeholder":"Write something about yourself..."})) class Meta: model = UserProfile fields = ['first_name', 'last_name', 'username', 'email', "pfp", "bio"] When creating the user, the two newly added fields (bio and pfp) are not being saved in admin/auth/user, so my question is, is it possible to add those fields to the admin users database? -
axios cannot get only response of base64 but can get the others data
First, I sent image path from react to Django by using axios of POST method. Next, I edited image in Django, and returned edited image that were converted into base64 to react. like this. /* this is view.py in Django */ class SquareCognitionSet(viewsets.ViewSet): @action(methods=['POST'], detail=False, name='Edit image') def show(self, request): input = request.data['input'] edited_image = edit.main(input) // my user-defined function. return base64 after edit image. data = {"message": "Got base64", "base": edited_image, "type": imghdr.what(input)} return Response(data=data) No problem so far. Promlem is from here. I cannot get only base64 data of response that was sent from Django. However, axios could get response from Django. I confirmed console.log() /*this is react*/ useEffect(()=>{ async function check(ImagePath: string) { window.electronAPI.server_on(); // electron starts server to work axios await axios.post("http://127.0.0.1:8000/ImageEdit/edit/", { input: ImagePath // input value of image path }) .then((response)=>{ **console.log("success: ", response); <-- here, I confirmed response** }) this is result of console.log(). Then I run console.log("base64: ", response.data.base); However, nothing is shown. Even the text of "base64: " is disappear. What i tried. I tryed whether I can take out the others value sent from Django. I added value {"message": "Got base64"} in response of Django. Then, I take out value … -
Keycloak change dervied key size
I'm trying to import passwords from Django to Keycloak. They both use the pbkdf2 algorithm, but Django uses a key length of 256 bits and Keycloak uses 512 bits. Therefore the password validation doesn't work. Is there any way to change the key length in the settings. The documentation doesn't mention anything about environment variables or settings. I only found, the constant DEFAULT_DERIVED_KEY_SIZE in the Pbkdf2PasswordHashProvider class. To change this value I believe I have to build Keycloak on my own, which I would prefer not to do. Or is there any other way to rehash the passwords without having the users password. Maybe it is possible to add another Pbkdf2PasswordHashProvider with the changed DEFAULT_DERIVED_KEY_SIZE and then selecting this provider in the settings, so I can still use the 512 version, after all users switched to the 512 bits and then I can deprecate the 256 provider. -
server Python Django
Как принять данные с килента с помощью Post запроса (Логин, пароль, почту) с последующей записью в базу данных для использования при входе Использовал это но не до конца понимаю правильно или нет, скорее всего нет так как в базу данных ничего не записывается #Views.py class Reqs: def __init__(self, user, password, email): self.user = user self.password = password self.email = email class ReqsEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, Reqs): return { "user": obj.user, "password": obj.password, "email": obj.email, } return super().default(obj) def api_response(request): user = request.POST.get("user") password = request.POST.get("password") email_ = request.POST.get("email") data = Data(user, password, email_) data.save() try: return HttpResponse(data, safe=False, encoder=ReqsEncoder) except: return HttpResponse("G") -
Is there a way to make faster requests from django using APIKey or auth check_password?
I have django rest_framework app, and I implemented the hasApiKey approach to restrict the access to my views methods, what is happening is the requests taking from 500 ms till 800 ms to be processed, when I remove the hasAPiKey the requests taking 20 ms to be handled, which is so much diffrence. how can I improve the speed of my requests in this case, even I tried to implement my own ApiKey using make_password, check_password from auth, and I had the same problem, hashing is slowing down the app. any recomendations? thanks! I tried to implement my own ApiKey using make_password, check_password from auth, and I had the same problem, hashing is slowing down the app. -
Trying to deploy a React app with seperate Django backend
Trying to deploy a React/Django website I have created a web applications with a seperate front and backend(React/Django) and ive never deployed either of them. I need it to be available on the internet for a school presentation. I have a vps with ubuntu and plesk running on it. I know how to run build the react app using plesk but i dont know how to add the django backend to it in a way they can connect. Help would be much appreciated. They use Axios with http only cookies to send data front to back. I tried creating a new domain for the react app within plesk. Frontend works and has got a tempory https/ssl protected domain. But dont know how to host the django backend on the same server in a way it can reach the django backend. -
How can I find all the invoices that has at least 5 transactions and all the latest 5 transactions are in status 'paid'?
class ChargeOverInvoice(models.Model): id = models.CharField(db_column='Id', max_length=18, primary_key=True) created_date = models.DateTimeField(db_column='CreatedDate', auto_now_add=True) class ChargeOverTransaction(models.Model): name = models.CharField(db_column='Name', max_length=80, verbose_name='Transaction #', default=models.DEFAULTED_ON_CREATE, blank=True, null=True) chargeover_invoice_id = models.CharField(db_column='ChargeOver_Invoice_ID__c', max_length=255) customer = models.ForeignKey(Account, models.DO_NOTHING, db_column='Customer__c') invoice = models.ForeignKey(ChargeOverInvoice, models.DO_NOTHING, db_column='ChargeOver_Invoice__c', blank=True, null=True) status = models.CharField(db_column='Status__c', max_length=255, verbose_name='Status') created_date = models.DateTimeField(db_column='CreatedDate', verbose_name='Created Date') I can get the result if it was about filtering within dates like this ChargeOverTransaction.objects.filter(status='Failed (decline)', created_date__lte=now()-relativedelta(days=35)).values('customer', 'invoice', 'chargeover_invoice_id').annotate(total=Count('id')).filter(total__gte=5) But not sure how can I get the latest 5 and add validation on them. -
How to pass database credentials securely inside docker container using Gitlab cicd?
Unable to securely pass database credentials inside a docker container in order to connect Django to Postgresql using gitlab cicd. I've added environment variables to the gitlab cicd settings. However,this method is not working -
How to compare a two table values in django using filter
def count_time(request): sp = Specific_product.objects.filter(boolean=False) #I need to compare the sp product and product table name using this method products = Product.objects.all().filter(name={{sp.product}}) stu={ "pro_d":sp,'products': products,'purchases':purchases } return render(request, 'mf_ta/product_status.html', stu) #I need to compare the row values of Specific_product table (product) and Product table (name) using the sp.product. How can I satisfy this condition I'm getting this error AttributeError at /count_time/ 'QuerySet' object has no attribute 'product' Request Method: GET Request URL: http://127.0.0.1:8000/count_time/ Django Version: 4.0.7 Exception Type: AttributeError Exception Value: 'QuerySet' object has no attribute 'product' Exception Location: C:\Users\Admin\PycharmProjects\pythonProject1\invention_on_macroalgae\manufacturing_team_app\views.py, line 56, in count_time Python Executable: C:\Users\Admin\PycharmProjects\pythonProject1\venv\Scripts\python.exe Python Version: 3.9.0 Python Path: ['C:\Users\Admin\PycharmProjects\pythonProject1\invention_on_macroalgae', 'C:\Users\Admin\PycharmProjects\pythonProject1', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39', 'C:\Users\Admin\PycharmProjects\pythonProject1\venv', 'C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages'] Server time: Mon, 26 Dec 2022 03:54:39 +0000 -
AttributeError: 'PostsTranslation' object has no attribute 'created_at'
I am using django-parler for model translation, but getting error when creating object, I guess I understand my problem but cannot find solution. Here I have abstract class which I use from other models models.py class TimeStampedModel(TranslatableModel): created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Posts(TimeStampedModel): name = models.CharField(max_length=255) translations = TranslatedFields( slug = models.SlugField( max_length=255, db_index=True, unique_for_date='created_at' ), ) AttributeError: 'PostsTranslation' object has no attribute 'created_at' I am getting this error because of using unique_for_date='created_at' What can I do in this situation ? -
Email error: Message is not sending to the email instead it is printing in the terminal
When I am registering as a new user or want to change my password, then the Message which is needed to be sent to the email is showing in the terminal instead. Here is the terminal picture: enter image description here Here is the views.py function. from aiohttp import request from django.contrib.sites.models import Site from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib import messages from companies.models import Company from accounts.roles import UserRole # User mode from .models import CustomUser from domains.models import Domain from dashboard.models import MarketingHome, SliderHome # Custom forms from .forms import PublicCustomUserChangeForm, CustomChangePasswordForm from django.contrib.auth import views as auth_views from django.shortcuts import resolve_url from allauth.account.views import SignupView, LoginView @login_required def change_password_user(request): company = CustomUser.get_company(request.user) if request.method == "GET": form = CustomChangePasswordForm(request.user) context = { 'form': form, 'company': company } return render(request, 'account/change_password_user.html', context) else: form = CustomChangePasswordForm(request.user, request.POST) if form.is_valid(): form.save() # update_session_auth_hash(request, user) messages.success(request, 'Your password was successfully updated!') return redirect('account_change_password_user') else: messages.error(request, form.errors) return redirect('account_change_password_user') here is the registration function: class AccountSignupView(SignupView): template_name = "account/signup.html" def get_context_data(self, **kwargs): current_site = self.request.META['HTTP_HOST'] context = super(SignupView, self).get_context_data(**kwargs) context = { 'slider': SliderHome.objects.filter(domain_site__domain__contains=current_site, is_active=True), # 'current_domain': Domain.objects.filter(site__domain__contains=current_site).first() } return context account_signup_view = AccountSignupView.as_view() -
How to deploy Docker image from ECR to Elastic Beanstalk
I pushed the image of my django project to AWS ECR and now I need to deploy it to AWS Elastic Beanstalk. Now I have an application in EB with Docker platform and the sample app. In software configuration I added DOCKER_IMAGE_URL and set the value as the ECR image URI and after updating I'm still redirected to the sample app Wondering what I'm doing wrong or is that even the right way of deploying a django app to EB docker platform.