Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Django Forms and models (Enter a valid URL.)
My idea is to get a img from the user using the form (it can be local on her computer) and after the form is sent the system upload it to imgBB. The problem is that the form is not valid, because it says "Enter a valid URL.". class FeriaForm(forms.ModelForm): #... Others fields image = forms.URLField( label="", widget=forms.ClearableFileInput(attrs={'class': 'form-input'}) ) class Meta: model = JobFair fields = [ 'title', 'description', 'start_event_date', 'end_event_date', 'start_hour', 'end_hour', 'department', 'city', 'direction', 'maximum_capacity', 'is_visible', 'keynote_speaker', 'image' ] This model JobFair class JobFair(models.Model): organizer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='job_fairs', null=True) title = models.CharField(max_length=255) description = models.TextField() start_event_date = models.DateField() end_event_date = models.DateField(null=True) department = models.CharField(max_length=255) city = models.CharField(max_length=255) start_hour = models.TimeField(auto_now=False, auto_now_add=False) end_hour = models.TimeField(auto_now=False, auto_now_add=False, null=True) maximum_capacity = models.IntegerField(null=True) number_of_registered = models.IntegerField(default=0, null=True) is_visible = models.BooleanField(default=True) direction = models.CharField(max_length=255) keynote_speaker = models.CharField(max_length=255) image = models.URLField(blank=True, null=True) and this view where I used the form. def add_fair_view(request): if request.method == 'POST': form = FeriaForm(request.POST, request.FILES) # Manejar datos y archivos if form.is_valid(): image_file = request.FILES.get('image') # Obtener el archivo de la imagen # Subir el archivo a ImgBB try: response = requests.post( IMGBB_API_URL, data={'key': config('IMGBB_API_KEY')}, files={ 'image': (image_file.name, image_file.file, image_file.content_type) } ) response_data = response.json() if response.status_code … -
DRF issue while attempting to inspectdb command error appears: # The error was: ORA-00904: "USER_TABLES"."DEFAULT_COLLATION": invalid identifier
I have an Oracle database version 11.5.10.2. Recently, I study DjangoRestFramework in order to perform own APIs. Firstly, command python manage.py runserver doesn't work due to unable to connect to database. Then I imported oracledb module to settings.py file and added following command: oracledb.init_oracle_client(lib_dir=r'C:\\oracle\\instantclient_23_6') Without client no any connection appears for Oracle database. After that command 'python manage.py runserver' does connect to Oracle DB without errors. Since I don't need to do any changes in database due to many finance records I would upload models structure for my necessary tables only for API use GET HTTP method protocol. So, not at all tables are need to be inspected and moved to models.py file. Thus, for testing I add following command im command prompt: 'python manage.py inspectdb ap.ap_invoices_all' and output text is following: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # \* Rearrange models' order # \* Make sure each model has one field with primary_key=True # \* Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # \* Remove `managed = False` lines if you wish to allow Django to create, modify, and … -
Google Picker popup window not loading - Django
I am using Google's documentation on the Google Picker at https://developers.google.com/drive/picker/guides/sample and the popup for google drive is not opening when i use this code in django template. I authorize my gmail account but the popup is just not loading. It works fine when i run it via live server on a plain html ( so everything is setup good regarding API_KEY, CLIENT_ID and APP_ID ) but when i run the code inside django, the popup is not there. I tried 3 different (django) projects and the issue persists. Google console is not showing any errors, nothing, it's blank. I do see that APIs return 200 message, so i suspect something about Django is not working well. Cookies or whatever it can be, but i spent past several hours on this and can't find a solution -
How to persist model changes for specific models on transaction rollback in django atomic request
I have a Django project with ATOMIC_REQUESTS=True. When authentication fails I need to store critical data for the login attempt, here is example code: class LoginSerializer(serializers.Serializer): ... def validate(self, data): ... user = authenticate(email=email, password=password) if user is None: failed_login_attempt(email) raise serializers.ValidationError("Invalid credentials") def failed_login_attempt(email): user = User.objects.get(email=email) user.lock_status = "LOCKED" user.save() Device.objects.create(user=user, ip="127.0.0.1", fingerprint="some-fingerprint") Activity.objects.create(user=user, type="failed_login_attempt") Constraints: Raising the ValidationError causes all changes (including updates to user.lock_status, Device and Activity) to be rolled back. This behavior is expected because of the global transaction but I need these changes to persist. I cannot remove ATOMIC_REQUESTS=True as it's crucial for other parts of the application. Goal: I want to ensure that the failed_login_attempt function persists changes even if the ValidationError rolls back the rest of the transaction. What’s the best way to persist those critical changes? What I've tried: Wrapping failed_login_attempt in transaction.atomic() This doesn’t work because they are still part of the outer transaction. Bypassing the ORM and using raw SQL connections.cursor() feels like a hack so I would prefer to avoid it. -
Single 'through' model for multiple m2m fields
I'm trying to extend and refactor some legacy project. I have some set of models which represent "hardware" of some assebled device. Something like : class ComponentA(models.Model) brand = models.CharField() model = models.CharField() category = models.ForeignKey(Category) class Configuration(models.Model): component_a = ForeignKey(ComponentA) component_b = ForeignKey(ComponentB) component_n... class Device(models.Model): configuration = models.ForeignKey(Configuration) The goal is to extent ComponentA...ComponentN with Many2Many field which suppose to contain some extra parts and those parts quantity it consist of. However I found it weird to have through model for each Component model. All of the Component models shoud have a quantity for further statistic/calculations. Is there is some "clean" approach for implementation such a functionality? -
Firebase Push Notifications are not received in Django template but working in other external applications
I have a major problem with Firebase push notifications. I have a Django application with a configured function to send notifications. The function works for sending notifications to a mobile app and a separate React app. However, recently there has been a need for notifications to also reach the same application in Django - meaning the server sends a notification, and the template receives and displays an alert. I configured everything as per the documentation, and notifications are received when they originate from the Firebase console, but those sent from my server are completely ignored and not received. Where should I start looking for the issue? Let me add that sending notifications does not throw any errors. I’m out of ideas on what to do. -
Want to integrate onlyoffice text editor in my project
I used React in frontend and django in bbackend want to use onlyoffice text editor i used docker container and follow the steps after running in frontend i got pop up message that the document security token is not correctly formed .please contact your Document Administrator. I'll try to create api and then integrate in frontend but got that message -
Django Site Stopped Working After SSL Certificate Renewal: "No Patterns in URLconf"
I have a Django site that was deployed and functioning properly. However, after the SSL certificate expired, I tried to set up a free certificate. Since then, my site no longer works on the server, but it continues to run fine in the local environment. When running the server, I encounter the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'homepage.urls' from '/home/omar/Dizeta/homepage/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. here's the code urlpatterns in urls.py for more informations : from django.urls import path from • import views #if settings. DEBUG: urlpatterns=[ path('' ,views.homepage, name-'homepage'), path( ' about.php' ,views.about, name= 'about.php*), #path( 'blog_single' ,views.blog_single, name='blog_single'), path(' cataloghi' ,views cataloghi, name-'cataloghi'), path( 'servizi-php', views servizi, name-'servizi'), path( 'prodotti' ,views-prodotti, name='prodotti'), path(' antincendio-php', views-antincendio, name-'antincendio'), path( 'pompieristica' ,views-pompieristica, name-'pompieristica'), path( 'home-php', views tornahome, name-'tornahome*), path ('pagecataloghi' ,views pagecataloghi, name= 'pagecataloghi'), path(' segnaletica-php' ,views- segnaletica, name='segnaletica'), path( 'antinfortunistica.php" ,views.Calzature_e_abbigliamento,name=Calzature_e_ path('Pronto _soccorso', views.Pronto_soccorso, name-'Pronto_soccorso*), path( 'principalehomepage' , views -principalehomepage, name='principalehomepage'), path( 'Porte_tagliafuoco' ,views.Porte_tagliafuoco, name= 'Porte_ tagliafuoco"), path( 'Dispositivi di_protezione_individuale', views.Dispositivi_di protezione_inc path( 'board2/< int: board2_id>/',views.board2, name= 'board2'), ] anyone know what's … -
I can't get rid of CSRF checks
First of all, I know how necessary csrf is and what disasters will happen to me if I don't use it, I have read enough about it. I want to disable csrf checks by taking all kinds of risks. I have a backend using django rest framework and jwt authentication, I installed gunicorn and nginx on the server. No matter what I do <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.</p> I can't get rid of this error. Even removing all middleware didn't work. Please help, I want to get rid of CSRF. What should I do? -
Trying to finish scrape specific data from websites for my Solr search engine for my Django project
I am trying to finish the backend (Django) of my Solr search engine. I defined my fields in search_indexes.py, created my Solr core, configured my schema.xml and rebuilt my index. A little backstory to my search engine. The vertical search engine will be focused on homeowners searching for local arborists (tree services) by putting in queries. The documents with the fields I have created and indexed are company name, types of services, reviews etc…. So in order for me to finish the search engine, I need to scrape some data from arborist websites, that is company names, reviews, types of service. From my basic understanding of web scraping/indexing, I have to follow these steps to accomplish this. Send GET requests to url’s -- parsing the raw HTML data with BeautifulSoup to find elements/tags that contains the desired data -- save it in a JSON file -- indexing via Solr. The company name is inside 'meta_tag = soup.find('meta', attrs={'name': 'description'})', reviews is inside '' and types of services is inside of the website HTML/JSON structure. Now I have created the files in my Django project: scrape.py, parser.py, save_json.py and solr_index.py to perform these four tasks. So I would have to split … -
Django-paypal form is not showing "pay with credit or debit card" option
I am using django-paypal package to integrate PayPal to my django site. All works fine but there is a problem. The PayPalPaymentsForm is not showing "pay with credit or debit card" option. User can pay only with PayPal account. I am using the next code to render the payment form: def process_payment(request): price = request.GET.get("price") or 0 paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': str(price), 'item_name': 'refill amount', 'item_number': str(request.user.id), 'invoice': get_timestamp_uid(request.user.id), 'currency_code': 'USD', 'notify_url': f'{BASE_URL}{reverse("paypal-ipn")}', 'return_url': f'{BASE_URL}{reverse("paypal_payment:success_payment")}', 'cancel_return': f'{BASE_URL}{reverse("accounts:user-profile")}', } form = PayPalPaymentsForm(initial=paypal_dict) context = { 'form': form } return render(request, 'paypal_payment/process_payment.html', context) The result is demonstrated below: But I want to have a form with credit/debit card option as is showed below: So, what can I do in this situation? I have also tried to set to "On" the option "Website Payment Preferences -> PayPal Account Optional" in my PayPal sendbox account but it hasn't helped. -
VS Code Testing - creating testing profiles to run different options
I am using pytests with python-django in VS Code. I just discovered that there is an option to select a Default Profile in VS Code's Testing tab. Not sure how this was enabled. Are there any documentations to add a profile? I couldnt find anything online. If I add a new profile, will it allow me to switching between pytests options easily (i.e. --reuse-db). -
Triggering Stripe Events Results in 401 Unauthorized in Django using JWT
I am integrating stripe into a django project and am receiving a 401 unauthorized for every attempt to contact my webhook endpoint by stripe. This problem may have arisen as a result of my switching to JWT, from traditional REST authentication. Thank you all for your help and please let me know what other information I can provide that would be of help. When I run the following command I receive the errors below. Please let me know if there is anything you can do, I have searched far and wide for days on end in an attempt to solve this problem. Thank you. stripe trigger invoice.payment_succeeded 2024-12-02 20:46:06 --> customer.created 2024-12-02 20:46:06 <-- [401] POST http://localhost:8000/collect-stripe-webhook/ Here is the endpoint in question: @csrf_exempt @api_view(\['POST'\]) @authentication_classes(\[\]) # Disable authentication @permission_classes(\[AllowAny\]) # Allow any request def collect_stripe_webhook(request): webhook_secret = os.getenv('STRIPE_WEBHOOK_SECRET') signature = request.META.get("HTTP_STRIPE_SIGNATURE") payload = request.body try: # Verify Stripe webhook signature event = stripe.Webhook.construct_event( payload=payload, sig_header=signature, secret=webhook_secret ) except ValueError: return JsonResponse({'error': 'Invalid payload'}, status=400) except stripe.error.SignatureVerificationError: return JsonResponse({'error': 'Invalid signature'}, status=400) # Process the event print(f"Webhook received: {event['type']}") return JsonResponse({'status': 'success'}) Please find below some lines from settings.py ALLOWED_HOSTS = [] #CSRF ALLOWED_HOSTS = [ '127.0.0.1', 'localhost'] CORS_ALLOW_ALL_ORIGINS = … -
How should i deploy my full stack app. 2 different git repos or 2 different azure app services
So I'm am in charge of the frontend with angular of this webapp while someone else does the backend with django. I am trying to implement CI/CD and deploy this app to azure using github actions but I dont really know how to do this efficiently. I created a github repo and initialized the frontend and backends folders seperately and pushed the code to a dev branch in my git repo then created an azure account and created a resources-gp and also 1 azure app service and connected my github repo to it and selected python as workflow and it was connected but in my github repo i see this error: Github error Github same error And here the frontend and backend are all in one repo but when creating the workflow i specified just python i assume that was just for the backend but even though i still see this errors above. Can someone help me out here please? -
Django model form widget not renderiing
Framework – Django. I am trying to create a contact form with input field attributes. I have a problem with the first field "name". The second to fourth fields come out perfectly in html. Here is my models.py: from django.db import models class md_contactalpha(models.Model): name = models.CharField(max_length=100, verbose_name='Name',null=False, blank=False ) email=models.EmailField(max_length=100,verbose_name='Email', unique=True,null=False,blank=False) phone = models.CharField( max_length=15, verbose_name='Phone',null=True,blank=True) message = models.CharField(max_length=512,verbose_name='Message', null=True, blank=True, ) def __str__(self): return self.name Here is the forms.py file: from django import forms from .models import md_contactalpha class fm_contactalpha(forms.ModelForm): class Meta: model = md_contactalpha fields = ('name', 'email', 'phone', 'message') widgets = { 'name':forms.TextInput(attrs={'class':'input_text', 'placeholder': 'Full Name'}), 'email':forms.EmailInput(attrs={'class':'input_text'}), 'phone':forms.TextInput(attrs={'class':'input_text'}), 'message':forms.Textarea(attrs={'class':'message_box','rows':5}), } Here is the html file: <form method="post"> {% csrf_token %} <form method="POST"> {{ form.as_p }} </form> <button type="submit">Send Message</button> As mentioned the last 3 fields work perfectly. The “name” field does not fill any from the widget and produces this - <input type="" class= placeholder="Name" name="Name"> &lt;django.forms.fields.CharField object at 0x7fb2ea920ce0&gt; I have checked other posts on the subject of widgets but there seems to be no answer for why one field called name should have a problem. I would greatly appreciate any assistance. Thank-you. -
Django-SES: how do I receive emails?
I am learning how to send emails using Django-SES. There are good tutorials out there for sending emails. However, I have found very little on how to receive emails using a Django App on AWS. Can someone point me to any documentation/tutorial on how to process inbound emails using Django on AWS? Thank you very much! -
Django local development with uvicorn
It's possible to add ASGI support to python manage.py runserver, so the local development server, by installing daphne and adding it to INSTALLED_APPS. See docs here. This is how the result looks: System check identified no issues (0 silenced). December 02, 2024 - 20:50:29 Django version 5.0, using settings 'contractscounsel.settings' Starting ASGI/Daphne version 4.1.2 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Is it possible to do the same, but with uvicorn instead of daphne? -
zsh killed when python manage.py runserver
Earlier I've been working on Macbook with Intel. Recently I started to work on Macbook with M3. I have a Django application. On Intel it started. On M3 I receive error: As you could see there are no details. So how or where can I get some details about error? -
How to deploy django webapp on plesk, ubuntu
I would like to know how to deploy the Django web app on the Plesk panel. -
Automatic tenant name generation in django
A bit of preface first. I'm building a multi-tenant consumer facing application using Django/DRF. I'm (trying) not to use any 3rd party package for the multi-tenancy part. Instead I simply made a Tenant model that has a OneToOne field in the User model, so that there is a main tenant's table where all other tables have a foreign key pointing to it. Something like this: class Tenant(models.Model): tenant_id = f'{models.UUIDField(primary_key=True, default=RandomUUID, editable=False)}' tenant_name = models.CharField(max_length=255, default=get_user_email()) # How? class UserAccount(AbstractBaseUser, PermissionsMixin): tenant = models.OneToOneField(Tenant, on_delete=models.CASCADE) user_id = f'{models.UUIDField(primary_key=True, default=RandomUUID, editable=False)}' first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True, max_length=255) So then I tried to create function in models.py in the Tenant app that would return the user's email and then use that as a callable for a default value in tenant_name like so: from users.models import UserAccount def get_user_email(): return UserAccount.user.email class Tenant(models.Model): tenant_id = f'{models.UUIDField(primary_key=True, default=RandomUUID, editable=False)}' tenant_name = models.CharField(max_length=255, default=get_user_email()) But when I go to run makemigrations, it tells me that it cannot import UserAccount from user.models (most likely due to a circular import). So, am I on the right track? How do I avoid circular imports? -
Serializer validation error message not getting translated
I have defined a unique together validator with coressponding error message, but it's not getting translated. Here is the code: from django.utils.translation import gettext_lazy as _ class CollectionSerializer(serializers.ModelSerializer): uuid = serializers.UUIDField(read_only=True) products = ProductSerializer( many=True, read_only=True, ) category = CategoryRelatedField() class Meta: model = Collection fields = ["name", "products", "category", "uuid"] validators = [ serializers.UniqueTogetherValidator( model.objects.all(), fields=("name", "category"), message=_("This information already exists!"), ), ] The .po file is correct and I have compiled it. The active language is correct. Also messages responded by django itself is in correct language. I have no idea what to check furthur. -
Django Query API select_related in multi-table count query
Imagine I'm trying to count the number of tree cultivars in a certain park, and the trees are grouped in specific fields within the park. One catch is that trees can be replanted, so I want to count only existing trees and empty locations (removed IS NULL for trees currently planted, and the LEFT and RIGHT JOIN for locations not yet planted). After wandering through lots of Django select_related posts and documentation, I cannot see how to do this through Django's Query API. I have the park ID, so I'd be doing this starting with the Parks model in views.py. Am I missing something obvious (or not obvious) in Django's Query API? The following SQL does what I'd like: WITH p AS ( SELECT t.cultivar, l.id AS loc FROM trees t JOIN locations l ON t.location = l.id JOIN fields d ON l.field = d.id WHERE d.park = 'SOME_PARK_ID' AND t.removed IS NULL ) SELECT c.name, count(*) FROM p LEFT JOIN cultivars c ON p.cultivar = c.id RIGHT JOIN locations l ON p.loc = l.id GROUP BY name; For example: +--------+-------+ | name | count | |--------+-------| | <null> | 2 | | HGG | 2 | | BOX | … -
Django-TailwindCSS staticfile distribution not working
I am using the Django-Tailwind library. (https://django-tailwind.readthedocs.io/en/latest/index.html) Everything during development on my local machine works fine, i.e. all the styles are shown. But when I go to deploy it on my digital ocean droplet, no tailwindcss styling is shown at all. As per documentation, before deployment I ran python manage.py tailwind build and built the tailwind style file. I then did python manage.py tailwind collectstatic to collect the style file. It is thus stored in staticfiles/css/dist/styles.css . This is what the relevant code in my settings.py file looks like: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', "whitenoise.runserver_nostatic", 'tailwind', 'theme', "django_browser_reload", ... ] STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles/") STATICFILES_DIRS = [BASE_DIR / "static" ] TAILWIND_APP_NAME = 'theme' Does anyone have a clue as to what is happening? -
pytest-django: Model class sites.models.Site doesn't declare an explicit app_label
There have been lots of similar questions, but most of them are irrelevant to pytest. Running manage.py runserver works correctly for me, it only fails with pytest. When running pytest --collectonly --verbose -n0, pytest fails with the following error: ============================= test session starts ============================== platform linux -- Python 3.12.6, pytest-8.3.3, pluggy-1.5.0 -- /home/jasongrace2282/repos/website5/.venv/bin/python3 cachedir: .pytest_cache django: version: 5.1.3, settings: director.settings (from ini) rootdir: /home/jasongrace2282/repos/website5/manager configfile: pyproject.toml testpaths: director plugins: django-4.9.0, anyio-4.6.2.post1, xdist-3.6.1 collecting ... collected 1 item / 1 error <Dir manager> <Package director> <Dir apps> <Package auth> <Module tests.py> <Function test_password_login> Make sure logging in via password on the dev env works. ==================================== ERRORS ==================================== ________________ ERROR collecting director/apps/sites/tests.py _________________ director/apps/sites/tests.py:3: in <module> from . import parser director/apps/sites/parser.py:6: in <module> from .models import DockerAction, DockerImage, Domain director/apps/sites/models.py:39: in <module> class Site(models.Model): ../.venv/lib/python3.12/site-packages/django/db/models/base.py:134: in __new__ raise RuntimeError( E RuntimeError: Model class sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. =========================== short test summary info ============================ ERROR director/apps/sites/tests.py - RuntimeError: Model class sites.models.S... !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! ====================== 1 test collected, 1 error in 0.17s ====================== My director/apps/sites/apps.py looks like: class SitesConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "director.apps.sites" And my settings.INSTALLED_APPS has the … -
How to apply filters to searchbar generated with Datatables on Django?
I am trying to add filters to the search bar but I am alittle lost, I would like the filters to make it easier to search in the different columns (Such as, Sku, Name, Cost, Price and weight). As you can see I already have a filter and that one is perfect because it filters the name of the tables the information is being get from. I have problems creating the search bar filter and attach it to the existing searchbar. I will paste the code for the html and the views.py: product_list.html: {% block content %} <h1 class="text-center" style="font-size: 3rem; font-weight: 600; color: #004080; margin-top: 1px; margin-left: 830px"> Database </h1> {% if user.is_authenticated %} <a href="{% url 'user_logout' %}" style="position: absolute; top: 20px; right: 20px; text-decoration: none; background-color: #004080; color: white; padding: 10px; border-radius: 4px; text-align: center; width: 80px;"> Logout </a> <a href="{% url 'add_product' %}" style="display: block; margin-bottom: 10px; text-decoration: none; background-color: #004080; color: white; padding: 10px; border-radius: 4px; text-align: center; width: 150px;">Add Product</a> {% endif %} <link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script> <script> $(document).ready(function() { $('#product-table').DataTable({ paging: true, searching: true, ordering: true, info: true, responsive: true, pageLength: 25, lengthMenu: [5, 10, 25, 50, 100] }); }); …