Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make datetime already saved in database timezone aware in a Django project
We had a couple of timezone unaware datetime in model definition which resulted in saving a number of entries that were naive datetimes. The default was set to be utcnow like this time_sent = models.DateTimeField(default=datetime.utcnow, blank=True) And we got a lot of these RuntimeWarning: DateTimeField ModelName.time_sent received a naive datetime (2021-08-18 06:43:04.448875) while time zone support is active. We now have set the default as timezone.now so going forward we should not have this problem. However, what should we do to change the data already in database? Any ideas? -
Django||Python :: ValueError: bad marshal data (unknown type code)
I have tried creating a login/register Template that I can use to skip the login/register setup phase every time I need to create a new Django project. However, when I copy the code over and rename the file (and change all the "old file name" dependencies" ... It gives the above mentioned error with the below error message > C:\Users\KylePOG\Documents\GMA Programming\accConnect>python manage.py > runserver Traceback (most recent call last): File > "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", > line 22, in <module> > main() File "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", line 18, in main > execute_from_command_line(sys.argv) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", > line 419, in execute_from_command_line > utility.execute() File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", > line 363, in execute > settings.INSTALLED_APPS File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", > line 82, in __getattr__ > self._setup(name) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", > line 69, in _setup > self._wrapped = Settings(settings_module) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", > line 170, in __init__ > mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", > line 127, in import_module > return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File > "<frozen importlib._bootstrap>", line 1007, in _find_and_load File > "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked > File "<frozen importlib._bootstrap>", line 228, in > _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line > 1007, in _find_and_load File "<frozen importlib._bootstrap>", … -
Saving django parent and child form
I have a page where users enter details that relate to two models - that representing a patient, and another representing medications taken by that patient. I have designed the interface so that multiple medications can be added dynamically by the user. However, I am not sure how to save both the entries for the meds and the patient when the user submits. In the current setup below I am not successfully saving the Patient data as I receive the error “save() prohibited to prevent data loss due to unsaved related object 'patient’.” models.py class Patient(TimeStampedModel): patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) class Med(TimeStampedModel): med_name = models.CharField("MedName", max_length=20) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py from django.forms import inlineformset_factory, ModelForm from .models import Med, Patient MedFormSet = inlineformset_factory(Patient, Med, fields=("med_name",), extra=1) class PatientForm(ModelForm): class Meta: model = Patient fields = ['name', 'sex'] views.py from .forms import MedFormSet, PatientForm from .models import Patient, Med class MedAddView(TemplateView): model = Patient template_name = "../templates/patient/med_add.html" def get(self, *args, **kwargs): # Create an instance of the formset patient_form = PatientForm formset = MedFormSet(queryset=Med.objects.none()) return self.render_to_response({'med_formset': formset, 'patient_form':patient_form}) def post(self, *args, **kwargs): form = PatientForm(data=self.request.POST) formset = MedFormSet(data=self.request.POST) if form.is_valid() and formset.is_valid(): form.save() … -
Django error after install Bootstrap4 with pip
I just installed bootstrap4 using pip and then I execute runserver and this is what I got. I've been looking for solutions and now I´m here asking for your help please Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\python\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\python\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\python\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\python\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Program Files\python\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Program Files\python\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\python\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\python\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\python\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files\python\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 846, in exec_module File "<frozen importlib._bootstrap_external>", line 983, in get_code File "<frozen importlib._bootstrap_external>", line 913, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed ValueError: … -
Routing access to custom user model through database router in django
Consider following situation: You have multiple python/django applications, which share a common user database. You implemented the custom user model in a separate django-app called 'benutzer', which is imported into every applications project directory. Now simply routing access to the custom user model by a custom database-router is apparantly not enough. You probably will get erros similar to the following one: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration benutzer.0001_initial is applied before its dependency auth.0012_alter_user_first_name_max_length on database 'benutzer_extern'. Which models/app-names handled internally by django are needed to be routed additionally to the custom user model ? Adding app_label 'auth' to the router definition does not work. class ExternUsermodelRouter: """ A router to control all database operations on models in an extern user application. """ app_benutzerverwaltung = {'benutzer', 'auth'} def db_for_read(self, model, **hints): """ Attempts to read benutzer models go to db_benutzer. """ if model._meta.app_label in self.app_benutzerverwaltung: return 'db_benutzer' return None def db_for_read(self, model, **hints): """ Attempts to write benutzer models go to db_benutzer. """ if model._meta.app_label in self.app_benutzerverwaltung: return 'db_benutzer' return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the benutzer apps only appear in the 'db_benutzer' database. """ if app_label in self.app_benutzerverwaltung: return db == … -
How to perform conditional aggregation on a Django model's one to many related field?
Given the following model schemas: class Transaction(models.Model): wallet = models.ForeignKey(related_name="transactions") amount = models.DecimalField() # must be positive value type = models.CharField(choices=[("deposit", "deposit"), ("withdrawal", "withdrawal")] class Wallet(models.Model): pass What is the most efficient Django ORM query to obtain the balances of every wallet record in the database? current_balance = sum of "amounts", where type="deposits" - sum of "amounts", where type="withdrawal" It is possible to change the Transaction model's type field to store 1 & -1 integer values in the database, and perform the following query: Wallet.objects.all().annotate(current_balance=Sum(F("transactions__amount") * F("transactions__type"))) Let's assume we cannot change the columns or fields of the given tables / records. Thoughts? -
Django - How to handle unmanaged models during tests
In my Django project I am using 3 different databases, of which 2 are pre-populated with data (legacy databases), thus many of my models are not managed by Django managed = False. When I run tests Django throws django.db.utils.OperationalError: no such table: x. I've been dealing with this problem for days now and already explored few stackoverflow threads and blog articles (i.e https://medium.com/an-idea/testing-with-the-legacy-database-in-django-3be84786daba, https://hannylicious.com/blog/testing-django/, https://dev.to/vergeev/testing-against-unmanaged-models-in-django). Sadly nothing seems to help, some tables just don't want to be migrated to test databases (I am also using 3 test sqlite3 dbs). Many stackoverflow threads and blog posts are old and don't apply to current Django version (3.2). I would greatly appreciate any help if anyone has experienced similar problem. Cheers guys :) -
Field 'id' expected a number but got (something with Id)
Django 3.2.6 class FeedbackForm(CreatedMixin, CommentMixin, FlagMixin, models.Model): name = models.CharField(blank=False, default="", null=False, unique=False, max_length=500, verbose_name=gettext("Name:")) email = models.EmailField(blank=True, default="", null=False, unique=False, verbose_name=gettext("Email:")) phone = PhoneField(blank=True, default="", null=False, unique=False, verbose_name=gettext("Phone:")) message = models.TextField(blank=False, default="", null=False, verbose_name=gettext("Message:")) def __str__(self): return f"{self.name}_{self.email}_{self.phone}" class FeedbackForm(ModelForm): class Meta: exclude = [OmnibusNames.COMMENT.value, OmnibusNames.FLAG.value, OmnibusNames.CREATED.value,] model = FeedbackForm class FeedbackFormView(FormView): template_name = 'feedback_forms/feedback_form.html' form_class = FeedbackForm class FeedbackFormResult(View): def post(self, request, *args, **kwargs): feedback_form_model = apps.get_model(app_label="feedback_forms", model_name="FeedbackForm") new_feedback = feedback_form_model(request.POST) new_feedback.save() return render(request, template_name="feedback_forms/feedback_form.html") <form id="subscription-form" onsubmit="return false"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> The problem: {TypeError}Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['W8wfxQvsmQyElPtsdmJFiDJmzbyKZXRYfZS9TAbFGpNZDo22jWaLotUrllHYsDWi'], 'name': ['John'], 'email': ['tad@gmail.com'], 'phone_0': ['+19617828635'], 'phone_1': [''], 'message': ['ddd']}>. Hm. Something with id. But I though that Id is auto incrementdd. Could you help me? [![enter image description here][1]][1] ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [1]: https://i.stack.imgur.com/GYFL7.png -
is Django 3 compatible with MySQL 5.7?
I'm running a django app in Ubuntu, and the MySQL version is : mysql Ver 14.14 Distrib 5.7.34, for Linux (x86_64) using EditLine wrapper The Django version is 3.2.5 But it raised an Error: File "/opt/anaconda3/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/opt/anaconda3/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/opt/anaconda3/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/opt/anaconda3/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) Exception Type: ProgrammingError at /category/python.html Exception Value: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION (SELECT `blog_article`.`id`, `blog_article`.`created_time`, `blog_article`' at line 1") Is it a compatible issue between Django 3 and MySQL 5.7? -
how to create a django app that performs a google search
I want to make a Django app that searches on google a string and then saves the html page. so far I managed to create this <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container text-center"> <h1>my search engine</h1> <h3>Pressing search will run a google search for 'lallero search', then the code will scrape the first 5 links in that google search and store the corresponding html.</h3> <a href="{% url 'about' %}">About page</a> <br> <br> <form action="{% url 'search' %}"> <input type='submit' value='search' class="btn btn-primary"> </form> </div> that searches on google a very specific string and it is just a press button. I would like to add a form where I can write the string I want to search and then pass it as input to my "search" function so far I came out with this <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container text-center"> <h1>my search engine</h1> <a href="{% url 'about' %}">About page</a> <br> <br> <form action="{% url 'search' %}"> <input type="search" value='lallero search' class="form-control rounded" placeholder="Search" aria-label="Search" aria-describedby="search-addon" /> <button type="button" class="btn btn-outline-primary">search</button> </div> but I do not know how to pass the string I write as input to the function. any advice? -
Django simple search with Class based views and forms.py
I have been trying to do a variation of what Williams Vincent did on this page: https://learndjango.com/tutorials/django-search-tutorial . I am using Django 3.2 so if there are modifications, I need to make I have not identified them. I am having some troubles. This what I made which worked just fine. my_search.html: {% extends "base.html" %} {% block body %} {% for city in object_list %} <li> {{city.name}} &emsp; {{city.city_no}} </li> {% endfor %} {% endblock %} views.py: from django.views.generic import ListView from .models import City class SearchResutlsView(ListView): # test version model = City template_name = "search_results.html" def get_queryset(self): return City.objects.filter(name__icontains='Boston') Now it is time to add forms.py, but when I made the below changes to the code it does not work. What am I missing? There are no errors displayed. I get a blank html. {% extends "base.html" %} {% block body %} <form class="d-flex" method='get' action="{% url 'city:search_results' %}"> {{ form }} <button class="btn btn-outline-success" type="submit" value="qu">Search Name</button> </form> {% for city in city_list %} <li> {{city.name}} &emsp; {{city.city_no}} </li> {% endfor %} {% endblock %} forms.py from django import forms class SearchForm(forms.Form): q = forms.CharField(label='Search label', max_length=50, strip=True) views.py from django.views.generic import FormView, ListView from .models import City … -
How and where to calculate field in Django?
Let's say we have such models. class Product(models.Model): name = models.CharField(max_length=100) # ... main_photo = models.ImageField(upload_to='photos/') class ProductPhoto(models.Model): product = models.ForeignKey(Product, related_name='photos', on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos/') I have two views: ProductsView. It provides list of products with general information about each one, including name, ..., main_photo only. ProductDetailsView. It provides more detailed info, including all photos. I want detailed view to provide all photos in flat array photos, like this [main_photo, ...rest_photos]. How can I do this with django rest framework? On which level should this logic be implemented? Model, View, Serializer? -
How to prefetch_related on Django MPTT model sub-category?
I'm using Django MPTT model for category and sub-category. I'm unable to filter subcategories by their active state. I wanted subcategory data with is_active=True. models.py class TrnCategory(MPTTModel): name = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, related_name='subcategories', null=True, blank=True, db_index=True) is_subject = models.BooleanField(default=False) institute = models.ForeignKey(Institute, on_delete=models.CASCADE, related_name='catrgories') sequence = models.IntegerField(default=1) is_active = models.BooleanField(default=True) My query: views.py class CategoryDetailView(generics.RetrieveUpdateDestroyAPIView): serializer_class = CategorySerializer permission_classes = [IsAuthenticated, InstituteAdminRequired] def get_serializer_class(self): if self.request.method != 'GET': return CategorySerializer return CategoryDetailSerializer def get_queryset(self): return TrnCategory.objects.filter(institute=self.request.user.institute, is_active=True).prefetch_related(Prefetch('subcategories', queryset=TrnCategory.objects.filter(is_active=True).order_by('sequence') )).order_by('sequence') def perform_destroy(self, instance): instance.is_active = False for material in instance.materials.filter(is_active=True): material.is_active = False material.save(update_fields=['is_active']) instance.save() My output in postman { "id": 54, "name": "Python", "is_subject": false, "is_active": true, "parent": null, "subcategories": [ { "id": 106, "name": "File Handling", "is_subject": false, "is_active": true, "subcategories": [], "sequence": 5 }, { "id": 107, "name": "Modules and String Formatting", "is_subject": false, "is_active": true, "subcategories": [], "sequence": 6 }, { "id": 118, "name": "Assessment - 1", "is_subject": false, "is_active": true, "subcategories": [], "sequence": 7 }, { "id": 119, "name": "Assessment - 2", "is_subject": false, "is_active": false, "subcategories": [], "sequence": 8 } ], "sequence": 0 }, { "id": 108, "name": "Python Advanced", "is_subject": false, "is_active": true, "subcategories": [ { "id": 150, "name": "Testing", "is_subject": false, … -
Django - Is it better practice to just create REST endpoints with url parameters or APIViews with serializers?
So I have 2 examples below of what I mean. The DELETE uses Django REST framework and it takes a user id as url parameters to delete a FollowUser entity. Then the second expects the information to create a FollowUser object in the "data" of the request. I prefer the first method, because I don't have to create a APIView where all requests require the same data body and I don't need to create new serializers for different requests. For example, if DELETE only requires 2 table attributes, but POST requires all of them. Which one of these practices is safer(less prone to getting hacked)? Can I require JWT token authentication for both these styles of end-point creation? @api_view(['DELETE']) def delete(self, request, follower_id, followee_id): FollowUser.objects.get(follower_id=follower_id, followee_id=followee_id).delete() return HttpResponse(status=status.HTTP_200_OK) class FollowGoalView(APIView): def post(self, request): serializer = FollowUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django update_or_create with multiple defaults / fields
I would like to use update_or_create to update several fields but I can't find the correct syntax. The following gives an error: def form_valid(self, form): form.instance.user = self.request.user form.instance, created = MyModel.objects.update_or_create( user=self.request.user, defaults=( {'field1': form.instance.field1}, {'field2': form.instance.field2}, {'field3': form.instance.field3}, )) return super().form_valid(form) The error I get is 'tuple' object has no attribute 'items'. I also tried this with a list, similar error. It works fine when I have only one dictionary such as defaults={'field1': form.instance.field1}. I'm assuming this should work with multiple dictionaries since the docs say that it helps avoid using try and except because "This pattern gets quite unwieldy as the number of fields in a model goes up." -
How to Crop Images in a Django Application *JavaScript Issue*
I am having issues with my JavaScript code, and I am trying to get the image crop (picture) below to pop up but when I click the Choose File button but nothing happens. I am following https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html and it is a little outdated so I was wondering if anyone could help point out what part of the code is out of date. If someone could help that would be much appreciated. {% block javascript %} <script> $(function () { /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#id_file").change(function () { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#image").attr("src", e.target.result); $("#modalCrop").modal("show"); } reader.readAsDataURL(this.files[0]); } }); /* SCRIPTS TO HANDLE THE CROPPER BOX */ var $image = $("#image"); var cropBoxData; var canvasData; $("#modalCrop").on("shown.bs.modal", function () { $image.cropper({ viewMode: 1, aspectRatio: 1/1, minCropBoxWidth: 200, minCropBoxHeight: 200, ready: function () { $image.cropper("setCanvasData", canvasData); $image.cropper("setCropBoxData", cropBoxData); } }); }).on("hidden.bs.modal", function () { cropBoxData = $image.cropper("getCropBoxData"); canvasData = $image.cropper("getCanvasData"); $image.cropper("destroy"); }); $(".js-zoom-in").click(function () { $image.cropper("zoom", 0.1); }); $(".js-zoom-out").click(function () { $image.cropper("zoom", -0.1); }); /* SCRIPT TO COLLECT THE DATA AND POST TO THE SERVER */ $(".js-crop-and-upload").click(function () { var cropData = $image.cropper("getData"); $("#id_x").val(cropData["x"]); $("#id_y").val(cropData["y"]); $("#id_height").val(cropData["height"]); $("#id_width").val(cropData["width"]); … -
In my Django and DRF project, I get Server error for my right-working link, and 404 not found page for missing url after adding 404 page
Hi, I have Blog post project some functionalities made with DRF and some functionalities made with Django.I need to add 404 page for missing urls. But If I use right-working link, I will get server error, However, I will get 404 page for missing url. For example, urls such as '127.0.0.1:8000/en/me' or '127.0.0.1:8000/en/me/contact/' or '127.0.0.1:8000/en/book' will bring server error, but url '127.0.0.1:8000/en/men' return not found page in my django_project/urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi from django.conf.urls.i18n import i18n_patterns # from django.conf.urls import handler404 from my_works import views as my_works_views schema_view = get_schema_view( openapi.Info( title="API Docs", default_version='v1', description="API urls description", terms_of_service="https://www.myblogs.com/policies/terms/", contact=openapi.Contact(email="aahmadov271101@gmail.com"), license=openapi.License(name="Test License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns ( path('', include('my_works.urls')), path('me/', include('accounts.urls')), path('admin/', admin.site.urls), ) urlpatterns+= (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)) urlpatterns+= (static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)) handler404 = 'accounts.views.error_404_view' admin.site.site_header = 'Alimardon Mustafoqulov Administration' admin.site.site_title = 'Administration' admin.site.index_title = 'Administration page' in my django_app/urls.py: from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from .views import ( ArticlesViewList, BooksViewList, PresentationsViewList, ProjectsViewList, EventsViewList, VideosViewList, ) … -
Django programming: cannot cast time without time zone to timestamp
I am newbie to django and was using SQLite during development, when i moved to postgres when trying to deploy to production i get the below error Cannot cast type time without time zone to timestamp with time zone settings.py Django settings for todoBackend project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path from django.core.management.utils import get_random_secret_key import os import sys import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", "False") == "True" ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",") # Application definition INSTALLED_APPS = [ "rest_framework", "corsheaders", "api.apps.ApiConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ALLOW_ALL_ORIGINS = True ROOT_URLCONF = "todoBackend.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], … -
Change django form fields based on a value from a dropdown
I am trying to make a form in django which needs to update itself based on a value from a dropdown. Here is my forms.py file. class LeadForm(forms.Form): CHOICES=[(0,'option A'), (1,'option B')] radio_button = forms.ChoiceField(choices=CHOICES, widget=forms.Select()) test_field_A = forms.CharField(widget=forms.TextInput()) test_field2A = forms.CharField(widget=forms.TextInput()) test_fieldB = forms.CharField(widget=forms.TextInput()) test_field2B = forms.IntegerField(min_value=0) If "option A" is selected from the drop down, I need only the fields containing "A" in the end. And I only need testfield_2A and test_field2B if 'option B' is selected. Can I achieve this with Django alone or do I need to write Javascript/Jquery? Also do I need to write separate forms for these two cases? Thanks in advance. -
No username attribute of model error, even already have objects = UserManager()?
Here is my model in the user app from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserTable(AbstractBaseUser, PermissionsMixin): USERNAME_FIELD='email' objects = UserManager() email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=255, default=None) is_active = models.BooleanField(default=False) Here is my admin.py inside the user app. from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import UserTable admin.site.register(UserTable, UserAdmin) I also included in my settings.py INSTALLED_APPS = [ .... 'user.apps.UserConfig', .... ] This is the error when I run python manage.py migrate (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'user.UserTable'. The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'user.UserTable'. I dont know why, I thought when I set objects = UserManager() fields like username, first_name, last_name is setted up. I also user USERNAME_FIELD to set email replacing the username primary key. -
Python code changes are not reflecting on the Django Web server (httpd with mod_wsgi package)
I have been hosting a django-based web server (httpd with mod_wsgi package) on Linux CentOS 7. I used to reflect the changes made in my code by restarting the web server using the following command: sudo systemctl stop httpd sudo systemctl start httpd and it would reflect the changes smoothly. Since few days back this strategy does not work at all. That is, whenever I make any change in my python code, even simply printing a message in log file, it is not reflected. I reboot the VM and only then the code changes were reflected. I tried the following things already which did not help at all: Clearing .pyc files Restarting/Reloading httpd server touch wsgi file All of the above mentioned tries did not appear to work. The changes are only reflected when the VM is rebooted. This problem has just started occurring 3-4 days ago and it was completely working before. Any help or suggestions are highly appreciated. Thanks. -
Javascript is Loading Page Too Soon - Django Edit Form
I'm trying to edit an existing post (form) on my site but when I click 'edit' I get this in the console: Fetch finished loading: POST "http://127.0.0.1:8000/edit_post/18". Status is 201 so I think the page is skipping over most of the javascript and directly posting it/saving to server. Also when I click 'edit' a text box is immediately supposed to appear with my post text already there. But this never opens, it just says fetch finished loading appropriately in the console. How can I make sure all the Javascript is run first? I tried using preventDefault and keep running into Uncaught type errors. I'm pretty new to Javascript so I'm still learning this. For example, one thing I tried within the event_handeler function was: document.querySelectorAll("#textarea").addEventListener("submit", function(event) { document.querySelector(`#post-edit-${id}`).innerHTML += "Sorry!"; event.preventDefault(); }) But I got uncaught type errors. function edit_handeler(element) { id = element.getAttribute("data-id"); document.querySelector(`#post-edit-${id}`).style.display = "block"; document.querySelector(`#post-content-${id}`).style.display = "none"; edit_btn = document.querySelector(`#edit-btn-${id}`); edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); }} function edit_post(id, post) { const body = document.querySelector(`#post-content-${id}`).value; fetch(`/edit_post/${id}`, { method: "POST", body: JSON.stringify({ body:body }) }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = post; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display … -
How Can I Validate Two Fields from Two different models using Django forms
I have two Models (Product and Sales) and the two models have their respective django forms modeled accordingly. The Product Model has a field named price while the Sales Model has a field named sellingprice. In my Validation rule I want to validated these two fields from two different models (Product and Sales) during user submission on one Django form. I want to check if the Product price is not less than or equal to the sellingprice of the Sales Model. Below is what I am trying to do but getting errors. from django import forms from django.core.exceptions import ValidationError class SalesForm(forms.Form): class Meta: model = Product, Sales fiels = __all__ ... def clean(self): cleaned_data = super().clean() product_price= cleaned_data.get("product_price") selling_price= cleaned_data.get("selling_price") if selling_price > product_price: # Only do something if both fields are valid so far. else: raise ValidationError( "Selling Price can not be less than or equal to Product Price " ) -
ModuleNotFoundError: No module named 'rest_framework' when running celery -A backend worker -l info
I'm trying to run my tasks and I'm currently using Celery for this alongside Django and DjangoRestFramework This is how I've set things up, root directory is also called backend . ├── backend │ ├── asgi.py │ ├── celery.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py └── save_to_db ├── admin.py ├── apps.py ├── dump.rdb ├── migrations │ ├── 0001_initial.py │ └── 0002_auto_20210728_0251.py ├── models.py ├── serializers.py ├── tasks.py ├── tests.py ├── urls.py └── views.py So I have all my configuration for Celery in celery.py which I followed from this on how to set up Celery for Django https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html This is how my config looks like import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') app = Celery('backend') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') I decided to run this command to get Celery started celery -A backend worker -l info But … -
Django: sql works well in mysql but gives error in cursor.execute
put sql sentence in sqlyog SELECT `v` ,`t` FROM `pm` WHERE `id`='12'; the true return is: v t ------- ------------- 13.32 23 13.319 23 13.319 23 but when I use cursor.execute() in django, it only returns one result and my code in django is: sql = "select v,t from pm where id = '12'" cursor = connection.cursor() cursor.execute(sql) V = cursor.fetchall() print(V) return result: ((13.319, 23.0),) if I use fetchone(),it will return one tuple ((13.319, 23.0)) This problem is really strange, and I hope that somebody can give me some hints. THANK YOU SOOOO MUCH!