Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't figure out how to 'assert' properly for psycopg2.errors.NotNullViolation in Django
I am currently creating some tests for a model I created. The test is checking to see if the first_name NOT NULL constraint is working for that field. It should do that by checking if the object.save() method fails. If it fails then the assertation should return pass. My test method looks like this: def test_tutor_fname_notnull(self): ''' Test passes if first_name NOT NULL constraint is working. If first_name is missing, data should not be saved to DB and return false. ''' stevie = Tutors(last_name='wonder',email='sboywonder@gmail.com',birth_day='1990-01-02') self.assertIs(stevie.save(), False) The assertation fails and returns this: psycopg2.errors.NotNullViolation: null value in column "first_name" of relation "artsubjects_tutors" violates not-null constraint DETAIL: Failing row contains (1, null, wonder, sboywonder@gmail.com, 1990-01-02). This means the NOT NULL constraint is working and that the assertation should pass. But the assertation actually fails. ---------------------------------------------------------------------- Ran 1 test in 0.003s FAILED (errors=1) Destroying test database for alias 'default'... Any idea on how I could better handle this assertation as to make it pass as intended when the object.save() method fails as expected? -
Django and Mypy : unable to read config options
I am attempting to use mypy with django, following the tutorial here: django-mypy-check-runs I wasn't able to use the init.py import as per the article, instead I used the same code in the ready function of the apps.py in my top level app. mypy runs perfectly, as long as the function api.run has the project base directory in a list as a parameter as per the code in the article: results = api.run([settings.BASE_DIR]) I am unable to find out why the project base directory presented this way is of any use. According to the docs, the list that is passed to api.run, should have configuration options passed in the list as they would be passed to the executable on the commandline. I have checked the source code of mypy and this seems to be the case. If I change the code so that the api.run has a list as a parameter, that contains configuration options, mypy doesn't work. If I pass an empty list or no list at all, mypy doesn't work. Also, although I have a mypy.ini file in the same directory, and also at the project root (in case this is what the settings.BASE_DIR in the list passed … -
Does Django support integer enums for model fields similar to models.TextChoices?
I'm using Django 3.2 and Python 3.9 and Postgres. I have the below model in which I want to constrain one of the fields ("type") to be from a predefined enum ... class Transaction(models.Model): class TransactionTypes(models.TextChoices): BUY = 'BUY', _('Buy') SELL = 'SELL', _('Sell') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(null=False, default=datetime.now) price = models.FloatField(null=False) amount = models.FloatField(null=False) type = models.CharField( null=False, max_length=5, choices=TransactionTypes.choices, ) class Meta: indexes = [ models.Index(fields=['created']), However, this is slightly space-inefficient as I'm using a character type when I feel I shoudl be using an integer type for the enums. Does Django have anything out of the box that can accommodate integer enum types? -
How to write clean permission in Django
I have never deal with a custom permission system and I am kind of struggling. I have this get_queryset: def get_queryset(self): """ Get query set regarding the user's group. If the group name is not xx then filter the result by dealer name """ user_groups = self.request.user.groups.all().values_list('name', flat=True) if 'xx' not in user_groups: dealer = MANUFACTER_CHOICE dealer_name: str = [dealer_name[1] for dealer_name in dealer if dealer_name[1].lower() in user_groups][0] return ShapeFile.objects.filter(system__dealer__name=dealer_name) return ShapeFile.objects.all() Basically, it check the group the user is in. My users must be in a group. My ShapeFile model have a foreign key to system that have a field dealer. Dealer must be equal to one of my group name. If the user is in xx, he can see every ShapeFile on the DB. Else I need to check the group the user is in and find all shapefile that belong to a system that have a dealer name equal to the user's group. I feel that I should implement a Object level permission https://www.django-rest-framework.org/api-guide/permissions/#object-level-permissions. But I do not see how I could use it. Could anyone explain what's the good way to do this ? Thanks -
[Django]Cant run collectstatic to upload media to S3
I'm using the following configs to store static and media files to S3 USES_S3 = config('USES_S3') == 'True' if USES_S3: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_KEY = config('AWS_SECRET_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_REGION_NAME = config('AWS_S3_REGION_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=94608000'} STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' STATICFILES_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/' MEDIAFILES_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') However I keep getting the following error, when I try to run collectstatic k_date = self._sign(('AWS4' + key).encode('utf-8'), TypeError: can only concatenate str (not "NoneType") to str It seems this error happens when you can't connect to S3. What am I doing wrong, any help appreciated. -
Form with ImageField doesn't open pop-up to choose file
I do have a straight forward form to update the user's profile picture. However, in the template when I click choose file it doesn't pop the dialog to select a file from the computer. # Template <form class="update-profile-image-form" method="post" enctype="multipart/form-data" action="update_profile_image/"> {% csrf_token %} {{ profile_image_form }} <button type="submit">Save Image</button> </form> If I submit the form without selection a file, it processes everything just fine using the default image set in the model. So somehow the form seems to be working to some extend at least.. # Form class ImageUpdateForm(forms.ModelForm): class Meta: model = Account fields = ['profile_image'] # Model def get_profile_image_filepath(self, filename): return f'profile_image/{self.pk}/{"profile_image.png"}' def get_default_profile_image(): return "profile_image/Logo_large.png" class Account(AbstractBaseUser): """ Main User Account model, inherits from AbstractBaseUser """ email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image()) -
Embed jupyter notebook in django
I have a web page(django) which shows the contents of a folder. I want to open the files in this folder with jupyter notebook. How can i embedd the jupyter link on my page ? Clicking the link must: Open a jupyter notebook with selected folder. The notebook must be available seperately for each logged in user.(Preferably all the note book instances must open on the same port, with different token id.) Is it possible ? -
Django throwing a ValueError: source code string cannot contain null bytes
The whole error is quite huge : Traceback (most recent call last): File "C:\Users\FiercePC\IdeaProjects\RadioShazam\server\ServerDjango\manage.py", line 22, in <module> main() File "C:\Users\FiercePC\IdeaProjects\RadioShazam\server\ServerDjango\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\FiercePC\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\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 257, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\FiercePC\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 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 3, in <module> from django.core.management.commands.runserver import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\servers\basehttp.py", line 14, in <module> from wsgiref import simple_server ValueError: source code string cannot contain null bytes` I just generated the project and didnt almost anything. The program works on my computer but not on my friends. We have the same versions of python/django etc. -
Why does my reverse url lookup with kwargs not work on viewset action api?
Here is my viewset with an action: class RewardsQueryViewSet(UUIDModelViewSet): queryset = RewardsQuery.objects.all() serializer_class = RewardsQuerySerializer ordering_fields = ("-created_at",) http_method_names = [ "post", "get", ] def create(self, request, **kwargs): serializer = RewardsQuerySerializer(data=request.data) serializer.is_valid(raise_exception=True) transaction = serializer.save() return Response(transaction) @action( detail=True, methods=("get",), url_path="earned-rewards", ) def earned_rewards(self, request, *arg, **kwargs): session = RewardsQuery.objects.get(uuid=self.kwargs["uuid"]) transactions = Rewards.objects.filter(profile=session.profile) return Response({"results": transactions}) in urlconf, I see this entry: api/<version>/ ^applications/(?P<client_id>[^/]+)/rewards-queries/(?P<uuid>[^/.]+)/earned-rewards/$ [name='rewards-query-earned-rewards'] but when I try to do the reverse lookup, it fails. I've tried both of these: drf_reverse('rewards-query-earned-rewards', kwargs={'client_id': instance.application.client_id, 'uuid': str(instance.uuid)}) reverse('rewards-query-earned-rewards', kwargs={'client_id': instance.application.client_id, 'uuid': str(instance.uuid)}) django debug error: Exception Type: NoReverseMatch Exception Value: Reverse for 'rewards-query-earned-rewards' with keyword arguments '{'client_id': 'FVQI5U57tfCyDV99YjhF3ExdlpiObg5JASvy81Mu', 'uuid': '2057de0f-f5b4-4af4-aa99-ac3681cc6984'}' not found. 2 pattern(s) tried: ['api/(?P<version>[^/]+)/applications/(?P<client_id>[^/]+)/rewards-queries/(?P<uuid>[^/.]+)/earned-rewards\\.(?P<format>[a-z0-9]+)/?$', 'api/(?P<version>[^/]+)/applications/(?P<client_id>[^/]+)/rewards-queries/(?P<uuid>[^/.]+)/earned-rewards/$'] Why is reverse lookup failing? -
Django rest framework : creating a user ask for authentication
I was using django user, authentication and permission modules but while making a request to create a new user in the POST request, its asking for authentication. and I am getting { "detail": "Authentication credentials were not provided." } Here is my serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = { 'password' : { 'write_only':True, 'required': True } } def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) # create token for the user return user def update(self, instance, validated_data): instance.username = validated_data['username'] instance.set_password(validated_data['password']) instance.save() return instance views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated, IsOwnerOfObject] authentication_classes = (TokenAuthentication,) urls.py from django.urls import path, include from .views import UserViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('users', UserViewSet, basename = 'users') urlpatterns = [ path('api/', include(router.urls)), ] -
how to reset datetimefield in django
I doubt in the DateTime field, my 'course' model has a field called "publish_date" and if the course is published then "course.publish_date = datetime.datetime.now ()". Also, there is a chance that the published course will not be published, so I should be able to change it to publish_date = null, But it makes mistakes, give me a solution to fix it. views.py class PublishCourseViewSet(ResponseViewMixin, viewsets.GenericViewSet): def put(self, request, course_id=None, *args, **kwargs): try: course = get_object_or_404(Course, pk=course_id) course_status = course.review_status if course_status == 'review_passed': course.review_status = 'published' course.publish_date = datetime.datetime.now() course.save(update_fields=["review_status", "publish_date"]) serializer = CourseListSerializer(course) return self.jp_response(s_code='HTTP_200_OK', data=serializer.data) else: return self.jp_error_response('HTTP_400_BAD_REQUEST', {"detail": "course not yet ready for publishing"}) except Exception as e: return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) class UnPublishCourseViewSet(ResponseViewMixin, viewsets.GenericViewSet): def put(self, request, course_id=None, *args, **kwargs): try: course = get_object_or_404(Course, pk=course_id) course_status = course.review_status if course_status == 'published': course.review_status = 'review_passed' course.publish_date = null course.save(update_fields=["review_status", "publish_date"]) serializer = CourseListSerializer(course) return self.jp_response(s_code='HTTP_200_OK', data=serializer.data) else: return self.jp_error_response('HTTP_400_BAD_REQUEST', {"detail": "course not yet ready for publishing"}) except Exception as e: return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) -
How come Django templates, Ajax, and form.errors don't work together in a more integrated fashion?
I'm continuing on my Django, Ajax, and form.errors journey...and here's what I can and can't make sense of....If an ajax request submitted by django....has form.errors....how come django can't recognize this in the template? It can if the form is submitted via a traditional form_valid approach...but not as_json. If the error is as_json....you have to manually interrogate the errors. At least this is the most documented method on the internet. Can someone who is way smarter than I am provide a reasonable explanation as to why this wouldn't be possible? It seems like it should be....with just a simple template loop... Instead I've read the way to solve this is ajax with crispy forms...or ajax with manipulating the DOM. Thanks in advance for any feedback on this topic. -
Dropdown List with Django dependent
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. this post(https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html) not working. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. if 'gruppo_single' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) print("<----------ciao sono qui ------>", gruppo_id) self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id) except (ValueError, TypeError): pass else: print("<----------errore ------>") models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = … -
Django 3.2.8 | DetailView url doesn't load base.html if "/" present
I have this weird behavior where the following loads static files : url.py : path('<int:pk>/detail', PropositionsDetailView.as_view(), name='propositions-detail') but if I add a trailing "/" it doesn't seem to find them ; I only get the base.html unformated : path('<int:pk>/detail/', PropositionsDetailView.as_view(), name='propositions-detail') would someone know why that is ? -
placeholder on dependent dropdown filter
I have a django filter with a dependent drop down to filter car manufactures and models. The models use a charfield and pulls the cars from a db entry. I would like a place holder to say manufacture and model on their respected fields. I cant find much online about doing this. The only post I can find relates to using the choice field on the model which wont work for me. filter class CarFilterForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Post.objects.none() if 'model_manufacture_id' in self.data: try: model_manufacture_id = int(self.data.get('model_manufacture_id')) self.fields['model_id'].queryset = CarModels.objects.filter(model_manufacture_id=model_manufacture_id) except (ValueError, TypeError): pass class carFilter(django_filters.FilterSet): class Meta: model = Post fields = 'manufacture', 'model' form = CarFilterForm html <form method="get" id="AllCarsForm" data-cars-url="{% url 'ajax-allcars' %}"> {% render_field myFilter.form.manufacture class="cars-filter-widget" %} {% render_field myFilter.form.model class="cars-filter-widget" %} <button class="btn btn-primary" type="submit">Search</button> </form> -
How to filter an annotated queryset using Window function without changing the annotated field
I have a queryset of users, after annotating the rank of each user using Django Window function, I want to query for a user without modifying the rank value users_points_query = users.order_by( '-total_points' ).annotate( rank=Window( expression=Rank(), order_by=[ F('total_points').desc() ], ) ) this works fine, but when filtering on users_points_query query, the rank is calculated again, so the first user will get a rank of 1, which is based on the first row and so on. -
How to join multiple table with ForeignKey in django
from django.db import models class Employee(models.Model): ID = models.AutoField(primary_key=True, db_index=True) EMP_CODE = models.CharField(max_length=150) EMP_NAME = models.CharField(max_length=150) ...etc class EMPLOYEE_PERSONAL(models.Model): ID = models.AutoField(primary_key=True, db_index=True) EMP_CODE = models.CharField(max_length=150) EMP_LINK = models.ForeignKey(Employee) EMP_ADDRESS = models.CharField(max_length=150) ..etc class EMPLOYEE_COMPANY_DETAILS(models.Model): ID = models.AutoField(primary_key=True, db_index=True) EMP_CODE = models.CharField(max_length=150) EMP_LINK = models.ForeignKey(EMPLOYEE_PERSONAL) EMP_COMPANY_NAME = models.CharField(max_length=150) NO_OF_WORKING_DAY = models.CharField(max_length=150) ..etc In here I have EMP_CODE how to get all table data value in single query in orm .for eg( I need EMP_NAME ,EMP_ADDRESS ,EMP_COMPANY_NAME ) Using EMP_CODE . I beginner of python Django -
Django Site matching query error when start
Error: DoesNotExist at /login/ Site matching query does not exist. Git code: https://github.com/Vladislava05/todo.git -
SMTPAuthenticationError at /email/signup/ in my django project on pythonanywhere.com
Django sendmail not working, i got error: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials q13sm252028qtx.80 - gsmtp') there are similar question on S.O.,like this. everyone taking about "allow less secure apps", but i already turn that option ON. my auth details are correct, i had tried with two different accounts. two step varification is disabled. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True views.py def sendmail(email,token): subject = 'Varify Email' message = 'Hello User please activate your account by click on this link '+'http://mywebsite.pythonanywhere.com/email/varify/'+token from_email = 'praveexxxxxxxxxxx@gmail.com' recipient_list = [email] send_mail(subject=subject,message=message,from_email=from_email,recipient_list=recipient_list) def signup(request): token = generatedtoken email = someoneemail@gmail.com sendmail(email,token) -
get the currently logged user request.user in utils.py
I need to get the currently logged user 'budget_id' (column from database) in utils.py. Normally in views.py I use: def login_user(request): return request.user.last_name utils.py fragment: class Calendar(HTMLCalendar): def __init__(self, year=None, month=None,): self.year = year self.month = month super(Calendar, self).__init__() def formatday(self, day, events): budget_id = request.user.budget_id // need here -
Set up JSONField in HTML page
I've created this model class RoadConstruction(models.Model): fromCity = models.CharField(max_length=200, null=True) toCity = models.CharField(max_length=200, null=True) status = models.CharField(max_length=200, null=True) date_updated = models.DateTimeField(auto_now_add=True, null=True) jsonData = models.JSONField(null=True) profile = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) So when I use Forms and add the form into my html page it generates a text area for jsonData. But here is the catch I know how to like properly define the contents of JSONField but the thing is the JSON is going to be dynamic and it all depends upon the user who is submitting the form. So, I cannot fix the JSONField. I'll explain with examples of what I'm expecting with JSONField. fromCity, toCity, status is self explanatory as it can be very easily implemented with Forms. In xyz.html page there will be initially one row of empty form. colA colB colC valueA valueB valueC Here suppose the user gave above inputs i.e valueA, valueB, valueC. So I want data to be stored in JSONField as [ { 'colA': valueA, 'colB': valueB, 'colC': valueC, } ] Also there will be a ADD button which will add a new row like this and then the user can fill it. | colA | colB | colC | |------|------|------| | … -
django translation get_language returns default language in detail api view
this is the api which sets language when user selects some language this works fine. class SetLanguage(APIView): def get(self, request, *args, **kwargs): user_language = kwargs.get("lan_code") translation.activate(user_language) response = Response(status=status.HTTP_200_OK) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) request.session[LANGUAGE_SESSION_KEY] = user_language return response viewset here with this viewset only in the api blog/{id} the function get_language returning default language code but on other api it working properly. I am not being able to find the issue. What might gone wrong ? class BlogViewSet(ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerilizer detail_serializer_class = BlogDetailSerializer def get_serializer_class(self): if self.action == "retrieve": return self.detail_serializer_class return super().get_serializer_class() def list(self, request, *args, **kwargs): queryset = Blog.objects.filter(parent=None) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) @action(detail=True, methods=["get"]) def childs(self, request, id): child_blogs = Blog.objects.filter(parent_id=id) serializer = self.get_serializer(child_blogs, many=True) return Response(serializer.data) model from django.utils.translation import get_language class MyManager(models.Manager): def get_queryset(self): current_language = get_language() print(current_language) return super().get_queryset().filter(language=current_language) class Blog(models.Model): title = models.CharField(_("Title"), max_length=100) objects = MyManager() -
How can I add two date fields in Django
Is it possible to add two date fields in Django models as single field. typically this field I have added from date range picker JavaScript picker which user can select from n to in the single field. Is any way to achieve it in Django -
'NoneType' object has no attribute 'transform'
AttributeError at /turboai/turboAI/jaaiparameters/ enter image description here def transform_data(df, cols, scaler, n_days_past=120): n_cols = len(cols) # df to np array np_arr = np.array(df.values.flatten().tolist()) np_arr = scaler.transform([np_arr]) np_arr = np_arr.reshape((np_arr.shape[0], n_days_past, n_cols)) return np_arr -
Couldnt save Modelform to database
I am trying to save the model form and getting error that foreign key column is not there. Error: column "connection_type_id" of relation "connection_details_test" does not exist ( There is no column connection_type_id, why its looking for this column, should I change my model?) Models: class ConnectionTypes(models.Model): connection_type_id = models.IntegerField(primary_key=True,default=re_sequence('connection_type_seq')) connection_type_name = models.CharField(max_length=100) connection_type_desc = models.CharField(max_length=300) connection_type_category = models.CharField(max_length=100) last_update_date = models.DateTimeField(default=dbcurr_ts) class Meta: managed = False db_table ='connection_types_test' verbose_name = 'connection_types_test' verbose_name_plural = 'connection_types_test' def __str__(self): return str(self.connection_type_id) class ConnectionDetails(models.Model): connection_id = models.IntegerField(primary_key=True,default=re_sequence('connection_seq')) connection_name = models.CharField(max_length=200) connection_type = models.ForeignKey(ConnectionTypes, on_delete=models.CASCADE) endpoint = models.CharField(max_length=100) port = models.IntegerField() login_id = models.CharField(max_length=100) login_password = fields.CharPGPPublicKeyField(max_length=100) connection_string_1 = fields.CharPGPPublicKeyField(max_length=100) connection_string_2 = fields.CharPGPPublicKeyField(max_length=100) connection_string_3 = fields.CharPGPPublicKeyField(max_length=100) aws_region = models.CharField(max_length=20) owner_id = models.IntegerField() last_update_date = models.DateTimeField(default=dbcurr_ts) working_schema = models.CharField(max_length=100) service = models.CharField(max_length=100) def generate_enc(mystrenc): return 'pass' class Meta: managed = False db_table = 'connection_details_test' verbose_name = 'connection_details_test' verbose_name_plural = 'connection_details_test' Model Form : class ConnectionForm(forms.ModelForm): login_password = forms.CharField(widget=forms.PasswordInput()) owner_id = forms.IntegerField(widget=forms.HiddenInput(), required=False) class Meta: model = ConnectionDetails exclude = ['connection_id','last_update_date'] View.py def addconnection(request): connectionform = ConnectionForm(request.POST or None) if connectionform.is_valid(): ownerqs = AuthUser.objects.values('id').get(username = request.user.username) connectionform.cleaned_data['owner_id'] = int(ownerqs['id']) connectionform.save() messages.success(request, f"sucess!") else: messages.success(request, f"Failure!") return render(request,'main/ssaddconnection.html',{"cform": connectionform,"CanUseMod":UserModules.objects.filter(user_id=request.user.id).filter(module_id=1).count(),"UserIsAuth":request.user.is_authenticated}) Anyone can help me on this?? Thanks, Aruna