Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest client change content type
I have a working test that checks the functionality of the POST request coming to the django url endpoint @pytest.mark.django_db def test_me(logged_client): .... data = { 'creativeId': 12, 'descriptionTextId': 345, 'headlineText1Id': 432, 'headlineText2Id': 478, 'campaigns': ['HS_GP_UNKNONW_CAMPAIGN_Purchase07_WW_2_20.07.09'], 'creativeCategory': 'video', } response = logged_client.post( reverse('google_panel:run_google_soft_launch'), data=json.dumps(data), content_type='application/json', ).json() assert ... Now the list of values coming in the post request has changed. One more parameter creativeRotationType was added. accordingly a new value is added to the data data = { .... 'creativeRotationType': 'asset' } But now there is an error ValueError: Content-Type header is "text/html; charset=utf-8", not "application/json" How is it that adding a new field changes the type from application/json to text/html; charset=utf-8 ? -
How to insert local HLS video on Django
I have a rtsp stream that I locally convert in HLS stream with ffmpeg following the second answer of this guide. Now I have to insert this video in Django. How the guide suggests I need videojs and with HLS plugin. Here my html code: <!doctype html> <html lang="it"> <head> <title> Stream Player </title> <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet"> </head> <body> <center> <video-js id="my_video_1" class="vjs-default-skin" controls preload="auto" width="800" height="600"> <source src="/video/test.m3u8" type="application/x-mpegURL"> </video-js> <script src="https://unpkg.com/video.js/dist/video.js"></script> <script src="https://unpkg.com/@videojs/http-streaming/dist/videojs-http-streaming.js"></script> <script> var player = videojs('my_video_1'); </script> </center> </body> </html> "/video/test.m3u8" is a directory inside Django project. When I run my project I can't see the video and the error is "The media could not be loaded, either because the server or network failed or because the format is not supported." Can someone help me? -
Postgres database error while updating fields in Django models.py
models.py client_name=models.CharField(max_length=20) company=models.CharField(max_length=200) finance_contact_email=models.EmailField(max_length=25,default=None) business_purpose=models.CharField(max_length=50,null=True,default=None) location=models.CharField(max_length=200) emergency_contact=models.CharField(max_length=200,null=True,default=None) website=models.URLField(max_length=200,null=True) comments=models.TextField(max_length=300,null=True, blank=True) start_Date = models.DateTimeField(max_length=10,null=True) end_Date=models.DateField(max_length=10,null=True) #sample=models.CharField(max_length=244,null=False,default=None) #sample2=models.CharField(max_length=244,null=False,default=None) class Meta: db_table ='Client' def __str__(self): return self.client_name While adding an extra field in models.py, the database shows this following error (ProgrammingError at /admin/App/client/ column Client.sample does not exist LINE 1: ...nts", "Client"."start_Date", "Client"."end_Date", "Client"."...). To overcome this issue, I have to drop the database and create a new DB but all values will be lost. So, dropping the database every time during Production will be not acceptable. I am using postgres for database. Kindly help me to sole this issue without dropping the database Currently using these steps for migrating 1. python3 manage.py makemigrations app_name 2. python3 manage.py migrate 3. python3 manage.py runserver -
How to make Many-to-many mutations in Django-Graphene?
I'm working in Django 3.2 and graphene-django 2.15. I'm still learning how to use Graphene by the way. Note: I'm not allowed to share all the code so I rewrote it for the purpose of this question. Please notify me if you've found any error unrelated to the question. I have an Team model which has a Many-to-Many relationship with the default Django Group model: from django.db import models from django.contrib.auth.models import Group class Team(models.Model): team_id = models.IntegerField(unique=True) # Custom ID not related to Django's pk name = models.CharField(max_length=255) groups = models.ManyToManyField(Group, blank=True) Here is my schema: import graphene from django.contrib.auth.models import Group from graphene_django import DjangoObjectType from .models import Team class TeamType(DjangoObjectType): class Meta: model = Team class GroupType(DjangoObjectType): class Meta: model = Group class GroupInput(graphene.InputObjectType): id = graphene.ID(required=True) class UpdateTeam(graphene.Mutation): team = graphene.Field(TeamType) class Arguments: team_id = graphene.ID(required=True) name = graphene.String(required=True) groups_id = graphene.List(GroupInput, required=True) def mutate(self, info, team_id, name, groups_id): team = Team.objects.get(pk=team_id) team.name = name team.groups = Group.objects.filter(pk__in=groups_id) team.save() return UpdateTeam(team=team) class TeamMutations(graphene.ObjectType): update_team = UpdateTeam.Field() class Mutation(TeamMutations, graphene.ObjectType): pass schema = graphene.schema(query=Query, mutation=Mutation) When I perform this query: mutation{ updateTeam( teamId: 65961826547, name: "My Team Name", groupsId: [{id: 1}, {id: 2}] ) { team { … -
Django Rest Framework - How to create a Rest api to send it to a blockchain
I have created a Django app, I wanted to build a REST Api within django using python sdk library given by the hyerledger iroha(https://github.com/hyperledger/iroha-python). here are my models.py #Iroha Test class IrohaAccounts(models.Model): acc_name = models.CharField(max_length=30, null=False, blank=False, unique=True) dom_name = models.CharField(max_length=50,null=False, blank=False) def __str__(self): return self.acc_name Serializer.py #Iroha Test class IrohaAccountsSerializer(serializers.ModelSerializer): class Meta: model = IrohaAccounts fields = ['acc_name','dom_name'] def save(self): account = IrohaAccounts( acc_name=self.validated_data['acc_name'], dom_name=self.validated_data['dom_name'], ) account.save() return account Views.py #Iroha Test @api_view(['POST',]) def iroha_account(request): """ Create account 'userone@domain' """ if request.method == "POST": serializer=serializers.IrohaAccountsSerializer(data=request.data) if serializer.is_valid(): account=serializer.save() data = { 'response' : "acc create", 'acc_name' : account.acc_name, 'dom_name' : account.dom_name, } # these first two lines are enough to create the keys private_key = IrohaCrypto.private_key() public_key = IrohaCrypto.derive_public_key(private_key) tx = iroha.transaction([ iroha.command('CreateAccount', account_name=acc_name, domain_id=dom_name, public_key=public_key) ]) IrohaCrypto.sign_transaction(tx, ADMIN_PRIVATE_KEY) send_transaction_and_print_status(tx) return Response(data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) BTW I'm new to django and learning i don't know what is wrong by default it goes to the postgres sql database and checks for the table. But i wanted the request to sent to the Blockchain instance which is running in the docker container. Do help thank you! -
how to show only the data of the user that is logged in (Django)
So it shows data like all objects but now I only want to show the specific data of each user this is my views.py: views. py and this is my models.py models.py -
How to have countries,cities, regions and subregions in a Django Project
I'm developing a simple website in Django. The main function of the WebApp is to store user information like: Country of the User City of the User Region (of the Country) of the User Sub-region (of the Country) of the User District (of the Country) of the User In my search for solutions I've found one. To use the http://www.geonames.org/ database. In relation to Django specifically I've found a two Django Apps: https://github.com/coderholic/django-cities https://github.com/yourlabs/django-cities-light I'm currently testing django-cities and I've lost two days trying to import the data. The App is unmaintained and modifications must to be done so the App runs on Django 4 and until now I've not been successful to make it work. My question here on SO is mainly to ask for help about options. Is GeoNames the only option? The Django community have other options than django-cities and django-cities-light? Thanks in advance. -
how to write the fetch in that case - django app payment
hello I am working on a django app 'my app is about paying for someone service' client will access to the page and click on their selected person and then they will fill a form and click on get the service and then people who work in the plateform will go to another page and they can find a list of forms of people who want to get their service .... but I want the form not to be posted until the payment is done so my database will not be fall. so this is my views.py I have actually 2 functions : #here where client can select people they are willing to take service from @login_required(login_url='login') def pSelected(request,slug): profile = get_object_or_404(Profile,slug=slug) form = MessageForm() if request.method == 'POST': form = MessageForm(request.POST,request.user) form.sender = request.user.username form.receiver = request.POST.get('receiver', '') if form.is_valid(): form.sender = request.user.username form.receiver = request.POST.get('receiver', '') messages.success(request, f'succed') form.save() print(form.sender,form.receiver) else: form = MessageForm() return render(request,'base/p-selected.html',context) #here for workers in the platefrorm @login_required(login_url='login') def giveService(request): requests = Message.objects.all().order_by('-id') context={'requests':requests} return render(request, 'base/giveService.html',context) now in my p-selected.html <form> <!--I have here for example a form method post *inside of my form I have input get and payment with paypal … -
Google Cloud Storage access via service account
I've been repetitively hitting my head against the proverbial brick wall of GCP's Storage API. I'm trying to apply the django-storages module to connect with a GCP bucket for my static files and anything else I want to use it for in the future. According to the django-storages documentation (https://django-storages.readthedocs.io/en/latest/backends/gcloud.html#usage), if you are running in the GCP virtual environment, you set your service account to have Storage permissions via the IAM interface and everything should work like tickety-boo. So, my GCP cloud build runner builds the docker images then runs python manage.py migrate and python manage.py collectstatic before deploying my docker image to CloudRun. The build runner uses a service account called XXXX@cloudbuild.gserviceaccount.com, so going into IAM, I add the “Cloud storage – Storage admin” role, and just to be sure, I also add the “Cloud storage – Storage object admin” role. Now I trigger a re-run of my cloudbuild and ... at the migrate stage I receive the error: ... Step #2 - "apply migrations": File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module Step #2 - "apply migrations": return _bootstrap._gcd_import(name[level:], package, level) Step #2 - "apply migrations": File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Step #2 - "apply migrations": File "<frozen … -
Django dictionary with the same value
I'm trying to create a dictionary with some specific values but it gets multiple values the same readers = Readers.objects.all() count = 0 readersResult = {} teste = { "avatar": "", "firstName": "", "percent": "", "lastName": "" } for reader in readers: test["percent"] = "value from another place" test["firstName"] = reader.firstName test["lastName"] = reader.lastName test["avatar"] = reader.avatar print("TEST: ", test) readersResult[count] = test count = count + 1 print("RESULT":, readersResult) My output is: web_1 | TEST: {'avatar': '/images/avatars/71.png', 'firstName': 'abc', 'percent': '37.08999158957107', 'lastName': 'def'} web_1 | TEST: {'avatar': '/images/avatars/61.png', 'firstName': 'abc', 'percent': '4.037005887300253', 'lastName': 'def'} web_1 | RESULT: {0: {'avatar': '/images/avatars/61.png', 'firstName': 'abc', 'percent': '4.037005887300253', 'lastName': 'def'}, 1: {'avatar': '/images/avatars/61.png', 'firstName': 'abc', 'percent': '4.037005887300253', 'lastName': 'def'}} What am I doing wrong ? -
Django models equal one filed to another
i try to equal owner_id to id , i mean when user's id is 1 and create organization i want to owner_id also be 1 . what is best way? class Organization(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(default='0000000',max_length=100) type = models.CharField(default='0000000',max_length=20) owner_id = models.CharField(id,max_length=100) def __str__(self): return str(self.name) this not working owner_id = models.CharField(id,max_length=100) -
start docker with database, but i don't see database results in api
start docker with database, but i don't see database results in api I attach an image of the console running docker-compose up attached image of the api and attached image of the db docker image api image db image -
Dajngo CSV FIle not download ? When we have a large CSV file download its takes some time?Django 502 bad gateway nginx error Django
How can I download a large CSV file that shows me a 502 bad gateway error? I get this solution I added in below. Actually, in this, we use streaming references. In this concept for example we download a movie it's will download in the browser and show status when complete this will give the option to show in a folder same as that CSV file download completely this will show us. -
view the count of items cycled in that single day django template
as you can see I have a calendar with the days and every day in which there is an action is marked, I would like that if the actions are more than 3 it is put a + instead of 4. the texts are repeated because these actions are not of a single day but have a start and end date. I need to figure out how to see the number of items for that day and I would need to do it inside the template. html code <div class="giorni"> {% for giorno in giorni %} {% if giorno == 0 %} <div></div> {% else %} <div class="single-day{% if giorno == giorno_odierno %} oggi{% elif giorno < giorno_odierno %} vecchio{% endif %}"> {{ giorno|date:"d" }} {% if integratori %} {% for dayone in integratori %} {% if giorno >= dayone.inizio and giorno <= dayone.fine %} <div class="integrazione"> <div> <img src="{% static 'img/integratori.svg' %}" class="img-fluid"> <h6 class="m-0">{{ dayone.integratore }}</h6> </div> </div> {% endif %} {% endfor %} {% endif %} </div> {% endif %} {% endfor %} </div> -
Django PostgreSQL Migration from SQLite - UnicodeDecodeError
I'm trying to migrate my db from default sqlite to postgresql. I was following this video: https://www.youtube.com/watch?v=ZgRkGfoy2nE&ab_channel=VeryAcademy I've installed postgresql, created new database downloaded my project db by using python manage.py dumpdata > datadump.json and set my setting.py like that DATABASES = { #'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', #} 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydbname', 'USER': 'postgres', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } then run python manage.py migrate --run-syncdb when I'm trying to run python manage.py loaddata datadump.json I'm getting UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 2206: invalid start byte I tried to set my json file encoding to utf-8 by using notepad++ but it did't help. I'm out of ideas. What should i do ? -
How to schedule Django shell command every week?
I'm trying to let a certain Python script run every week in the Django shell. How can I accomplish this? I've read about cron & django-rq, but I don't think this is possible within the given parameters. Thanks in advance! PS.: the code in question, it just deletes the old database and adds the updated one: from formcheck.models import FormCheck import csv FormCheck.objects.all().delete() formcheck_csv = open('PolisCheck.csv', 'r', encoding = "utf-8") reader = csv.reader(formcheck_csv) headers = next(reader, None)[1:] for row in reader: polis_dict = {} for h, val in zip(headers, row[1:]): polis_dict[h] = val formcheck = FormCheck.objects.create(**polis_dict) formcheck_csv.close() exit() -
Dynamic Ordering of Multiple QuerySets
I'm fairly new to Django and I'm currently creating a webpage that receives some context information from the url to create a tabbed bootstrap navbar (e.g., tab-example). The part I'm struggling with is how to properly populate each tab-pane with dynamic content. Dynamic content being 3 different QuerySets (displayed as lists) dependent on the information in the tab header. So far I let the view function gather all QuerySets for every tab and handed them back via the context in render() as a list of 'query_dicts' like so: query_dict = { "header": header, "data": [query_direct_hit, query_vague, query_very_vague] } Now I would like to be able to independently sort the Querysets of each header (e.g. order query_direct_hit by title, query_vague by date and preserve meta ordering in query_very_vague). I can't think of a way to do this, other then providing the view with even more context information, which would blow up the url even further. This can't be the best way to do this, right? Right now the url and view header already look as follows: path('search-entry/<search_term>/<entry_id>/<score>', views.search_entry, name='search-entry') def search_entry(request, search_term, entry_id, score): # do stuff I already saw other posts use jquery.load() or ajax, in order to only update … -
how to query from parent model to child model
I want to get all the posts created today but instead of querying from post model I want to query from the Author model. I tried this but it didn't work Author.objects.filter(post__created__date=date.today()) class Author(models.Model): #parent model name = models.CharField(max_length=200) class Post(models.Model): #child model title= models.CharField(max_length=200) description = models.TextField() author= models.ForeignKey(Author,on_delete=models.CASCADE) created = DateTimeField(auto_created=True) -
React - Django connection: Data in Heroku app lost
I am using a Django app as a backend on Heroku and a React app as a frontend at my local machine. The apps are used for creating blog posts. They have worked quite well so far. I created several posts, and these posts were seen on the server and could be retrieved for frontend. However, when I came back from the night (sleeping), these posts were disappeared. I do not know how to solve that problem. Your suggestion and explanation would be highly appreciated. Thank you. -
HOW TO RUN A LOOP 2 DIFFERENT TABLES IN DJANGO TO HTML
I am working on a project where I have a table in my HTML that gets info from 2 different tables from my database and I need to run a loop for each one. What's the best solution? VIEWS MODELS HTML -
Why html buttons dynamically created by django cannot access my javascript function?
My Django application makes divs dynamically. Each div is a post of a blog post and also I have a like button on each div. Each button will automatically turn into unlike when a user clicks on it without reloading using javascript. I wrote a javascript function for this. Unfortunately, my javascript function works only the last post on a page (As I have pagination property). document.addEventListener("DOMContentLoaded",function(){ // const colon = document.createElement('div'); // colon.setAttribute('id','colon') // e.preventDefault() // const likebtn = document.createElement('button'); // likebtn.setAttribute('class','likebtn btn btn-primary'); // likebtn.setAttribute('class','likebtn'); // document.querySelector('.card-footer').appendChild(likebtn); // document.querySelector('.likebtn').innerHTML = "Like"; document.querySelector(`#likeform${posts_id}`).addEventListener('submit',(event) => { event.preventDefault(); like_function(); // return false; }) // document.querySelector('.likepost').addEventListener('click', ()=> like_function('likepost')); }) // let is_like = "{{is_like}}"; // let num_like = "{{num_like}}"; function like_function(){ // document.createElement('button').innerHTML = "Love"; // console.log("Updated!") fetch(`/like/${posts_id}`,{ method:"POST", body : JSON.stringify({ "is_like" : is_like, "num_like" : num_like, }) }) .then(response => response.json()) .then(result => { if(result.is_like){ console.log("function is liked"); console.log(`${result.is_like} for post ${posts_id}`); let num_like = result.num_like; console.log(`Number of posts : ${num_like}`); document.querySelector(`#likebtn${posts_id}`).innerHTML = "Unlike"; num_like = num_like + 1; console.log(`Number of posts : ${num_like}`); document.querySelector(`#num_of_likes_${posts_id}`).innerHTML = `${num_like} ` // location.replace("http://127.0.0.1:8000") } else{ console.log("function is unliked, back off!"); console.log(`${result.is_like} for post ${posts_id}`); let num_like = result.num_like; console.log(`Number of posts : ${num_like}`); … -
django pytest how to test a view with argument(id)
i have a question regarding using pytest. These are my very 1st tests. I have 2 views which i want to test (simplest possible way). Views: class MenuView(View): def get(self, request): return render(request, 'diet_app/menu.html') class CuisineDetailsView(View): def get(self, request, id): cuisine = Cuisine.objects.get(id=id) recipes = cuisine.recipe_set.all() return render(request, 'diet_app/cuisine_details.html', {'cuisine': cuisine, 'recipes': recipes}) Here are my tests: def test_menu(client): url = reverse('menu') response = client.get(url) assert response.status_code == 200 @pytest.mark.django_db def test_cuisine_details_view(client): url = reverse('cuisine-details') response = client.get(url) assert response.status_code == 200 Urls: path('menu/', MenuView.as_view(), name='menu'), path('cuisine_details/<int:id>/', CuisineDetailsView.as_view(), name='cuisine-details'), 1st test (menu view) is working properly 2nd test (cuisine details view) shows error .NoReverseMatch: Reverse for 'cuisine-details' with no arguments not found. 1 pattern(s) tried: ['cuisine_details\\/(?P<id> I know i should probably put somethere ID argument but tried few options and havent succeed. Will be grateful for any help/advise -
why is group a wrong alias in postgres + Django for auth_group table
Why is that the following simple query does not work (Using Django in the backend) # select group.name from auth_group as group; ERROR: syntax error at or near "." LINE 1: select group.name from auth_group as group; while the following works # select groupd.name from auth_group as groupd; name --------------- FO Admin Role admin alice bob (4 rows) What is wrong with using group as an alias ? -
Is there a default route in case of any invalid url in django?
I am not an expert on Django. I came across for the invalid url a lot in django. is there any defualt route to be configured instead of showing nothing or showing error page while debuging. like, we might configure one route that redirects in any case of invalid url or not data found or ... Hope i explained and made my point clear. -
How to install pyodbc on Dockerfile
I'm trying to install pyodbc on Django to access Sql Server but the Docker image had no be built. I get the error: => ERROR [16/16] RUN pip install --no-cache-dir -r requirements.txt 155.7s ------ > [16/16] RUN pip install --no-cache-dir -r requirements.txt: ... #20 93.38 Building wheels for collected packages: pyodbc, dj-static, static3, django-ckeditor, odfpy, anyjson, django-celery, pyftpdlib #20 93.38 Building wheel for pyodbc (setup.py): started #20 96.49 Building wheel for pyodbc (setup.py): finished with status 'error' #20 96.49 ERROR: Command errored out with exit status 1: #20 96.49 command: /usr/local/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/setup.py'"'"'; __file__='"'"'/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-_ty0puya #20 96.49 cwd: /tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/ #20 96.49 Complete output (13 lines): #20 96.49 running bdist_wheel #20 96.49 running build #20 96.49 running build_ext #20 96.49 building 'pyodbc' extension #20 96.49 creating build #20 96.49 creating build/temp.linux-x86_64-3.8 #20 96.49 creating build/temp.linux-x86_64-3.8/tmp #20 96.49 creating build/temp.linux-x86_64-3.8/tmp/pip-install-6hbca4vm #20 96.49 creating build/temp.linux-x86_64-3.8/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138 #20 96.49 creating build/temp.linux-x86_64-3.8/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/src #20 96.49 gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPYODBC_VERSION=3.0.10 -DPYODBC_UNICODE_WIDTH=4 -DSQL_WCHART_CONVERT=1 -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/include -I/usr/local/include/python3.8 -c /tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/src/sqlwchar.cpp -o build/temp.linux-x86_64-3.8/tmp/pip-install-6hbca4vm/pyodbc_01637cbf594442cbbc4aac8a8305e138/src/ sqlwchar.o -Wno-write-strings #20 96.49 gcc: …