Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import wants to override unchanged fields
If i export to xlsx and reimport, Django-Import-Export reports overwritten fields but there are no changes. I already tried to debug this myself with the skip_row() method but i think im generally doing sommething wrong resources.py class FormatClassResource(resources.ModelResource): number = fields.Field(column_name="Nummer", attribute="number") barcode = fields.Field(column_name="Barcode", attribute="barcode") name = fields.Field(column_name="Name", attribute="name") price = fields.Field(column_name="Preis", attribute="price") class Meta: model = FormatClass use_bulk = True use_transactions = True skip_unchanged = True import_id_fields = ["number", "barcode", "name", "price"] exclude = ["id"] Import result -
How do I optimize memory and cpu usage using python
enter image description hereHow do I optimize memory and cpu consuming by these applications in python, could you provide me any article it's related I couldn't find out in Google it's related...thank you. -
How to schedule the custom management command in Django?
I need to schedule the custom management django command. I am using windows. I tried django-crontab but that's not working. Can someone please help me with this? In my_app here is the file "check_links" : check_links.py class Command(BaseCommand): help = 'Check broken links' def handle(self, *args, **options): print("function executed") -
Django Add related_name error on AbstractUser Custom model
Django shows this error when migrating SystemCheckError: System check identified some issues: ERRORS: accounts.CustomUser.groups: (fields.E304) Reverse accessor for 'accounts.CustomUser.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.groups' or 'auth.User.groups'. accounts.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'accounts.CustomUser.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'accounts.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'accounts.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'accounts.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'accounts.CustomUser.user_permissions'. It is suggesting to add related_name but I have not user any ForeignKey Field in my model, My model is inheriting from the AbstractUser models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): USER_TYPE_CHOICES = ( (1, 'CUSTOMER'), (2, 'AGENT'), (3, 'SUPERVISOR'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) -
Django - How to add multiple permissions on group?
I have a list of permissions list = ['view', 'add', 'edit'] The permissions inside the list are already saved on my table. I first clear the group's previous permission so I can insert a new one group = Group.objects.get(name='Group1') group.permissions.clear() Is there a way to add the list of permission to Group1 programmatically? -
How to present only one data with foreign key in Django?
what happens is that I am using a foreign key in a form and it is presented as a select, the thing is that all the information appears and I only want to present the name of the client, however the name, the model of the car and much more information appears to me, how can I present only one data? carros-form-add.html <div class="row mb-3"> <div class="col-md-4"> <div class="mb-3"> <label>Cliente</label> {{ form.cliente }} </div> </div> </div> carros/models.py cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) carros/models.py class Clientes(models.Model): tipo = models.CharField(max_length=200) TITLE = ( ('Mrs.', 'Mrs.'), ('Miss', 'Miss'), ('Mr.', 'Mr.'), ) corp=models.CharField(max_length=200) title= models.CharField(max_length=200, null=True, choices=TITLE,default='Mr.') name= models.CharField(max_length=200) -
In Django and DRF, why would an api route request.user return an AnonymousUser instance, while django.contrib.auth.get_user(request) return the user?
Let's take a very simple route: class Highscore(APIView): def get(request): user = request.user highscore = user.highscore return Response({"highschore":highscore}) For some unknown reason, there are cases in which request.user despite having the user authenticated and logged in (!) return an Anonymous User instance rather than the user itself. However, this can be bypassed by using get_user util function from django.contrib.auth. from django.contrib.auth import get_user class Highscore(APIView): def get(request): user = get_user(request) highscore = user.highscore return Response({"highschore":highscore}) What could be the cause of that? Important note: The user is for sure logged in. So much so that when opening the admin website in a different tab, it recognizes the correct user just from the session. If it is and admin it presents the admin content and if not if give the "you are logged in as ... but this view is reserved for admin users". -
Django-allauth links redirect
I'm using django allauth for my account management in a django project but the links tot the login, logout and register not redirecting to the appropriate pages for login, logout and register. -
I can't figure out django user registration forms
Good day! I have a problem with registering users on the site, I tried many methods viewed on the Internet, but I made something similar, but it doesn't work. I understand that this may not be a working method, or I have designed it incorrectly. Could you give me advice on how to register or fix errors in my code? Thank you in advance! Forms.py from django.forms import ModelForm, \ TextInput, \ Textarea, \ NumberInput, \ FileInput, \ PasswordInput, \ EmailInput from django.contrib.auth.models import User from .models import Recipe class FoodForm(ModelForm): class Meta: model = Recipe fields = ["recipe_title", "recipe", "recipe_time", "recipe_ingridients", "image"] widgets = { "recipe_title" : TextInput( attrs={ "class" : "title_form", "placeholder" : "Введите название рецепта" } ), "recipe": Textarea( attrs={ "class": "form_of_all", "placeholder": "Введите ваш рецепт" } ), "recipe_time" : NumberInput( attrs={ "class" : "ingr", "placeholder" : "Введите время" } ), "recipe_ingridients": NumberInput( attrs={ "class": "ingr", "placeholder": "Введите кол-во ингридиентов" } ), "image" : FileInput( attrs={ 'type' : "file", 'name' : "input__file", 'id' : "input__file" } ) } class RegisterationUserForm(ModelForm): class Meta: model = User fields = ["first_name", "last_name", "email", "password"] widgets = { "first_name" : TextInput( attrs= { "placeholder" : "Введите имя", "type" : "text", "class" … -
What would happen if I uninstall python, would my python project still work?
Let's say I created a django project with the help of virtualenv and I named my virtualenv venv, If I uninstall python from my system can I still use my project with the help of that venv? -
Full text search in MySQL in Django application
I have written Django app and I am using MySQL in it. I'd like to implement full text search but from what I see full text search is supported only for PostgreSQL. I checked many articles and answers but most of them are outdated. Is there currently any way to handle full text search in MySQL for multiple models. I am currently using Q lookups but it need to use something similar to trigram similarity or levenstein distance. -
Why does my environment variable are equal to None on github actions?
I am trying to build a CI with GitHub actions for my django app. I defined my environment variables on github in settings -> secrets -> actions. This is my ci.yaml file : # name of our workflow name: Django CI/CD Workflow # triggers for our workflow on: push jobs: health-check-job: # health check job for testing and code formatting check runs-on: ubuntu-latest # os for running the job services: postgres: # we need a postgres docker image to be booted a side car service to run the tests that needs a db image: postgres env: # the environment variable must match with app/settings.py if block of DATBASES variable otherwise test will fail due to connectivity issue. POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github-actions ports: - 5432:5432 # exposing 5432 port for application to use # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - name: Checkout code # checking our the code at current commit that triggers the workflow uses: actions/checkout@v2 - name: Cache dependency # caching dependency will make our build faster. uses: actions/cache@v2 # for more info checkout pip section documentation at https://github.com/actions/cache with: path: ~/.cache/pip … -
How to get rid of this "Upload Image Currently" in django ImageField?
I wanna show my image like this for my client, I just wanna get rid of the below "Upload Image Currently" tag. So how can I remove this? Upload Image Currently -
Python/Django - not able to run stand alone script / classes
I have a problem with running parts of script in Django as I can't get it to run the classes. The class I would like to import is this: class Location(models.Model): City = models.CharField(max_length=200) Province = models.CharField(max_length=200) Country = models.CharField(max_length=10) I have found some things when I tried to find a solution and at this point I have this: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'portal.portal.settings' import django django.setup() from portal.core.models import * When I run this, it gives an error for django.setup(): Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "C:\Users\User\Documents\Portal\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\Documents\Portal\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\Documents\Portal\venv\lib\site-packages\django\apps\config.py", line 211, in create mod = import_module(mod_path) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' 'core' is the package module where all the functions are located … -
Adding a date selector for a JavaScript chart in HTML
My chart data is based on a list of dictionaries. It's a Django project, so my data is defined in views.py: I count the number of records with Mike, Jane and Jack. mylist= [{'Date': '2021-10-02', 'ID': 11773, 'Receiver': Mike}, {'Date': '2021-10-02', 'ID': 15673, 'Receiver': Jane}, {'Date': '2021-10-03', 'ID': 11773, 'Receiver': Mike}, ... {'Date': '2021-12-25', 'ID': 34653, 'Receiver': Jack}] mike=len(tuple(d for d in mylist if d['Receiver'] == 'Mike')) jane=len(tuple(d for d in mylist if d['Receiver'] == 'Jane')) jack=len(tuple(d for d in mylist if d['Receiver'] == 'Jack')) count = [mike, jane, jack] I have already drawn a pie chart based on my total counted data in my chart.HTML file : <!-- pie Chart --> <div class="col-xl-4 col-lg-4"> <div class="card shadow mb-4"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold">Team Chart</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-area"> <canvas id="myPieChart"></canvas> <script> var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Mike", "Jane", "Jack"], datasets: [{ data: {{count}} , backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, }); </script> </div> </div> </div> </div> Instead of getting the total count, I want to draw the chart based on … -
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 ?