Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Keep specific fields on form after submit
I have a view that has a simple "save and add another" functionality, that redirects the user to the same page after submit the form. View: def new_planning(request): form = PlanningForm(request.POST) if form.is_valid(): form.save() if 'another' in request.POST: messages.success(request, ('Success!')) return redirect('new_planning') else: return redirect('list_planning') return render(request, 'pages/planning/new_planning.html', context={ 'form': form, }) Form: class PlanningForm(forms.ModelForm): accountplan = ModelChoiceField( queryset=AccountsPlan.objects.filter(active=True).order_by('code'), ) month = forms.DateField( required=True, error_messages={'required': '', }, ) amount = forms.DecimalField( max_digits=9, decimal_places=2, required=True, validators=[ error_messages={'required': '', }, ) class Meta: model = Planning fields = '__all__' The function works as expected and after the submit, the same page is rendered with a blank form. What I want is to keep just the "amount" field blank and keep the data typed in the "accountplan" and "month" fields. Is there a way to do this? I read about instance in the docs, but it doesn't seem to be what I looking for, since I don't want to get the data from the database (if that's possible), but simply keep the last inputs typed in both fields. -
DJANGO - How can i make the statics folder accessible on deploy
in the admin screen, I can access CSS and JS files by typing their url locally but i can't when it is deployed. this is how it works locally this is how it works deployed Online it takes me to the 404 screen while locally it returns the raw file (as i am trying to do) these are my settings for static files in Settings.py STATIC_URL = 'guias/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'guias/static') thanks everyone :D -
Django ._meta and adding to ManyToMany fields
I haven't had much luck finding other questions that helped with this, but apologies if I missed something and this is a duplicate. I'm trying to add to some ManyToMany fields, without having to explicitly type out the names of the fields in the code (because the function I'm working on will be used to add to multiple fields and I'd rather not have to repeat the same code for every field). I'm having a hard time using ._meta to reference the model and field objects correctly so that .add() doesn't throw an "AttributeError: 'ManyToManyField' object has no attribute 'add'". This is simplified because the full body of code is too long to post it all here, but in models.py, I have models defined similar to this: class Sandwich(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) veggies = models.ManyToManyField(Veggie) meats = models.ManyToManyField(Meat) class Veggie(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) class Meat(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) Once instances of these are created and saved, I can successfully use .add() like this: blt = Sandwich(name='blt') blt.save() lettuce = Veggies(name='lettuce') lettuce.save() tomato = Veggies(name='tomato') tomato.save() bacon = Meat(name='bacon') bacon.save() blt.veggies.add(lettuce) blt.veggies.add(tomato) blt.meats.add(bacon) But if I try to use ._meta to get blt's fields and add to them that way, I … -
Django signals don't work with DEBUG=False
I have the following code that work fine in development mode with DEBUG=True. In a nutshell - signal should invalidate a cache. The project running Django 4.0, Python 3.9. signals.py from django.core.cache import cache from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from apps.hub.models import Comment, Marker @receiver(signal=post_delete, sender=Marker, dispatch_uid="marker_deleted") def clear_cache_delete_handler(sender, **kwargs): """Method for clearing a cache on home page after Marker instance has been deleted.""" cache.delete("markers_frontend") @receiver(signal=post_save, sender=Marker, dispatch_uid="marker_updated") def clear_cache_save_handler(sender, **kwargs): """Method for clearing a cache on home page after Marker instance has been updated.""" cache.delete("markers_frontend") I connect them in apps.py from django.apps import AppConfig class HubConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apps.hub' def ready(self): """Register all signals.""" # Implicitly connect a signal handlers decorated with @receiver. from . import signals But whether I set DEBUG=False, signals don't work and as a result cache is not invalidates. I tried both - local machine and a hosting server. Result is the same. What is wrong? -
Django doesn't redirect to the same page
I'm working on a django project website. When submitting a form I need to save the data and show a message with from django.contrib import messagesmodule. It works perfectly with saving data but it never shows the message and redirecting to the same page. Views.py class. def showIndex(request): if request.method == 'POST': contact = Contact() name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') contact.name = name contact.email = email contact.message = message print('yes and no ') messages.success(request, 'Profile details updated.') contact.save() return render(request,'index.html') return render(request,'index.html') and this is the codes in index.html. I have created the form here. <form method="POST" class="u-clearfix u-form-spacing-30 u-form-vertical u-inner-form" style="padding: 10px"> {% csrf_token %} <div class="u-form-email u-form-group u-form-partition-factor-2"> <label for="email-319a" class="u-label u-text-body-alt-color u-label-1">Email</label> <input type="email" placeholder="Enter a valid email address" id="email-319a" name="email" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" /> </div> <div class="u-form-group u-form-name u-form-partition-factor-2"> <label for="name-319a" class="u-label u-text-body-alt-color u-label-2">Name</label> <input type="text" placeholder="Enter your Name" id="name-319a" name="name" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" /> </div> <div class="u-form-group u-form-message"> <label for="message-319a" class="u-label u-text-body-alt-color u-label-3">Message</label> <textarea placeholder="Enter your message" rows="4" cols="50" id="message-319a" name="message" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required=""></textarea> </div> <div class="u-align-left u-form-group u-form-submit"> <a href="#" class="u-btn u-btn-submit u-button-style u-white u-btn-2">Submit</a> … -
How to access return value from apscheduler in a long process function?
Similar topic has been asked before, but my question is different. I want to get the fisrt function's return as a signal to trigger the second function, and the first function need run 2 minutes before it completed. def first_func: #long time run logic here #then has a return return signal def second_func: if 'success string' in signal: #do something def scheduler_func(request): try: scheduler = BackgroundScheduler() # Schedule the load process scheduler.add_job(first_function) scheduler.start() return render(request, 'customer/customer_base.html') except: pass finally: second_func() I have tried use global signal,but the second function not able to get the signal. -
Django ModuleNotFoundError: No module named 'fcm-django' error
I am trying to set up Firebase Cloud Messaging with my Django Rest Framework Backend for sending push notifications, however I keep getting ModuleNotFoundError: No module named 'fcm-django' error when I run python manage.py migrate I have already installed fcm-django using pip install fcm-django This is the error: Traceback (most recent call last): File "C:\Users\Admin\Desktop\DigiLab-Back-End\manage.py", line 22, in <module> main() File "C:\Users\Admin\Desktop\DigiLab-Back-End\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\apps\config.py", line 228, in create import_module(entry) File "C:\Program Files\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 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'fcm-django' This is what I have done in my Settings.py to integrate FCM from firebase_admin import initialize_app INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Profiling.apps.ProfilingConfig', 'Appointments.apps.AppointmentsConfig', 'Chattings.apps.ChattingsConfig', 'Finance.apps.FinanceConfig', 'Feedbacks.apps.FeedbacksConfig', 'Inventory.apps.InventoryConfig', 'Settings.apps.SettingsConfig', 'Authentication.apps.AuthenticationConfig', 'fcm-django', 'rest_framework', 'corsheaders', ] FIREBASE_APP = initialize_app() FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "test", # true if you want to have only one … -
Why is Django test throwing an error complaining about a column size that is incorrect when I try to run tests?
I have an old project that I'm resurrecting that was built with Python 2. I'm getting it going with a more current version of Python and Django (v3.9 and v4.1.2 respectively). I have the app basically up and running and I just tried to get the automated testing going. But I'm getting this error: django.db.utils.OperationalError: (1074, "Column length too big for column 'body' (max = 16383); use BLOB or TEXT instead") Unfortunately, I have the 'body' column in multiple objects in my models.py, AND each of them is defined as a TextField (e.g. body = models.TextField()). I'm not sure how to post the offending code since the error doesn't specify the exact object. My test is simple as I'm just trying to get testing going: from django.test import TestCase class Test_Countries(TestCase): def setUp(self): pass def test_basicCompare(self): self.assertEqual(1, 1) Before running the test (python manage.py test IFSServices/tests), I've ensured that makemigrations and migrate have succeeded. Any help that anybody could provide to help (incl how to ask a more useful question) would be greatly appreciated. -
django filter: How to filter results with multiple values
I am working on Django and I need to filter records eg: table: Person name age David Abraham Benj 18 so, if I run this, Person.objects.filter(name__icontains="David Abraham") it is working but if I run this, Person.objects.filter(name__icontains="David Benj") it is not working any idea how it works? framework: Django and SQL: Postgres -
Django huey file not processing all tasks
This is very strange. I don't want to setup a Redis service and since my queue has only very little requirements file or sqlite would work just fine. The both work fine on localhost, but when I deploy it to a docker container there are the following issues: SQLite compains that there is an I/O error. The path is set to /tmp, which has read/write permissions. I read that there are issues with CIFS filesystem, not sure if this is the case. Fact it, it doesn't work. Filesystem queue. Tasks are created in the folder, the consumer is starting to process them, but then just stops. Consumer is still running, but not processing any files anymore. Any advice on where to start looking would be appreciated. -
DJango-How to merge two variables together and send them as an argument to the url?
url: 127.0.0.1:8000/name/ url has one parametr, name but name is first_name + last_name in template we resive first_name and last_name How to merge two variables (first_name and last_name) together and send them as an argument (name) to the url??? -
Annotate results from related model method onto model Queryset?
I'm trying to figure out the best / most efficient way to get the 'progress' of a Summary object. A Summary object has X Grade objects - a Grade object is_complete when it has a Level chosen and has 1 or more related Evidence objects. I am trying to tie that Summary 'progress' to a Person. The models.py look like this: class Summary(models.Model): id = models.BigAutoField(primary_key=True) person = models.ForeignKey( Person, on_delete=models.PROTECT, related_name="summaries" ) finalized = models.BooleanField(default=False) class Meta: verbose_name = "Summary" verbose_name_plural = "Summaries" def progress(self): """Return the progress of the summary.""" grades = self.grades.all() finished_grades = ( Grade.complete.all().filter(summary=self).count() ) try: progress = (finished_grades / grades.count()) * 100 class Grade(models.Model): id = models.BigAutoField(primary_key=True) summary = models.ForeignKey( Summary, on_delete=models.PROTECT, related_name="%(class)ss" ) level = models.ForeignKey( Level, on_delete=models.PROTECT, null=True, blank=True, related_name="%(class)ss", ) class Meta: verbose_name = "Grade" verbose_name_plural = "Grades" @property def is_complete(self): if 0 < self.evidences.count() and self.level: return True return False class Evidence(models.Model): id = models.BigAutoField(primary_key=True) grade = models.ForeignKey( Grade, on_delete=models.PROTECT, related_name="%(class)ss" ) comment = models.TextField() My views.py looks like this: class PersonListView(ListView): model = Person template_name = "app/person_list.html" context_object_name = "person_list" def get_queryset(self): people = Person.objects.all().prefetch_related("summaries", "summaries__grades", "summaries__grades__evidences") # There should only be one non-finalized summary # or there will … -
Django back end not sending response message back to React front end
I am currently working on a e-commerce project using django and react. I finished building my create order route and it is working fine in terms of adding the order and orderItem to the database. (I am checking from the admin panel). However the issue is that for some reason I am not able to see the response on the front end even though I am returning it. This is my react component making the reuest PlaceOrder.jsx const handleCreateOrder = async () => { let body = {}; body.user = userContextEmail; body.totalPrice = totalPrice; body.shippingAddress = shippingAddressString; const items = {}; for (let i = 0; i < cart.length; i++) { let itemId = cart[i].id; let itemQuantity = cart[i].quantity; items[itemId] = itemQuantity; body.items = items; } let response = await fetch("http://127.0.0.1:8000/base/orders/create", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(body), }); let result = await response.json(); console.log(result.data); // NOTHING BEING DISPLAYED ON MY CONSOLE }; urls.py path('orders/create', order_views.createOrder) order_views.py @api_view(['POST']) def createOrder(request): data = request.data # print(data) profile = Profile.objects.get(username=data['user']) totalPrice = data['totalPrice'] shippingAddress = data['shippingAddress'] try: order = Order.objects.create( profile = profile, totalPrice = totalPrice, shippingAddress = shippingAddress ) except: message = {'detail': 'An error has occured during … -
show or know LDAP attributes in django
I have a project in django where i try to connect with ldap server. All seems works well, because when i login in django, the user is added to the django database. The problem is that I made a custom user with the department field in django and I want to get a concret attribute from ldap and assign with the field department, but when I login i see in django logs this line: search_s ('ou=xxx,o=xxx, 2 '(uid=%user)s)') returned 1 objects cn=usern_name,ou=xxx,o=xxx Creating Django user user_name Populating Django user user_name cn=user_name,ou=xxx,o=xxx does not have a value for the attribute aaeAppAdd Then I see in department field in Django user database that is empty. How I can see or get the user_object attributes (print, etc) that the LDAP offer when i login correct? These are my config files. settings.py # Config to authenticate with LDAP import ldap from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion, GroupOfNamesType AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) basedn = "ou=xxx,o=xxx" AUTH_LDAP_SERVER_URI = 'ldap://ldapserver:389' AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch(basedn, ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "department": "aaeAppAdd" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": {"console": {"class": … -
how to apply template for django ModelViewset class
hello i am stuck and i can't apply my html to this class please help class ProductViewSet(ModelViewSet): queryset = Product.objects.prefetch_related('images').all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter pagination_class = DefaultPagination permission_classes = [IsAdminOrReadOnly] search_fields = ['title', 'description'] ordering_fields = ['unit_price', 'last_update'] -
django.db.migrations.exceptions.MigrationSchemaMissing error Connecting Postgres to Django?
This is my first time that i am using other database than sqlite3 with django ,so i go ahead with postgres ,install it on my machine and created the user and db but after config the setting.py when i migrate i got this error # database config DB_NAME = 'django_chat_db' DB_USER = "django" DB_PASSWORD = "password" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': 'localhost', 'PORT': '5432', } } ERRORs Traceback (most recent call last): File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.InsufficientPrivilege: permission denied for schema public LINE 1: CREATE TABLE "django_migrations" ("id" bigint NOT NULL PRIMA... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\migrations\recorder.py", line 70, in ensure_schema editor.create_model(self.Migration) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\base\schema.py", line 447, in create_model self.execute(sql, params or None) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\base\schema.py", line 199, in execute cursor.execute(sql, params) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File … -
It is impossible to add a non-nullable field Error when extending Abstract User
I want to extend the Base Abstract User Model and this is the extended model: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=25) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) address = str(street) + str(street_number) + str(city) + str(code) + str(province) But I get this message popup: It is impossible to add a non-nullable field 'password' to student without specifying a default. This is because the database needs something to populate existing rows. However I haven't added a new password field and all the existing password fields (for the superuser) already have a value. What should I do? When I add a default value and try to migrate it, it complains that there is no such table as 'mainApp_student'. -
Is there any way to overwrite the default operation id , tag, name ,description of generated drf api schema?
Is there any way to overwrite the default operationid,name,tag,type,summary, description of generated drf api schema? -
Learning Better Way of Doing It (Django Models)
I am doing Django and I have 4 models. District, Province, Schools and User. The District belongs to a Province, in the School model/table there are the foreign keys to which the school belong. In the User table, I have district, province and school foreign keys. these tuples were named province or district in the tables they are FKs. The error I was getting was a conflict and needed to add a related_name. I need someone to explain to me the value for related_name. From my reading, it is showing the table name, If the FK is in the Comments model then the related_name='comments'. In my case I have three FK in the User model so how do I manage this? I hope this tries to explain my query. -
Django python manage.py runserver TypeError: 'dict' object is not callable
''' Environment: Request Method: GET Request URL: http://127.0.0.1:8000/league/ Django Version: 4.1.2 Python Version: 3.10.0 Installed Applications: Traceback (most recent call last): File "/Users/km/Projects/tournament/Worldchamps/champ_env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) Exception Type: TypeError at /league/ Exception Value: 'dict' object is not callable ''' -
Specifying the display of a django DateField from the model, and not form/input/settings?
I have a Django model with a DateField, like so: production_date = models.DateField(null=True, blank=True) I am trying to have that field display as the default Python date format in templates, which looks like "2000-01-01". But in a Django template it displays as "Jan. 1, 2000." In a Python shell, the date displays properly: In [4]: resource.production_date Out[4]: datetime.date(2014, 4, 20) In [5]: str(resource.production_date) Out[5]: '2014-04-20' But in the template, when I call production_date, I get the other format. I have many templates that use this value, and many ways the data gets added to the database. So I do not want to go to each template and change the display. I do not want to change the input form because that is not the only way data gets added. I do not want to change my site settings. I just want the field to display the default Python value. How do I accomplish this? Thank you! -
Error: no such table when extending Abstract User Model
I wanted to extend the Base Abstract User Model within Django to have some other Fields: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=20) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) address = str(street) + str(street_number) + str(city) + str(code) + str(province) def __str__(self): return f'Adresse: {self.address}' I added this into my settings.py file: AUTH_USER_MODEL = 'mainApp.Student' But I get an Error saying there is no such table "Student" when trying to load /admin/. I have made all the migrations using: python manage.py makemigrations mainApp python manage.py migrate mainApp Error: OperationalError at /admin/ no such table: mainApp_student If y'all need any more infos, please comment! -
How to use HTMX to send url to HTML audio element
This is what I've come up with so far. Where am I going wrong? <button hx-put="/link/to/file.mp3" hx-target="audio"> LOAD TRACK 1 </button> <audio controls> <source src="audio" type="audio/mpeg"> Your browser does not support the audio element. </audio> -
python Django get exact table filed value from JWT token
I'm coding a Django project with JWT token. 'email' is a field from user table. I want to get the exact user email by using: usereamil = request.user.email When I print it ,I got none. But if I use: username = request.user.username I can get a wired user name ,not exact one in the data base ,which I think it is a security way to protect the data. But I do want to get the exact email address of user ,so that can send email to the user. Any friend can help ? -
How can I pass in href a field of my model to put it after in the modal id
Im trying to do a dinamic list to create all the references that I already have saved. <div class="row"> <div class="col-2"> <div class="list-group" id="list-tab" role="tablist"> {% for reference in reference_list %} <a class="list-group-item list-group-item-action" id="list-home-list" data-bs-toggle="list" href={{reference.brand_manufacturer}} role="tab" aria-controls="list-home">{{reference.brand_manufacturer}}</a> {% endfor %} </div> </div> <div class="col-8"> {% for reference in reference_list %} <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show" id="{{reference.brand_manufacturer}}" role="tabpanel" aria-labelledby="list-home-list">{{reference.website_url}}</div> {% endfor %} </div> </div> </div>