Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google Ads API & Python - How to get all accounts (name + ID) that a user has access
I'm trying to get the account name and ID of all the accounts that the logged user has access to. I've managed to get the IDs using the code on https://developers.google.com/google-ads/api/docs/account-management/listing-accounts?hl=es-419. But I need the names too and apparently you have to make one API call for each ID to get their account names or any other info. I've tried with the following Python (Django) code, but it's not working (it probably could be improved a lot and maybe has mistakes, I'm a Python beginner): def one(request): client = credenciales(request) ga_service = client.get_service("GoogleAdsService") # Get customer resource names from the original code customer_service = client.get_service("CustomerService") accessible_customers = customer_service.list_accessible_customers() customer_resource_names = accessible_customers.resource_names # Prepare a list to store customer data list_clients = [] # Iterate through each customer resource name for resource_name in customer_resource_names: # Extract the customer ID from the resource name custom_id = resource_name.split('/')[-1] # Create a query using the customer_id query = f''' SELECT customer_client.descriptive_name, customer_client.id, customer_client.status FROM customer_client ''' stream = ga_service.search_stream(customer_id=custom_id, query=query) for batch in stream: for row in batch.results: data_clients = {} data_clients["descriptive_name"] = row.customer_client.descriptive_name data_clients["id"] = row.customer_client.id data_clients["status"] = row.customer_client.status list_clients.append(data_clients) # Pass the list of customer data to the template context = { … -
django object.id does not work when passed in an url in html
I have just started learning Django and I cannot figure out why my player.id kills the page when I try to pass it in an url, while it does work as a variable (see both in the code below.) When I omit the player.id from the url, the page works (except for the "delete" link, of course). {% for player in all_players%} <li>{{player.player_name|capfirst}} scored {{player.player_score}} and the id {{player.id}}!</li> <div class="link" id="link"> <a href="{% url 'delete' player.id %}"> delete </a></div> {% endfor %} Here is my urls and "delete" in view: urlpatterns = [ path('first', views.first, name='first'), path('delete/int:player_id', views.delete, name='delete'), path('third', views.third, name='third'), path('second/int:player_id', views.second, name='second'), path('', views.index, name='index'), ] def delete(request, player_id): player = Player.players_objects.get(id=player_id) player.delete() return render(request, 'all_players.html', {'player': player}) -
Deploy Django app on PythonAnywhere with custom domain [closed]
I have worked on one legacy project where I have build Django backed-end website. I want to put this on PythonAnywhere server, but problem is that domain registrar provider only supports NS and not CNAME. Is there any way to deal with this so I host the web on pythonanywhere? -
Is there a way to make a https post with only port 80 in nginx config file?
So, I a have Django app which needs to send data to an API. I am using request to send the data. First, it was warning me that -in short- I am not using SSL for sending the JSON data. To solve this I added "verify=PATH TO THE CERT FILE" requests.post(url, json=payload, verify='\fullChainCert.crt') After this I got 200, so I was happy. Question is, will it work like this on server? Port 443 is open on server, but only 80 in nginx config file. -
Uploading to azure blob storage via front end
I want to allow the user to upload large files to azure blob storage.. The problem is when I do it the regular way: [Javascript HTTP POST Request (with file attached) -> django web server -> azure blob storage] the request times out.. Is there a way I can have Javascript call and upload photos to azure blob storage directly and securely and skip the django web server? -
Why the result of embedded field with Djongo is empty set
This is My Code from djongo import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: abstract = True def __str__(self): return self.name class Entry(models.Model): _id = models.ObjectIdField() blog = models.EmbeddedField( model_container=Blog, ) headline = models.CharField(max_length=255) objects = models.DjongoManager() def __str__(self): return self._id.__str__() This is My Query from generator.models import * e =Entry() e.headline='h1' e.blog={'name':'n1','tagline':"t1"} e.save() res = Entry.objects.all() #res[0].blog #{'name': 'n1', 'tagline': 't1'} res = Entry.objects.filter(blog__startswith={'name':'n'}) #res #<QuerySet []> Is the query right enter image description here The result of embedded field with Djongo query would not be empty -
Moving from Django signals to save override: How to translate the "created" parameter of a Django post_save signal for a save method override
I have made some bad decisions earlier regarding how I handle post_save events on a Django model and I am currently looking into changing my approach. Let's begin by making my example. Here is my model. class MyModel(models.Model): #... all my model creation and logic are here def do_something(self): # Actually do something, for the sake of simplifying the example, just write pass pass Now, what I am using is a receiver function like this one. It works, but for many reasons that are mine, I want to stop using signal in this case. @receiver(post_save, sender=MyModel) def foo(sender, instance, created, **kwargs): if created: instance.do_something() I imagine I could override the MyModel.save method, something like this: class MyModel(models.Model): #... def save(self): super().save() if created: # It is this line that I need to figure how to do. self.do_something() By what should I replace the if created: of my receiver function if I want to override the save() method? Or do you have something else to recommend? I would also be curious if it is the same thing for pre_save signals. -
Why is my base.html conflicting with my index.html
I have a Django blog site where I put my navbar inside the base.html at the root of the project, I also have an h3 in my index.html but the h3 just appears inside the navbar instead of stacking below the navbar. Folder structure This is my base.html This is the output](https://i.stack.imgur.com/8y9ZL.jpg)(https://i.stack.imgur.com/FJRmF.jpg) -
Django admin panel shifts to left
Just a simple question that I have no idea how to describe: Anybody knows what has happened here? -
Subtract datetimes, round result to full hour python
I am trying to calculate time between one date and another and give result in hours rounding up hours. I tried just substracting, both dates are datetime total_hours = self.valid_until - self.started_at the result is timedelta. I tried this one but it seems like it is viable for datetime field only (total_hours.replace(second=0, microsecond=0, minute=0, hour=total_hours.hour) +timedelta(hours=total_hours.minute//30)) -
After pushing my code from the production server to a gitlab repository, I have a problem with postgresql and migrations in my django webapp
Now maybe I'm getting this wrong but here's my story : Today, i decide to get the code that I've been writing in an uncontrolled manner on the production server to a gitlab repository. So I create the repository on gitlab and push my code using git init git add . git commit -m "message" git remote add origin https://gitlab.com/xxxxxx git branch -M master git push -uf origin master A few hours later I notice my django webapp is down and when i check in the error logs, it coincides roughly with the work I was doing on gitlab The error message I get is 2023-08-08 21:26:31,218: Error running WSGI application 2023-08-08 21:26:31,226: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' I reinstalled the module with pip3 install psycopg2 Then i get the error message psycopg2.errors.UndefinedTable: relation "app_pageview" does not exist LINE 1: ..."app_pageview"."url", "app_pageview"."count" FROM "app_pagev... pageview is a middleware I create to log the number of pageviews per page to the database I have a look in the database with python3 manage.py dbshell \dt and I see that there are no tables relating to the pageviews in the database So I think , maybe if I see … -
Trying to send Validation Email in django, getting error
Im trying to send validation email when creating a user in django. It used to work like that but then I did some refactoring on the URLs and used urlpattern = UrlPattern() and urlpattern.register(UserView). That is in the main django project url.py In the app url.py Im having urlpatterns = [ path('activate/<uidb64>/<token>', backend_logic.activate, name='activate') ] where activate is a function in backend_logic, which used to work and send the email to the one from request. However, now Im getting the error Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name. -
I have problem when I uploading my website in Heroku give me this error
error: subprocess-exited-with-error × Building wheel for twisted-iocpsupport (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [13 lines of output] running bdist_wheel running build running build_ext building 'twisted_iocpsupport.iocpsupport' extension creating build creating build/temp.linux-x86_64-cpython-311 creating build/temp.linux-x86_64-cpython-311/twisted_iocpsupport gcc -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -Itwisted_iocpsupport -I/app/.heroku/python/include/python3.11 -c twisted_iocpsupport/iocpsupport.c -o build/temp.linux-x86_64-cpython-311/twisted_iocpsupport/iocpsupport.o twisted_iocpsupport/iocpsupport.c:1102:10: fatal error: io.h: No such file or directory 1102 | #include "io.h" | ^~~~~~ compilation terminated. error: command '/usr/bin/gcc' 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 twisted-iocpsupport Successfully built autobahn paypalrestsdk psycopg2 pycountry Failed to build twisted-iocpsupport ERROR: Could not build wheels for twisted-iocpsupport, which is required to install pyproject.toml-based projects ! Push rejected, failed to compile Python app. ! Push failed I change Daphne package but still not working -
Any way to use CRUD TableBlock in Wagtail?
I'm talking about a table with data from a model (like Django). So that the visitor can make changes to the table fields without reloading the page. The description of the framework shows several options for developing such a solution in WAGTAIL make a snippet and link it to a table. There will be a filter option. But I still could not understand whether it is possible to make changes to the table cells without reloading. In that case, I suppose to use something like that: @register_snippet class Mapping(models.Model): map_code = models.OneToOneField('Map', models.DO_NOTHING, db_column='curr_map_code', primary_key=True) date_begin = models.DateField() class Meta: managed = True db_table = 'MAPPING' Using the STREAMFIELD add a TABLEBLOCK. the documentation says that it is based on handsontable 6.2.2 and it has the ability to make changes without rebooting page with table. But I cant achive managed to generate table data based on the Django model and possibility for user edit. That is, I can manually enter values in the cells in the admin panel. But in the custom view, there is no such possibility at all. Try to use something like that: class Mapping(models.Model): map_code = models.OneToOneField('Map', models.DO_NOTHING, db_column='curr_map_code', primary_key=True) date_begin = models.DateField() class Meta: managed … -
I need a brief explanation into how to connect my Django application to a Google Cloud MySQL database
I'm pretty new to web development and I'm currently deploying my first web application. It's pretty much built with stock Django and a few dependencies. Right now, I have it deployed on Railway.app with a very standard SQLite database. However, I would like to have my data stored in a more long term solution, so I'm looking at using MySQL inside of a Google Cloud instance. I have already tested my application using a local mySQL database, now, I'm trying to connect it to the remote one. However, I'm a bit stumped in how to do it on the Google Cloud instance. Google Cloud provides me an public IP, I have an user and password and a database created there, but that is not enough and I'd like some guidance in how to proceed from here. From what I understand, Google Cloud requires the user to access through an allowed network and I'm unsure what that means. I'm also unsure what this would look like once deployed on Railway. Google Cloud in general uses a lot of names that I don't quite understand. Do I need to use a Cloud Console to do anything? Is there anyway for me to … -
how to edit a django project?
Ive downloaded a django project, I wanna delete a feature from it, how to edit or modify the code? I know nothing about django I want to remove feature from a working code. The project is online examination system i want to remove the salary feature in it. (https://drive.google.com/file/d/1EqE4xqgp5YQKkQCwVrypxN6Hh3BR4tq1/view?usp=sharing) can anybody remove that salary feature from this? or tell me how to do it? -
Use Django Allauth with inertia.js & Vue
I'm trying to using Django Allauth with inertia + vue combination. Take a view like e.g.: from inertia import render def about(request): return render(request, "About", props={"pageName": "About"}) I have my project configured in a way that it will render this inside About.vue like so: <script setup lang="ts"> defineProps<{ pageName: string; }>(); </script> <template> <div> <h1>This is the {{ pageName }} page</h1> </div> </template> How would I go about connecting this to Django Allauth? Thinking of something like extending from e.g. their LoginView: from inertia import render from allauth.account.views import LoginView def login(request): return render(request, "Login", props={"context_obj": ?}) Not sure what I can do to pass the context object through. Anyone any ideas? -
Migrate from CharField to LocalizedCharField
I am integrating django-localized-fields and have to save current data in char field at least in default language. For example: from django.db import models class FineModel(models.Model): title = models.CharField(max_length=128) needs to migrate to from localized_fields.models import LocalizedModel from localized_fields.fields import LocalizedCharField class FineModel(LocalizedModel): title = LocalizedCharField(blank=True, null=True, required=False) and text from title column should be transferred to updated title column like that: new_obj.title.en = old_obj.title I tried to add new temporary field title_l and use 3 migrations to transfer all data from title field to title_l field delete title field rename title_l to title and delete title_l from model but this is not working, because first of these migrations will fail on production contour because title_l is not presented in FineModel. Any advices appreciated, I believe this can be done in single migration. -
How to render react images on django
After developing my react application, i decided to render it in my django using the npm run build command, which I have successfully done and it's working efficiently. But the only problem is that my images are not being rendered. Please any suggestion on how i can make django render my images. Django keeps saying this "Not Found: /images/blog/b2.webp [08/Aug/2023 17:43:02] "GET /images/blog/b2.webp HTTP/1.1" 404 3104" each time the app runs I created a static root to render all static files and also a media root for all media files. Here is the code STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'reactapp/myschool/build/static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'reactapp/myschool/build/media') -
Custom authentication backend works but doens't work with Django Rest's Token Authentication
My User model has an email field and a username field. `USERNAME_FIELD' is set to email. But I wrote an authentication backend to also support logging in using username: class UsernameAuthBackend(BaseBackend): def authenticate(self, request, email=None, password=None): try: user = User.objects.get(username=email) if user.check_password(password): return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None settings.py: AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "accounts.authentication.UsernameAuthBackend", ] This works fine but it I can't use usernames with obtain_auth_token to get a user's token. (It also doesn't work on Django's admin panel.) -
For my perceptrons, I need to know the session duration per user
For my perceptrons, I need to know the session duration per user, the visited links, etc. The issue with these two elements is that I'm having trouble; JavaScript must capture this information, and upon exiting the website, send it to Django so that my AI can aggregate them later. var centi = 0; var mili = 0; var sec = 0; var sec_; var afficher; var compteur; var reglage; function updateDisplay() { if (sec < 10) { sec_ = "0" + sec; } else { sec_ = sec; } afficher = sec_ + ":" + centi + mili; document.getElementById("time").innerHTML = afficher; } function chrono() { reglage = setInterval(function() { mili++; if (mili > 9) { mili = 0; centi++; if (centi > 9) { centi = 0; sec++; } updateDisplay(); } }, 100); updateDisplay(); } function arret() { clearInterval(reglage); document.parametre.lance.disabled = ""; document.parametre.pause.disabled = "disabled"; document.parametre.zero.disabled = ""; document.parametre.intermediaire.disabled = ""; document.parametre.rappel.disabled = ""; } function raz() { clearInterval(reglage); document.parametre.zero.disabled = "disabled"; document.parametre.intermediaire.disabled = "disabled"; document.parametre.rappel.disabled = "disabled"; centi = 0; mili = 0; sec = 0; compteur = ""; updateDisplay(); document.getElementById('presenter').style.visibility = 'hidden'; document.getElementsByName('intermediaire')[0].style.backgroundColor = 'rgba(50,205,50, 0.25)'; } function inter() { compteur = document.getElementById("time").innerHTML; document.getElementsByName('intermediaire')[0].style.backgroundColor = "orange"; } function … -
Django: TruncDate datetime retunrs always datetime
I'm using Django 3.2.12 and mysql 8.0.27 for Win64 on x86_64 (MySQL Community Server - GPL) and have this models class Anomalie(models.Model): dateajout = models.DateTimeField(auto_now_add=True, null=True) I am trying to get all Anomalie per day so I'm using this: items = Anomalie.objects.annotate(date=TruncDate('dateajout')).values('dateajout').annotate(count=Count('id')).values('dateajout', 'count') but I get this when I print items: <QuerySet [{'dateajout': datetime.datetime(2023, 7, 4, 1, 58, 15, 509978, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 7, 10, 12, 56, 9, 682396, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 7, 11, 12, 23, 54, 838830, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 7, 12, 13, 5, 38, 557618, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 8, 6, 3, 57, 31, 69749, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 8, 6, 14, 15, 38, 704047, tzinfo=), 'count': 1}]> As you can see, I always get "'count': 1", even if 2 anomalies were created on same day (2023, 8, 6)... I think it's because TruncDate returns a datetime instead of a date... I searched on many forums like https://forum.djangoproject.com/t/problem-with-count-and-truncdate/10122 or Formatting dates for annotating count in Django + Python 3 but I don't know what I'm doing wrong... Any idea please? -
customize django admin whith jquey dosent work
i have a model in my django project for phone types .I want to hide the count of phone when phone is not available . i used jquery but it dosent work and i dont now why . if u can pls help me . this is my model class PhoneModel(models.Model): phone_brand = models.ForeignKey('Brand', on_delete=models.CASCADE, verbose_name="برند") phone_model = models.CharField("مدل تلفن همراه", max_length=300 ,unique=True) price = models.IntegerField("قیمت", validators=[ MinValueValidator(0, "مقدار مورد نظر باید بیشتر از 0 باشد") ]) color = models.CharField("رنگ محصول",max_length=200) phone_size = models.IntegerField("سایز گوشی همراه", validators=[ MinValueValidator(0, "مقدار مورد نظر باید بیشتر از 0 باشد.") ]) availability = models.BooleanField("موجود", default=False) count = models.IntegerField("تعداد",blank=True, validators=[ MinValueValidator(0, "مقدار مورد نظر باید بیشتر از 0 باشد") ]) country = models.CharField("کشور", max_length=300) def __str__(self): return self.phone_model class Meta: db_table = 'phone' verbose_name = 'گوشی' verbose_name_plural = 'گوشی ها' this is my jquery code: (function($) { $(document).ready(function() { var $availability = $('#id_availability'); var $count = $('#id_count'); function toggleCharFieldVisibility() { if ($availability.is(':checked')) { $count.parent().show(); } else { $count.parent().hide(); } } toggleCharFieldVisibility(); $availability.on('change', toggleCharFieldVisibility); }); })(django.jQuery); and at last this is my admin.py: @admin.register(PhoneModel) class PhoneAdmin(admin.ModelAdmin): list_display = ["phone_model", "phone_brand"] class Media: js = ("phone/js/custom_admin.js",) i found this jquery code from web and dont now few … -
`no tests ran` in Pytest in Django
I have test1_ex.py in tests/ as shown below. *I use Pytest in Django: django-project |-core | └-settings.py |-my_app1 |-my_app2 |-tests | |-__init__.py | |-conftest.py | └-test1_ex.py # Here |-pytest.ini ... And, this is pytest.ini: # "pytest.ini" [pytest] DJANGO_SETTINGS_MODULE = core.settings python_files = test_*.py And, there is fixture1() in tests/conftest.py as shown below: # "tests/conftest.py" import pytest @pytest.fixture def fixture1(): print('fixture1') And, there is test1() in tests/test_ex1.py as shown below: # "tests/test_ex1.py" import pytest def test1(fixture1): print('test1') Now, I ran the command below: pytest -q -rP Then, I could run test1() as shown below: $ pytest -q -rP . [100%] ============================================ PASSES ============================================ ____________________________________________ test1 _____________________________________________ ------------------------------------ Captured stdout setup ------------------------------------- fixture1 ------------------------------------- Captured stdout call ------------------------------------- test1 1 passed in 0.11s Next, I put test1_ex.py in tests/test1/ as shown below: django-project |-core | └-settings.py |-my_app1 |-my_app2 |-tests | |-__init__.py | |-conftest.py | └-test1 | |-__init__.py | └-test1_ex.py # Here |-pytest.ini ... But, I could not run test1() as shown below: $ pytest -q -rP no tests ran in 0.10s So, how can I run test() in tests/test1/? -
Django Validation not working, prevent whitespace only
So I'm creating a blog project using Django. The user has the ability to comment on a blog post, edit and delete etc. I want to provide an error if a user tries to enter an empty comment. If the comment contains just whitespaces, or perhaps they click on the submit button without any comment at all. In my forms.py I added the clean_body function as per django documentation. They also mention using '{{ form.non_field_errors }}' in my Template which I've included. Does 'forms' need to be replaced with the form name from forms.py? Now when I load the blog post, the comment field instantly says 'This field is required' and also if I put a comment with whitespaces, the page will refresh and the same 'This field is required' is displayed instead of the unique error message I have added. Finally to add, I have put 'from django.core.exceptions import ValidationError' in my forms.py file. HTML <div class="card-body"> {% if user.is_authenticated %} <h3>Leave a comment:</h3> <p>Posting as: {{ user.username }}</p> <form id="commentForm" method="post" style="margin-top: 1.3em;"> {{ comment_form | crispy }} {{ form.non_field_errors }} {% csrf_token %} <button id="submitButton" type="submit" class="btn btn-primary primary-color btn-lg">Submit</button> </form> {% else %} <h3>Log in or …