Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run Django rest api and react build together
I'm running django rest api and react in 2 different ports (using nginx and gunicorn), I want to only run the django server that will take charge of showing react build (react pages), so both react and django will run in the same port. -
issue with connecting to PostrgreSQL on localhost in Django application [duplicate]
I am using Docker to run my Django app and I have multiple images in it: PostgreSQL, celery_worker, celery_beat, and django_app. All of them except celery_beat is working fine. I am using this command to build docker: docker-compose -f docker-compose.yml up -d --build When I open Docker Desktop I see that it restarts all images, everything is working fine for few seconds, then it exits celery-beat and returns in celery-beat image with the following error: [2022-10-13 15:34:59,440: WARNING/MainProcess] could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I tried many solutions that I found on StackOverflow and other pages but with no success. 4 out of 5 images are working fine. When clicking on postgreSQL image I see the following status: 2022-10-13 13:27:04.195 UTC [1] LOG: database system is ready to accept connections docker-compose.yml version: '3.8' services: db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=PF23_admin - POSTGRES_DB=postgres container_name: docerized_app_db_postgresql_dev app: build: context: ./backend dockerfile: Dockerfile restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/:/usr/src/backend/ ports: - 8000:8000 env_file: - ./.env depends_on: - db container_name: docerized_app_django_app_dev redis: image: redis:7-alpine ports: - "6379:6379" container_name: docerized_app_redis_dev celery_worker: … -
Code works without errors in vs code, but not from command promt
I am learning django and to run a server i should do python manage.py runserver. I have installed django, but when i try to run a command through a command prompt i always get an error Traceback (most recent call last): File "D:\projects\django-proj\password_generator\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\projects\django-proj\password_generator\manage.py", line 22, in <module> main() File "D:\projects\django-proj\password_generator\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? if i call django-admin in command prompt, it works well. it also works if i just run a code in vs code. what can be the problem? -
Using HTMX/Javascript in Django Template : not defined
I decided to try HTMX with Django and implementing a Django form in a modal box. I found this tutorial and was following it. I got to the part where it uses an HTMX function htmx:afterSwap to open the modal but when I put that in a script tag in the template, I run into an error. It is Step 4 where the error occurs. My template looks (mostly) like this. I've tried to trim it down to the essentials. {% for thing in things %} {% if forloop.first %} <ul id="myThingList" class="things"> {% endif %} <button id="thing{{ thing.id }}Button" type="button" class="btn btn-primary" hx-get="{% url 'myapp:things-create' %}" hx-target="#thingSection"> Upload Thing</button> <li id="thingItem" class="thing" hx-target="this" hx-swap="outerHTML"> {{ thing.name }} </li> <div id="thingModal" class="modal fade" role="dialog" tabindex="-1" aria-labelledby="thingModal" aria-hidden="true"> <div id="thingSection" class="modal-dialog modal-dialog-centered" hx-target="this" role="document"></div> </div> {% if forloop.last %} </ul> {% endif %} {% empty %} <p class="no-things">No things have been added yet.</p> {% endfor %} <script> const modal = new bootstrap.Modal(document.getElementById("thingModal")) htmx.on("htmx:afterSwap", (e) => { // Response targeting #thingSection => show the modal if (e.detail.target.id == "thingSection") { modal.show() } }) </script> I am getting Uncaught ReferenceError: bootstrap is not defined Additional information: HTMX works (I use it in other … -
(urls.E004). Your URL Pattern is invalid in project level urls.py file
I am newbie to Django. I am getting the below error in-spite of rightly mapping the app level urls.py file to project level urls.py. Please help. urlpatterns = [ path('admin/', admin.site.urls), path('app_space/', include ('app_space.urls')) ] Response in terminal: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern <contextlib._GeneratorContextManager object at 0x000001C33030C7C8> is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. -
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request
I'm trying to do get-request from react to django-server let projects = await axios.get('http://127.0.0.1:8000/api/project', {headers}).catch(error => console.log(error)) And i get 'Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/project' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.' -
how do I convert PCM 16bit signed LE 16000kHz to WAV in python given only the bytes?
I pulled an object from amazon s3 buckets like so: s3_response_object = S3.get_object(Bucket=bucket_name, Key=key_name) object_content = s3_response_object['Body'].read() # object content --> b'\x06\x10...' Inside the bucket you have a PCM 16bit signed LE 16000kHz audio file. If you write that file to a .wav file like so: with open("audio.wav", "wb") as f: f.write() The wav file cannot be played by quicktime VLC or any audio player. How can I convert these bytes into a wav file. The end goal is to pass these bytes into a view with django, and I have already verified that my django view works properly using a drop in replacement stream of bytes to use for the view, and the audio plays back no problem. I think the bytes that I get from AWS need some type of conversion to be valid for passing into my view. Any help would be much appreciated. END GOAL INSIDE DJANGO VIEW: def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: """" get_context_data gets audio from S3 and pass to django view""" context = super().get_context_data(**kwargs) s3_response_object = S3.get_object(Bucket=bucket_name, Key=key_name) object_content = s3_response_object['Body'].read() context["audio"] = b64encode(object_content) return context INSIDE DJANGO TEMPLATE <audio controls> <source src="data:audio/wav;base64,{{ audio }}" type="audio/wav"> </audio> Any help would be … -
AttributeError at /customers/f0e85ace-438f-4c61-a129-6d5986e6f346/ 'customer' object has no attribute 'get'
i have just started django and i am struggling to find error .Seems like get() method is not being recognized .What should i do?I would really appreciate your help from django.db import models from django.core.validators import RegexValidator import uuid # Create your models here. class customer(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) name=models.CharField(max_length=200,null=True) phone_no=models.CharField(max_length=200, validators= [RegexValidator(r'^\d{1,10}$')],null=True) email=models.EmailField(max_length=200,null=True) def __str__(self): return self.name class tag(models.Model): name=models.CharField(max_length=200,null=True) def __str__(self): return self.name class products(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) categories=[ ('organic','organic'), ('inorganic','inorganic') ] name=models.CharField(max_length=200,null=True) price=models.FloatField(null=True) manufacturedate=models.DateTimeField(auto_now_add=True,null=True) description:models.TextField(null=True) categories=models.CharField(max_length=200,null=True,choices=categories) tag=models.ManyToManyField(tag) def __str__(self): return self.name class order(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) status=[ ('pending','pending'), ('out of stock','out of stock',), ('Delivered',('Delivered')) ] ordered_date=models.DateTimeField(auto_now_add=True) status=models.CharField(max_length=200,null=True,choices=status) customer=models.ForeignKey(customer,null=True,on_delete=models.SET_NULL) product=models.ForeignKey(products,null=True,on_delete=models.SET_NULL) urls.py url seems ok i could not find any mistake from django.urls import path from . import views urlpatterns=[ path('',views.home), path('products/',views.product), path('customers/<str:pk>/',views.customer), ] views.py Here in the customer it is not it says get is not the attribute .seems like i am missing something from django.shortcuts import render from .models import * # Create your views here. def home(request): customers=customer.objects.all() orders=order.objects.all() total_customers=customers.count() total_orders=orders.count() delivered=orders.filter(status='Delivered').count() pending=orders.filter(status='pending').count() context={'customers':customers,'orders':orders,'total_customers':total_customers, 'total_orders':total_orders,'delivered':delivered, 'pending':pending } return render(request,'accounts/home.html',context) def product(request): product=product return render(request,'accounts/products.html') def Customer(request,pk): Customer=customer.objects.get(id=pk) return render(request,'accounts/customers.html') -
Should I use Django Function based views or Class based views for better functionality?
I am just learning Django, and I am attempting a project to create a notes app. During the process of the project, a friend of mine advised me to use function-based views, but I later discovered that class-based views can be customized too. Given that both can work fine for my little project, is it best practice to use function-based views from scratch or to override class-based views methods? Thank you. -
Django Browser back button issue after logout not able to login again
I am trying to integrate Azure AD with Django and achieve single page application behaviour.When I login with Azure ad at first time it working fine, i logout and click Browser Back button from Logout page it is stay on logout page but After that i'm try to login from logout page I'm not able to login again. Index content doesn’t load, content remains same as logout page. -
how to clear an input fields when i click another tab it should clear the input field data Any suggestions?
any suggestions Iam working on one data filtering part in my task it takes an input values it shows filter options but if i open another tab of same page or switched to another page still it holds given input values my motto is clear the screen when we click another page or tab any suggestions please????? -
How to call bussines logic from seperate class in view in Django?
I am using django framework. And I have some functionality for uploading files. And I have a textarea where the extracted content of the uploaded file will be shown. So for example if you upload a pdf file within a image that contains text. In the textarea the text will be shown. But the logic for extracting the text from the image of course doesn't belong too the method in the view. So I made a seperate class for it, with name: extractingTextFromFile.py that looks like this: import io from tracemalloc import start from PIL import Image import pytesseract from wand.image import Image as wi import re class ExtractingTextFromFile: def extractingtextfromimage(): text_factuur_verdi = [] #image = pdfFile.convert('jpeg') imageBlobs = [] for img in image.sequence: imgPage = wi(image=img) imageBlobs.append(imgPage.make_blob('jpeg')) for imgBlob in imageBlobs: image = Image.open(io.BytesIO(imgBlob)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) and I have the views.py: from django.shortcuts import render from django.views import View from django.http import HttpResponseRedirect from .forms import ProfileForm from .models import UploadFile import extractingTextFromFile as textFromFile from wand.image import Image as wi from PIL import Image import pytesseract from django.conf import settings import io import os class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", … -
Insert data from an API on the database - Django project
I would like to save product data from an API in a table in my database that I created Models.py class Product(models.Model): code=models.CharField(max_length=70,primary_key=True) designation=models.TextField() def __str__(self): return self.product.code views.py from .models import Product def products(request): url='http://myAPI/Product/GetProducts' x=requests.get(url) content=x.json() all_product=content['products'] for product in all_product: product.save() return render(request,'cart/product.html',context) How to proceed to insert each product in the table with the for loop ?? Note that each product is characterized by a code and a designation -
Can someone help me to how to add a custom button when I clicked edit in Po or So and Once I clicked that button , one internal Suitelet should open
/** @NApiVersion 2.x @NScriptType ClientScript */ define(["N/record", "N/url",'N/currentRecord'], function (record, url,currentRecord) { function onclick_callforSuitelet(){} function pageInit() { var record = currentRecord.get(); var recordId = record.id; var recordType = record.type; log.debug("recId", recordId); log.debug("recType", recordType); var suitletURL = url.resolveScript({ scriptId:'customscriptss_suiteletbutton', deploymentId:'customdeployss_suiteletbutton', returnExternalUrl: true, params: { recId: recordId, recType: recordType } }); log.debug("suitletURL", suitletURL); } return{ pageInit:pageInit, onclick_callforSuitelet:onclick_callforSuitelet } }); -
The problem of not quickly adding the product to the shopping cart in django
I am building an online store with django, and I encountered a problem. The problem is that I can add the product through the product details page. But I can't do the same thing through the Add to cart button directly on the main page of the site. And my main problem is that when I directly click the Add to cart button on the main page. I am redirected to the shopping cart page, but without any products. All required images This is index.html in shop app: <div class="product"> <div class="product-img"> <img src="{{ product.image.url }}" alt=""> <div class="product-label"> <span class="sale">-30%</span> <span class="new">NEW</span> </div> </div> <div class="product-body"> <h3 class="product-name"> <a href="{{ product.get_absolute_url }}">{{ product.name }} </a> </h3> <h4 class="product-price">${{ product.price }}</h4> <div class="product-rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> </div> <div class="product-btns"> <button class="add-to-wishlist"><i class="fa fa-heart-o"></i><span class="tooltipp">add to wishlist</span></button> <button class="add-to-compare"><i class="fa fa-exchange"></i><span class="tooltipp">add to compare</span></button> <button class="quick-view"><i class="fa fa-eye"></i><span class="tooltipp">quick view</span></button> </div> </div> <div class="add-to-cart"> <form action="{% url 'cart:cart_add' product.id %}" method="post"> {{ cart_add_product_form }} {% csrf_token %} <button type="submit" class="add-to-cart-btn"> <i class="fa fa-shopping-cart"></i> add to cart </button> </form> </div> </div> This is detail.html in cart app: <table class="cart table"> … -
Django similar queryset optimization
I am making a filmography website. However, I am having a hard time optimizing the queryset in the detailview. class Actor(model.Models): id = models.IntegerField() name = models.CharField() class Movie(model.Models): id = models.IntegerField() movie_title = models.CharField() actor = models.ManyToManyField(Actor, related_name='relations') class ActorView(DetailView): model = Actor context_object_name = 'actor' template_name = 'actor.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['movies'] = self.object.relations.all() return context <div> {{ actor.name }} {% for movie in movies %} {{ movie.movie_title }} {% for actor_info in movie.actor.all %} {{ actor.name }} {% endfor %} {% endfor %} </div> I checked the sql tap in the django debug console. {% for actor_info in movie.actor.all %} {{ actor.name }} {% endfor %} Similar queries are being executed repeatedly in the code above. And data connection and query execution time are also very slow. How can I optimize this part in the view or model? -
Getting current username in utils.py django
I am new to django, trying to create a number sequence field while loading the page, the combination of current datetime + current username + count(his posts on this month) + 1 . To achieve this i use initial . forms.py class PostForm(ModelForm): post_no = forms.CharField( label='Post No',initial=getPostNo, widget=forms.TextInput(attrs={ 'class': 'form-control', 'readonly': 'readonly', 'placeholder':'Post No' }) in utils.py the definition of getPostNo def getPostNo: from .models import Posts m = datetime.now().month y = datetime.now().year tme = datetime.now().strftime("%d%m%Y") cnt = Posts.objects.filter(employee_id=1,post_date__month=m,post_date__year=y).count()+1 #here i need to filter using the current user id logged in . i gave 1 for testing return tme+str(cnt)+str(current username) //here i need current username i couldnt pass the logged in userid to getPostNo from forms.py and also i can't get request.user in utils.py. please suggest the right way to do this. thanks for any help. -
How to make autocomplete_fields search in model's string representation in Django 3
As I am using string representation of a model, it is also shown in a autocomplete_fields (Select2). But the problem is that when i try to search in the field, it is searching the model's name field, not string representation. Here is my code example: models.py class Store(models.Model): name = models.CharField(max_length=256) class Department(models.Model): name = models.CharField(max_length=256) store = models.ForeignKey(Store, on_delete=models.CASCADE) class Shelf(models.Model): name = models.CharField(max_length=256) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __string__(self): return f'{self.department.store.name} {self.department.name} {self.name}' class Product(models.Model): name = models.CharField(max_length=256) shelf = models.ForeignKey(Shelf, on_delete=models.CASCADE) admin.py @admin.register(Product) class ProductAdmin(admin.ModelAdmin): autocomplete_fields = ('shelf',) list_display = ('name', 'shelf') Is it posible to search by model string representation in this case? -
Django/Postgresql sequence not set when creatin objects in views
I have write a view that load an excel file as dataframe and use this datafralme to create or update records in a Postgresql database. But I can figure out why Postgresql sequence are not updated? This lead to database error when try add other records via admin forms. My stack: Django 2.2.5/Python 3.7.4/Docker/Docker-compose/Postgresql 2 models used: PData (86 records) and PForm (22 records), with PData_ide_seq and PForm_ide_seq, respectively When I check PForm_ide_seq, current value is 1 instead of 22 What is going wrong? @login_required def update_parameters(request): if request.is_ajax() and request.method == "POST": if ParametersFile.objects.all(): LAST_PARAMETER_FILE = ParametersFile.objects.all().last().upload dcf_queries = pd.read_excel(f'./{ LAST_PARAMETER_FILE }',sheet_name='data_queries_definitions').fillna('') missing_forms_queries = pd.read_excel(f'./{ LAST_PARAMETER_FILE }',sheet_name='form_queries_definitions').fillna('') print(LAST_PARAMETER_FILE) for record in dcf_queries.to_dict(orient='records'): PData.objects.update_or_create( ide=record['ide'], # filter to search for existing objects => should not be pass to default (if not IntegrityError) defaults = { 'query_type':record['query_type'], 'crf_name':record['crf_name'], 'crf_table':record['crf_table'], 'variable_name':record['variable_name'], 'variable_label':record['variable_label'], 'query_condition':record['query_condition'], 'query_message':record['query_message'], 'fields_to_display':record['fields_to_display'], 'activated': True if record['activated'] == 1 else False, } ) for record in missing_forms_queries.to_dict(orient='records'): PForm.objects.update_or_create( ide=record['ide'], # filter to search for existing objects => should not be pass to default (if not IntegrityError) defaults = { 'query_type':record['query_type'], 'source_form':record['source_form'], 'source_condition':record['source_condition'], 'search_form':record['search_form'], 'search_condition':record['search_condition'], 'query_message':record['query_message'], 'activated': True if record['activated'] == 1 else False, } ) return JsonResponse({"response": "Queries definitions table … -
Sum of a the column values of pivot_table - pandas
df = pd.DataFrame(result) df_pivot = pd.pivot_table( df, index=["sizeoforchardholding", "nooforchardists"], columns="fruit_plant_kind", values=["sizeoforchardholding", "nooforchardists"], aggfunc='sum', margins=True, margins_name='Sum', fill_value=0, ).reset_index() I want to find the sum of each column in the end but when I do it with margin it throws an error. Error: Survey Report Had an exception Grouper for 'sizeoforchardholding' not 1-dimensional Internal Server Error: /KindWise-Fruit-Survey-OrchardCount how can I find the sum of each column in the end. -
Using UpdateModelMixin update() to update record
How can I perform a partial update within list()? I am trying to update the balance value in a Wallet record class WalletListCreateAPIView(generics.ListCreateAPIView, mixins.UpdateModelMixin): queryset = Wallet.objects.all() serializer_class = WalletSerializer def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) def list(self, request, *args, **kwargs): current_user = request.user wallets = Wallet.objects.filter(user=current_user) balances = get_wallet_balances([wallet.address for wallet in wallets]) for wallet in wallets: # Update wallet balance based on address balance = balances[wallet.address] return super().list(request, *args, **kwargs) -
Synbolik link on web server doesn't work?
I have static folder serving the files on uwsgi. /user/app/static/ lrwxrwxrwx 1 root root 23 Oct 13 09:40 _out -> /usr/src/app/_mat/_out/ drwxr-xr-x 8 root root 4096 Oct 13 09:49 assets drwxr-xr-x 8 root root 4096 Oct 13 09:40 pages in this case, the imagefiles under assets can be appeared correctly, however the image files under _out can not be accessed.(404 error occurs) static/assets/test.png is ok static/_out/test.png returns 404 error I checked the permissions. Generally speaking, does symbolic link work under web server? -
how i can test views py django
i just learning how to pytest my code in django, and i need your help. So, i have tested my forms.py already,and now i want to test my views.py. I know that i need to test is it post on page,like by response on by ORM, but i cant understand how to do that, probably with my factories or no? This is my views.py class AddPost(CreateView): model = Posts form_class = PostsForm template_name = 'posts/addpost.html' success_url = '/' def form_valid(self, form): instance = form.save(commit=False) if self.request.user.is_authenticated: instance.owner = self.request.user instance.save() return HttpResponseRedirect(self.get_success_url()) class ShowPost(ListView): model = Posts template_name = 'posts/allposts.html' paginate_by = 2 this is test_forms @pytest.mark.django_db(True) class TestPostCreationForm: def test_form(self): proto_post = PostsFactory.build() form_payload = { 'phone_number': proto_post.phone_number, 'title': proto_post.title, 'type': proto_post.type, 'text': proto_post.text, 'price': proto_post.price, 'status': proto_post.status, 'image': proto_post.image, } form = PostsForm(form_payload) assert form.is_valid() instance = form.save() assert instance.phone_number == proto_post.phone_number assert instance.title == proto_post.title assert instance.price == proto_post.price and factories from users.tests.factories import UserFactory def get_mock_img(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = Image.new("RGB", size=size, color=color) image.save(file_obj, ext) file_obj.seek(0) return File(file_obj, name=name) class PostsFactory(factory.DjangoModelFactory): owner = SubFactory(UserFactory) phone_number = factory.Faker("phone_number", locale='uk_UA') title = factory.fuzzy.FuzzyText(length=50) text = factory.fuzzy.FuzzyText(length=250) price = factory.fuzzy.FuzzyDecimal(10.5, 50.5) status … -
Python Django use mysql function SHA2('pass',256)
I am creating application in Django and now I want create table with username and password. Right now, we generating password with mysql function SHA2('password',256) and my question... is possible use it the same in Django model? I mean everything what will be save to password row, will be saved as hash sha2 in admin app or I must create functions? this is my models.py class Users(models.Model): username = models.CharField(max_length=30) password = models.CharField(max_length=128) status = models.IntegerField() valid_from = models.DateTimeField() valid_to = models.DateTimeField() online = models.IntegerField() ip = models.CharField(max_length=20) created = models.DateTimeField() def __str__(self): return f'{self.username}' -
How to connect QuestDB with Django?
Is there any way to connect QuestDB with Django? I have looked into this documentation, but there are no specific engine for that purpose. Is there a way to set the settings in the settings.py file? Thanks.