Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why my server django database get Syntex error
why my server django database get Syntex error DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '----' 'USER': 'mai', 'PASSWORD': '----', 'HOST': '----' 'PORT': '26257', } }``` error is : 'USER': 'mai', On Console: 'USER': 'mai', ^ SyntaxError: invalid syntax -
Unable to iterate over all objects in table using objects.all()
I am writing a migration script that will iterate over all objects of a cassandra model (Cats). There are more than 30000 objects of Cat but using Cats.objects.all(), I am only able to iterate over 10000 objects. qs = Cats.objects.all() print(len(qs)) # returns 10000 print(qs.count()) # returns 30000 -
com.vmware.vapi.rest.httpNotFound - Vsphere API
I am trying to get my Vsphere version through API for program I am building. The thing is I keep receiving this error even though it worked previously. It stopped working now. Here is the command I run, but in Python django: curl -H "vmware-api-session-id: b00db39f948d13ea1e59b4d6fce56389" https://{api_host}/api/appliance/system/version Here is the erro: { "error_type": "NOT_FOUND", "messages": [ { "args": [], "default_message": "Not found.", "id": "com.vmware.vapi.rest.httpNotFound" } ] } -
For loop indentation is not taking place in jinja2 templating in vscode
I am writing a for loop or if else using jinja2 templating but it is not giving me indentation in vscode. Fore example, I wrote this: {% extends 'base.html' %} {% block content %} <h2>This is Item List</h2> {% for item in items %} <p>{{items}}</p> {% endfor %} {% endblock content %} But when I press Ctrl s or save it manually, it loses the indentation. The code becomes like this: {% extends 'base.html' %} {% block content %} <h2>This is Item List</h2> {% for item in items %} <p>{{items}}</p> {% endfor %} {% endblock content %} This is happening for for loops, if else and everything inside jinja2 templating. Not happening in normal python codes. This is not giving any error, but I feel distressed. How to solve it. -
'str' object has no attribute 'get' django rest framework
I'm trying to connect rest framework views to a template, the get method is working properly but when posting datas it gives me the error : views.py: class Login(APIView): serializer_class = LoginSerializer permission_classes = [IsAnonymous, ] template_name = 'accounts/login.html' renderer_classes = [TemplateHTMLRenderer] style = {'template_pack': 'rest_framework/vertical/'} def get(self, request): serializer = self.serializer_class() return Response({'serializer': serializer, 'style': self.style}) def post(self, request): payload = request.data serializer = self.serializer_class(data=payload) if serializer.is_valid(): user = authenticate(request, username=payload['username'], password=payload['password'] ) if user: login(request, user) response = { 'message': 'you logged in successfully!' } code = status.HTTP_200_OK else: response = { 'message': 'your username or password is wrong!' } code = status.HTTP_401_UNAUTHORIZED else: response = { 'error': serializer.errors } code = status.HTTP_403_FORBIDDEN return Response(data=response, status=code) I don't know where am I doing wrong , I appreciate if anyone can help me in this case -
Is There a possible way to align the list of apps displayed on the left side of the admin panel in django? [duplicate]
if you run a django website and go to admin panel you can see all the list of the models you created which is sorted in alphabetical order . is there any way i can change the sortnig order? -
Django global variable for all templates or context processor manipulation
I'm working on a website with 2 different languages. Text which should be translated is only in the template.htmls (index.html, accounts.html ... about 20 files) sometemplate.html ... <div>{% if ls == 'at' %}Deutschtext {% else %}english text{% endif %}</div> ... my context processor ... def language_selection(request): return {'ls': 'at'} ... This works, but how can I change the value of the context_processor from template? Or is there any other approach for a 'global variable' which can be changed and is accessible from all templates? -
Django, DRF: Two different models in one query set
How can I get the following two models in one query set? Sorting and searching must be performed. class Video(models.Model): title = models.CharField(max_length=300) image_url = JSONField() sample_image_url = JSONField(blank=True, null=True) sample_movie_url = models.URLField(max_length=1000, blank=True, null=True) review = JSONField(blank=True, null=True) ... class UserVideo(models.Model): title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000, unique=True) preview_url = models.URLField(max_length=1000, blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, db_index=True) ... I tried .union(), but I get the following error qs = Video.objects.all() qs2 = UserVideo.objects.all() print(qs.union(qs2)) django.db.utils.ProgrammingError: each UNION query must have the same number of columns By specifying the id in .values(), the union works successfully, but we need to get different fields for both models. Also, since we are using DRF, we need a way to work with ModelSerializer. -
how can i change this SQL to Django ORM code?
select * from sample join process on sample.processid = process.id where (processid) in ( select max(processid) as processid from main_sample group by serialnumber ) ORDER BY sample.create_at desc; models.py class Sample(models.Model): processid = models.IntegerField(default=0) serialnumber = models.CharField(max_length=256) ## class Process(models.Model): sample = models.ForeignKey(Sample, blank=False, null=True, on_delete=models.SET_NULL) Hi I have two models and I need to change this SQL query to Django ORM, Python code. How can I change the SQL query to ORM code? how can i change the subquery to ORM? Thanks for reading. -
how to save multiple forms on the same page, combining text input and uploading multiple files?
let's say I have 3 forms on the same page and each one has its own save button, the last 2 do multiple image loading, how can you write the view combining those 3 forms? I have no idea, I have tried many ways, I have read the django documentation but I cannot understand due to my inexperience, how to solve it <form enctype="multipart/form-data" method="post"> {% csrf_token %} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ form.name }}"> <input type="submit" value="OK"> </form> <form enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="file" name="garantia" class="type-file" multiple="" id="file-inputz" onchange="previewz()" accept="image/*" required=""> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </form> <form enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="file" name="fotosCarro" class="type-file" multiple="" id="file-input" onchange="preview()" accept="image/*" required=""> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </form> -
Django migration gives psycopg2.errors.DuplicateTable: relation error
I have previously restored the database for the system, and while i tried to migrate through the django applicaion, the following error is thrown. What is the possible cause and how can we mitigate such cases. I guess the problem is with the existing table conflict, will it solve the issue by delete/dropping the conflicting tables. Applying introduction.0001_initial...Traceback (most recent call last): File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "introduction_introduction" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, … -
whats the right way for read MySQL database with django
I'm new to django I have a local application I wrote in python that writes scientific data to a MySQL database hosted on a digital ocean droplet that also runs django. I'm experiencing an intermittent problem where occasionally (maybe 1 in 3 tries) a page request produces a 'bad gateway' error message. Refreshing the page will normally produces the correct page. A page example is http://104.131.165.99/garage/ The problem is annoying and I'm not sure what the cause is but I never understood models in django and I'm not sure how to even clearly ask my question. My local application uses pymysql to connect to the MySQL database thats part of the server where django is hosted, in otherwords a mysql database thats NOT(?) really associated with the instance of django running on the server. The code in my django app (see below) that runs when a page is requested uses pymysql with a host address of 127.0.0.1 to read and manipulate the MwSQL data. Whether or not this is the cause of my problem, I always wondered if this was the proper way to read mysql data in django considering the app writing to that database is on a different … -
Django serializer errors ('Invalid data. Expected a dictionary, but got {datatype}.')
-I am trying to create assignments (assignment can be created by user). -The API is working fine when i send request from DjangoRest Framework API the assignment is created successfully. -But in the actual form(Frontend form) when i try to post an assignment the following error is being generated. -PLease Help! Error that is being generated models.py def upload_to(instance, filename): return 'assignments/{filename}'.format(filename=filename) class Assignment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='assignments', blank=True, null=True) username = models.CharField(max_length=255, blank=True, null=True) title = models.CharField(max_length=20, blank=False, null=False) subject = models.CharField(max_length=20, choices=subject_choices, default=Statistics, blank=False) assignment_type = models.CharField(max_length=20, choices=assignment_choices, default=Assignment, blank=False) assignment_file = models.ImageField(_("Image"),upload_to=upload_to,default="", blank=False) description = models.CharField(max_length=50, blank=False) created_at = models.DateTimeField(auto_now_add=True) serializers.py class AssignmentSerializer(serializers.ModelSerializer): class Meta: model = Assignment fields = ('user','username','title', 'subject', 'assignment_type', 'assignment_file', 'description') views.py class CreateAssignmentView(APIView): parser_classes = [MultiPartParser, FormParser] serializer_class = AssignmentSerializer def post(self, request, format=None): assignment = request.data print(assignment) serializer = self.serializer_class(data = assignment) if serializer.is_valid(): print("valid") serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST) REACT Function for create assignments const createAssignment = (e) => { e.preventDefault(); let formData = new FormData(); console.log() const data = { user : user.user_id, username : user.full_name, title : assignmentTitle, subject : assignmentSubject, assignment_type : assignmentType, assignment_file : assignmentFile[0].name + " " + "(" … -
Django Rest Framework Postman 'POST' request error
I'm still having this error when trying to do a post request from postman. { "username": [ "This field is required." ], "password": [ "This field is required." ] } I can make the same post request successfully from my DRF localhost, but when i try on postman i get the error above. How can I solve it? Views.py class PlayThingList(viewsets.ModelViewSet): serializer_class = PlayThingSerializer queryset = PlayThing.objects.all() class UserViewset(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer Serializers.py class PlayThingSerializer(serializers.ModelSerializer): class Meta: model = PlayThing fields = '__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] urls.py router = DefaultRouter() router.register('playthings', PlayThingList, basename='playthings') router.register('users', UserViewset) urlpatterns = [ path('', include(router.urls)), ] -
RegexField validation error not being raised; Postman API request
Upon testing the response of an APIView with Postman, it's returning validated data pertaining to the query string attached to the request. In this case the query string consists of ?username="I___am_not_binny". Yet only strings with single underscores between characters are allowed. Upon making a request to the api endpoint it returns a 200 status yet it's suppose raise a bad request with a 400 status code. Tests ran through DRF with different string variations pass. Why is a 200 status code being returned? Strings tested: ["_This_is_me", "_This_is_me001_", "This_is_me_", "_____This_is_", "This_is_my_full_username", "WhoAm+"] ] Status: 200 OK { "username": "i___am_not_binny" } serializers.py class RegisterSerializer(ModelSerializer): username = RegexField( re.compile("^(_?[a-zA-Z0-9]+)+"), required=False, min_length=6, max_length=20, validators=[ character_validator, total_digits_validator, UniqueValidator(get_user_model().objects.all()) ] ) validators.py def character_validator(string): match = re.search(r"\W", string) if match: raise ValidationError("invalid character found", code="invalid") return string def total_digits_validator(string): match = re.findall(r"\d", string) if match and len(match) > 3: raise ValidationError("only up to 3 digits allowed in username") return string -
Weird behavior with model/object permissions and viewsets
I am experiencing some weird behavior where djangorestframework returns a 404 when trying to browse the browsable API, but attaching a ?format=json at the end returns a normal response. A simplified version of my project setup: #### API views ... class UserRUDViewSet( drf_mixins.RetrieveModelMixin, drf_mixins.UpdateModelMixin, drf_mixins.DestroyModelMixin, viewsets.GenericViewSet, ): """Viewset combining the RUD views for the User model""" serializer_class = serializers.UserSerializer queryset = models.User.objects.all() permission_classes = [permissions.RudUserModelPermissions | permissions.RudUserObjectPermissions] ... #### app API urls ... _api_prefix = lambda x: f"appprefix/{x}" api_v1_router = routers.DefaultRouter() ... api_v1_router.register(_api_prefix("user"), views.UserRUDViewSet, basename="user") #### project urls from app.api.urls import api_v1_router as app_api_v1_router ... api_v1_router = routers.DefaultRouter() api_v1_router.registry.extend(app_api_v1_router.registry) ... urlpatterns = [ ... path("api/v1/", include((api_v1_router.urls, "project_name"), namespace="v1")), ... ] The problem: I am trying to add permissions in such a way that: A user can only retrieve, update or delete its own User model instance (using per-object permissions which are assigned to his model instance on creation) A user with model-wide retrieve, update or delete permissions (for example assigned using the admin panel), who may or may not also be a django superuser (admin) can RUD all user models. To achieve this my logic is as follows: Have a permissions class which only checks if a user has per-object … -
'NoneType' object has no attribute 'profile'
Trying to update profile picture for student models but i get this error. 'NoneType' object has no attribute 'profile'. Idk if it has something to do with the views.py but it probably does. My views.py for user app: from django.contrib.auth.decorators import login_required from .forms import UpdateProfileForm from django.contrib import messages from main.models import Student from .models import Profile @login_required def profile(request): if request.method == 'POST': student = request.POST.get('student') p_form = UpdateProfileForm( request.POST, request.FILES, instance=student.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Student picture has been updated!') return redirect('student_profiles') else: p_form = UpdateProfileForm() context = { 'p_form': p_form, 'students': Student.objects.all() } return render(request, 'user/profiles.html', context) Signals.py: from django.dispatch import receiver from main.models import Student from django.contrib.auth.models import User from .models import Profile @receiver(post_save, sender=Student) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(student=instance) @receiver(post_save, sender=Student) def update_profile(sender, instance, created, **kwargs): if created == False: instance.profile.save() Profile model: from main.models import Student from PIL import Image class Profile(models.Model): student = models.OneToOneField( Student, default=None, null=True, on_delete=models.CASCADE, related_name="profile") image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.student.firstname} {self.student.surname} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) https://i.stack.imgur.com/sXJEk.png -
django ValueError: source code string cannot contain null bytes
I want to create an app but I want to use my existing tables so I run inspectdb command on terminal from django.db import models class OhrmJobTitle(models.Model): job_title = models.CharField(max_length=100) job_description = models.CharField(max_length=400, blank=True, null=True) note = models.CharField(max_length=400, blank=True, null=True) is_deleted = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'ohrm_job_title' generated by inspectdb based on my table I'm getting an error trying to runserver command below is the traceback if someone is interested Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\PycharmProjects\hrmorms\venv\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\user\PycharmProjects\hrmorms\venv\lib\site- packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\user\PycharmProjects\hrmorms\venv\lib\site- packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\user\PycharmProjects\hrmorms\venv\lib\site- packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\user\PycharmProjects\hrmorms\venv\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\user\PycharmProjects\hrmorms\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\PycharmProjects\hrmorms\venv\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\user\PycharmProjects\hrmorms\venv\lib\site-packages\django\apps\config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "C:\Users\user\AppData\Local\Programs\Python\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 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File … -
django and AWS: Which is better lambda or fargate
I currently use docker-compose.yml to deploy my django application on an AWS EC2 instance. But i feel the need for scaling and load balancing. I have two choices AWS lambda (using zappa - but heard that this is no longer maintained) AWS fargate (not sure how to use the docker-compose.yml file here) My django application required some big libraries like pandas etc. Currently i use docker-compose.yml file to run the django application. My docker-compose.yml file is as below I have django app image, reactjs app image, postgres, redis and nginx. # My version of docker = 18.09.4-ce # Compose file format supported till version 18.06.0+ is 3.7 version: "3.7" services: nginx: image: nginx:1.19.0-alpine ports: - 80:80 volumes: - ./nginx/localhost/configs:/etc/nginx/configs networks: - nginx_network postgresql: image: "postgres:13-alpine" restart: always volumes: - type: bind source: ../DO_NOT_DELETE_postgres_data target: /var/lib/postgresql/data environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} PGDATA: "/var/lib/postgresql/data/pgdata" networks: - postgresql_network redis: image: "redis:5.0.9-alpine3.11" command: redis-server environment: - REDIS_REPLICATION_MODE=master networks: # connect to the bridge - redis_network celery_worker: image: "python3.9_django_image" command: - sh -c celery -A celery_worker.celery worker --pool=solo --loglevel=debug depends_on: - redis networks: # connect to the bridge - redis_network - postgresql_network webapp: image: "python3.9_django_image" command: - sh -c python manage.py runserver 0.0.0.0:8000 … -
solid_i18n overriding current language
I'm using solid_18n urls just so that the default language is used as root path. I have SOLID_I18N_USE_REDIRECTS = True to redirect to the preferred language which is stored in request.session, however once you select a language, if you try going back to the default language using Django's view i18n.set_language it will redirect back to the other language. You end up stuck at that language. For example, you current language is Spanish and your current path /es/whatever. You try switching back to English, which is the default language, through /i18n/setlang/. But instead of changing the language to English and redirecting to /whatever, it's going back to /es/whatever with Spanish still active. Note that you can still change to non-default languages by setting the language or browsing to the corresponding prefix. For example /de/whatever or selecting it through set_language will work and will set German as current language, store it in the session and redirect accordingly. This is the solid_i18n middleware function: class SolidLocaleMiddleware(LocaleMiddleware): def process_request(self, request): check_path = self.is_language_prefix_patterns_used language_path = get_language_from_path(request.path_info) if check_path and not self.use_redirects: language = language_path or self.default_lang else: language = trans.get_language_from_request(request, check_path) set_language_from_path(language_path) trans.activate(language) request.LANGUAGE_CODE = trans.get_language() And this is Django: def set_language(request): """ Redirect … -
How to get absolute path in Django when using nginx?
I have a django project running on nginx and waitress. Here are the nginx settings: # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name localhost; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias C:/Users/Administrator/Documents/mydjangoproject/media; # your Django project's media files - amend as required } location /static { alias C:/Users/Administrator/Documents/mydjangoproject/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { proxy_pass http://localhost:8080; } In my views.py file, when I use my_url = request.build_absolute_uri(uri) I get http://localhost:8080/ instead of https://example.com How can I accomplish to get that absolute path (https://example.com)? -
BaseSerializer.save() takes 1 positional argument but 2 were given; Django rest Framework
Here is my error message TypeError at /users/auth/registration/ BaseSerializer.save() takes 1 positional argument but 2 were given Request Method: POST Request URL: http://127.0.0.1:8000/users/auth/registration/ Django Version: 4.0.3 Exception Type: TypeError Exception Value: BaseSerializer.save() takes 1 positional argument but 2 were given Exception Location: C:\Users\Chika Precious\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\dj_rest_auth\registration\views.py, line 85, in perform_create Serializers Here is my serializer class class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['id', 'email', 'first_name', 'last_name', 'occupation', 'phone', 'sex'] -
HStore.DictionaryField returns a string when this part of the code exist in Django. Not sure why
Will try to explain this as best I can. The snippet of code see below screenshot (narrowed it down to line 358) causes models with HStore.DictionaryField on, another section of the project, to return a string instead of the HStore Dict object. Removing this section resolves the issue fixes the issue and returns the HStore Dict. Cannot figure out how this snippet of code can affect that. This is in a admin.py class SomeModel(models.Model): allowed_vals = hstore.DictionaryField() -
Django : Upload Files to an container of a Azure Blob Storage
I want to have an application that upload files to an container of an Azure Blob Storage. I started by doing an application that uplod the files in a static media folder. Now I want to change it that the files go the the container. I have three problems to fix : The models.py, where I do not know how I should modify it. What do I do with the moldels.Filefield. I used it to define the folder to upload the file but right now I should not need it, should I ? If I am not wrong, I need it because of my form. This is my view upload. The view works but I am not sure that I did it the best way to upload to the container. Is it possible to do it in a different more efficient or nicer ? Should I add something in my settings.py file ? models.py class UploadFiles(models.Model): User = models.CharField(max_length=200) Documents = models.FileField() PreviousFilename = models.CharField(max_length=200) NewFilename = models.CharField(max_length=200) SizeFile = models.IntegerField() Uploaded_at = models.DateTimeField(auto_now_add=True) views.py from io import BytesIO import os from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from datetime import datetime, timedelta from … -
How i can get a value field from a foreignkey field properly
i want to get a value of a field (named "width") from foreignkey field named square exit on my form to print it on a pdf: Here is the code line that i have used it to get this value("width"): width = float(FormulaireIng.objects.get(square = FormulaireIng.objects.last()).values_list('width')) Here is the models.py: class FormulaireIng(models.Model): square = models.ForeignKey(Square, on_delete=models.CASCADE) class Square(models.Model): width = models.FloatField(verbose_name="Width", max_length=50) an error displayed after developing that: ValueError at /pdf/ Cannot query "4.0": Must be "Square" instance. How i can get a value field from a foreignkey field properly from a model. Thanks in advance.