Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add multiple domains into DJANGO_ALLOWED_HOSTS as an environment variable
in django 4.1 application I'm trying to add several allowed hosts in my .env fiel as an environment variable like this -> DJANGO_ALLOWED_HOST=synapse-developmentcenter.am www.synapse-developmentcenter.am 127.0.0.1 localhost 0.0.0.0 but only first domain working correctly and after echo $DJANGO_ALLOWED_HOST shows only synapse-developmentcenter.am and here is my settings.py line addressing .env file. running cat .env showing coorectly and when trying to export it again only first domain getting there for the rest it shows -> bash: export: `127.0.0.1': not a valid identifier like this ALLOWED_HOSTS = [] if not DEBUG: ALLOWED_HOSTS += os.environ.get('DJANGO_ALLOWED_HOST').split(' ') I tried chane variable types to this -> [DJANGO_ALLOWED_HOST=synapse-developmentcenter.am www.synapse-developmentcenter.am 127.0.0.1 localhost 0.0.0.0] or ["DJANGO_ALLOWED_HOST=synapse-developmentcenter.am www.synapse-developmentcenter.am 127.0.0.1 localhost 0.0.0.0"] even like this -> DJANGO_ALLOWED_HOST="synapse-developmentcenter.am www.synapse-developmentcenter.am 127.0.0.1 localhost 0.0.0.0" but neihet of them worked -
Why My PDF Files get corrupted when I am uploading them through Django admin site?
I I am creating a simple web page for downloading pdf files, file uploads are only admin side. This is my model for pdf file. As I download the file from front side, the file is corrupted, urls are connfigured properly, the file get's corrupted while django is saving my model, I assume this from the fact that my staticfiles also contain a corrupt version of file. class Paper(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) display_name = models.CharField(max_length=200) source_file = models.FileField() -
How to combine Django TestCase test wit PyTest test in one tests.py file?
I have code in tests.py (Django tests): class MyTest1(TestCase): ... class MyTest2(TestCase): ... class MyTest3(TestCase): ... as well as few pytest tests (in regular functions with proper pytest decorators), but Django after using command: python manage.py test is not taking into account pytest tests. This tests are not used. What should I change in my tests.py file? How to deal with two types of tests? -
Raise 404 exception in django when using Login Required
I have little problem with django when i want use login required i get error 404, i use mysql database and after I create user in database, this problem is occuring with login page. My code is: @login_required(login_url=reverse_lazy("login")) def login_user(request): cursor = connections['default'].cursor() if request.method == "GET": return render(request,'html/login_user.html') if request.method == "POST": usrn = request.POST['username'] password = request.POST['password'] if cursor.execute(f"SELECT username,password FROM users WHERE username='{usrn}' AND password='{password}';"): return redirect("home_login") else: messages.warning(request,"Username/Password incorrect,please try again.") return render(request,'html/login_user.html') from django.contrib import admin from django.urls import path from .views import home,product,contact,about,login_user,register_user,product_info,cart,home_login urlpatterns = [ path('', home,name='home'), path('product',product,name='product'), path('contact',contact,name='contact'), path('about',about,name='about'), path('account/login/',login_user,name='login'), path('register',register_user,name='register'), path('product_info',product_info,name='product_info'), path('cart',cart,name='cart'), path("home",home_login,name="home_login") ] -
How to sort products in django?
There is a page with products. Can you tell me how to make sure that the goods are sorted in the way that the user chose in the form?That is, there was a button that the user clicked on and could sort the goods, for example, from the cheapest to the most expensive, and vice versa, then he could sort the goods by novelty, etc Water code: `model.py class Product (models.Model): title = models.CharField(max_length=50,verbose_name='Заголовок') slug = models.SlugField(max_length=255,unique=True,db_index=True,verbose_name='URL') content = models.TextField(blank=True,verbose_name='Общее описание') structure = models.TextField(blank=True,verbose_name='Состав') care = models.TextField(blank=True,verbose_name='Уход') photo = models.ImageField(upload_to="photo/%Y/%m/%d/",blank=True,verbose_name='Фото') photo2 = models.ImageField(upload_to="photo/%Y/%m/%d/",blank=True, verbose_name='Фото2') photo3 = models.ImageField(upload_to="photo/%Y/%m/%d/",blank=True, verbose_name='Фото3') time_create = models.DateTimeField(auto_now_add=True,verbose_name='Время создания') time_update = models.DateTimeField(auto_now=True,verbose_name='Время изменения') price = models.DecimalField(max_digits=15,decimal_places=2,verbose_name='Цена') available = models.BooleanField(default=True,verbose_name='Наличие') is_published = models.BooleanField(default=True,verbose_name='Публикация') prod_sub_category = models.ForeignKey('Category', on_delete=models.DO_NOTHING,verbose_name='Выберите категорию') > subproduct = models.ForeignKey('Subcategory', on_delete=models.DO_NOTHING,verbose_name='Выберите подкатегорию')` -
when i runserver (python manage.py runserver) this error is raised: TypeError: a bytes-like object is required, not 'str'
I tried deploying my django postgresql app using Render. The deploy worked but no data is being returned. Also, when I try to load seed data or run the server from my directory the following error is thrown: Traceback (most recent call last): File "/Users/xxx/xxx/xxx/xxx/manage.py", line 22, in <module> main() File "/Users/xxx/xxx/xxx/xxx/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/core/management/__init__.py", line 386, in execute settings.INSTALLED_APPS File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/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 "/Users/xxx/xxx/xxx/xxx/project/settings.py", line 114, in <module> 'default': dj_database_url.parse(os.environ.get('DATABASE_URL'), conn_max_age=600), File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/dj_database_url.py", line 94, in parse if "?" in path and not url.query: TypeError: a bytes-like object is required, not 'str' here is part of my settings.py: DATABASES = { 'default': dj_database_url.parse(os.environ.get('DATABASE_URL'), conn_max_age=600), } I've also tried: DATABASE_URL = os.environ.get('DATABASE_URL') DATABASES = { … -
How to get multiple field values, when a foreign key is called in django
I have a Attendance model class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) date = models.DateField() day = models.CharField(max_length=10) in_time = models.CharField(max_length=5) out_time = models.CharField(max_length=5) Here is the Employee model class Employee(models.Model): emp_id = models.CharField(max_length=10,primary_key=True) emp_type = models.CharField(max_length=50) name = models.CharField(max_length=100) epf_no = models.CharField(max_length=10) nic_no = models.CharField(max_length=15) appoinment_date = models.DateField() termination_date = models.DateField() address = models.CharField(max_length=50) mobile_no = models.CharField(max_length=15) email = models.EmailField(max_length=50) bank_name = models.CharField(max_length=50) bank_branch = models.CharField(max_length=20) bank_acc_name = models.CharField(max_length=20) bank_acc_no = models.CharField(max_length=15) active_status = models.BooleanField(default=True) I'm getting data from Attendance model attendance_record = Attendance.objects.filter(date = date).values() Here for the employee attribute I'm automatically getting the emp_id field.But I want to get the name field as well How to do it.? -
what can i do to send json.dumps as list in django channels?
I want to take the player list from the room and send it to react with the room websocket(django channels). I need a list to handle all users but websocket turns a string like this this is not array pure string! [{"model": "api.roomusers", "pk": 396, "fields": {"user_name": "kevin", "score": null}}] Here is my consumers.py roomUsers = serializers.serialize( "json", models.RoomUsers.objects.filter(room=isRoomExist), fields=('user_name', 'score')) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'user_data', 'roomUsers': roomUsers, } ) def user_data(self, event): roomUsers = event["roomUsers"] async_to_sync(self.send(text_data=json.dumps( {"type": "user_data", "roomUsers": roomUsers}))) react side case "user_data": console.log(data.roomUsers); console.log(typeof(data.roomUsers)); break; **react side turn says data.roomUsers is string not an array. ** I am stuck here and I don't have an opinion to solve this situation -
Django Rest Framework how to display related models as one json file
I have a few different models with a fact table of scenarios and 6 dimension tables that relate to it below as examples: class fScenario(models.Model): #Variables scenarioId = models.IntegerField(primary_key=True) description = models.CharField(max_length=100) def __str__(self): return str(self.scenarioId) def get_absolute_url(self): return reverse('scenario-detail', args=[str(self.scenarioId)]) class Meta: ordering = ['scenarioId'] class dADA(models.Model): #Variables scenarioId = models.ForeignKey(fScenario, on_delete=models.CASCADE) dateTimeId = models.DateTimeField('ADA Time/Date') latitutde = models.FloatField(default=0) longitude = models.FloatField(default=0) instanceType = models.CharField(max_length=50, default='ADA') def __str__(self): return f'{self.scenarioId}, {self.instanceType}' class Meta: ordering = ['dateTimeId'] serializers.py class fScenarioSerializer(serializers.ModelSerializer): class Meta: model = fScenario fields = ['scenarioId', 'description'] class dADASerializer(serializers.ModelSerializer): scenarioId = fScenarioSerializer(read_only=True) class Meta: model = dADA fields = ['scenarioId', 'dateTimeId', 'latitutde', 'longitude', 'instanceType'] urls.py router = routers.DefaultRouter() router.register(r'fScenario', views.fScenarioViewSet) router.register(r'dADA', views.dADAViewSet) urlpatterns = [ path('', include(router.urls)), views.py class fScenarioViewSet(viewsets.ModelViewSet): queryset = fScenario.objects.all() serializer_class = fScenarioSerializer class dADAViewSet(viewsets.ModelViewSet): queryset = dADA.objects.all() serializer_class = dADASerializer I'm using rest framework view sets and I currently can see in my API separate fScenario and dADA views but cant figure out how to link the dADA to the fScenario view on one page. -
How to change styles for an import form (django-import-export)?
How to change styles for an import form (django-import-export)? -
DRF Q Filter string working in Django shell_plus, but not in django-filter code
I have a DRF project where I use Q filters to filter the query set. The search value will be used to search a string field "name" and tested if it is an integer and then tested if it is eq to "port" or part of a range defined by "port" and "port_end". I need to modify the Q filter based on some conditions, so I thought it would be easy to define the query based on conditions and use it in the filter. I was thinking that there might be an issue that the value is a string and the field in the DB an integer. But that is not the case I also tried to have fixed values in the string as integer and string, but that was not the issue. Also a int(value) did not change anything. If I do this in the Django shell_plus, then I get proper results: >>> value = "22" >>> query = Q(name__icontains=value)|Q(port__exact=value)|(Q(port__lte=value)&Q(port_end__gte=value)) >>> items = MyObject.objects.filter(query) >>> print(items) If I do the same in my DRF filter code then the "items" query has only matches for the name field. query = Q(name__icontains=value)|Q(port__exact=value)|(Q(port__lte=value)&Q(port_end__gte=value)) items = queryset.filter(query) I have remove the filter on … -
Delete rows or sort model if column value is less than given value?
I have a table model. In one column of the table, the data is in the form - date-time. Dates may vary slightly. How to compare the column of the model table through a loop or in some other way and (provided that the date in the column is less than a certain given date) delete the current row? Delete those rows from the model if the value in the column (date time) of the table is less than the given one. -- "value" = 2023-01-04 10:00:00 -- queryset_1_sorted = Model_1.objects.order_by("datetime" < "value") -- datetime temper_1 temper_2 g_rashod temper_nv 0 2023-01-02 10:00:00 58.13 49.35 70.520 1.4 1 2023-01-02 11:00:00 57.44 49.12 89.805 1.4 2 2023-01-02 12:00:00 57.82 49.30 89.187 1.4 3 2023-01-02 13:00:00 58.08 49.62 89.079 1.4 4 2023-01-02 14:00:00 58.20 49.77 89.081 2.1 225 2023-10-02 19:00:00 65.67 53.90 87.998 -7.6 226 2023-10-02 20:00:00 66.80 54.98 87.970 -8.1 227 2023-10-02 21:00:00 67.37 55.53 87.946 -8.1 228 2023-10-02 22:00:00 67.76 55.87 87.973 -8.1 229 2023-10-02 23:00:00 68.02 56.09 87.942 -8.1 -
Test one detail page of django website using TestCase
I got error while running tests: p_pattern = url_pattern.pattern.regex.pattern AttributeError: 'int' object has no attribute 'pattern' while try to test "detail pages", all other tests, so far, works fine. I have used in tests.py syntax like: response = self.client.get(reverse('employee_detail', (3,))) assert response.status_code == 200 and: response = self.client.get('/employee-detail/3/') self.assertEqual(response.status_code, 200) My urls.py corresponding line is: path("employee-detail/<int:employee_id>/", views.EmployeeDetailView.as_view(), name='employee_detail'), My tests failed on both examples. -
Is there a way I could send a book primary key to a url in another django app?
I want to make a book marketing web app using Django and I want to show the book details using another Django app, and I need the book primary key in the details app. my question is what is the best way to pass the book pk to the detail URL defined in the book_details app. this is my home urls.py: from django.urls import path, include from .views import * urlpatterns = [ path('', home_page_view, name='home'), path('books/', include('book_details.urls'), name='books'), ] and this is my details app (book_details) urls.py: from django.urls import path, include from .views import * app_name = 'book_details' urlpatterns = [ path('<int:pk>/', book_details_view, name="book_detail") ] I tried doing it like this in the home app template and it does not work: <a href="{% url 'book_details:book_detail' post.pk %} " class="book-card-link"> the Error: Reverse for 'book_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P[0-9]+)/\Z'] Sorry if my question is not very clear, it's my first time asking a question here, Thanks. -
sending json object to Django framework returns a 500 code error
I am sending an object using AJAX to a Django view. The data I am sending is mouse movement which is sent every 10 seconds to the server to be saved. Now, I have no problem reading my data from the client and server sides. The data gets saved in the database, but I get a 500 error message every time the function sends to the server gets executed. I tried to use fetch and got this error message: POST error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON I searched about this error, and my understanding is that the problem is with the data type, but I am unsure how I can trace the problem and fix it. Could someone help me troubleshoot this issue? here is my js function: var target_id = ''; var eventsLog = {"mouse": []}; function logMouse(event){ target_id = event.target.id; currDate = new Date() start_time = currDate.getHours() + ':' + currDate.getMinutes() + ':' + currDate.getSeconds() + ':' + currDate.getMilliseconds(); var insert = [start_time, target_id]; (eventsLog.mouse).push(insert); } var timesPerSecond = 5; var wait = false; $(document).on('mousemove', function (event) { if (!wait) { logMouse(event); wait = true; setTimeout(function () { wait = false; }, 1000 … -
My custom widget does not get rendered when the field is added using a parameter
Why is my widget not rendered? The render methond of SiteNameInputWidget is never hit. from django import forms from django.template import loader from django.utils.safestring import mark_safe class SiteNameInputWidget(forms.TextInput): template_name = 'sites/widgets/SiteNameInputWidget.html' def __init__(self, attrs=None, prefix_for=None): super().__init__(attrs) self.prefix_for = prefix_for def render(self, name, value, attrs=None, renderer=None): super().render(name, value, attrs, renderer) class SiteNameForm(forms.Form): def __init__(self, prefix_for=None, *args, **kwargs): super(SiteNameForm,self).__init__(args,kwargs) self.fields['site_prefix'] = forms.CharField(widget=SiteNameInputWidget(prefix_for=prefix_for)) If I define the Form like this (an don't pass prefix_for in the constructor) it gets called. class SiteNameForm(forms.Form): site_prefix = forms.CharField(widget=SiteNameInputWidget(prefix_for='TEST')) -
How to compare the columns of three tables of the model through a loop and copy the current row if equal?
I have three table models. In one column of the table, the data is in the form - date-time (datetime). Each of the three tables has this column (datetime). Dates may vary slightly. And I need to copy the data from all three model tables into one empty model - only those rows - where the values in a certain column (datetime) are equal to each other for these three model tables. You can even do something similar by converting to a DataFrame . How to compare the columns of three tables of the model through a cycle and, if equal, send the current row to another model? -- datetime temper_1 temper_2 g_rashod temper_nv 0 2023-01-02 10:00:00 58.13 49.35 70.520 1.4 1 2023-01-02 11:00:00 57.44 49.12 89.805 1.4 2 2023-01-02 12:00:00 57.82 49.30 89.187 1.4 3 2023-01-02 13:00:00 58.08 49.62 89.079 1.4 4 2023-01-02 14:00:00 58.20 49.77 89.081 2.1 225 2023-10-02 19:00:00 65.67 53.90 87.998 -7.6 226 2023-10-02 20:00:00 66.80 54.98 87.970 -8.1 227 2023-10-02 21:00:00 67.37 55.53 87.946 -8.1 228 2023-10-02 22:00:00 67.76 55.87 87.973 -8.1 229 2023-10-02 23:00:00 68.02 56.09 87.942 -8.1 -- datetime rashod_gas 0 2023-01-02 00:00:00 71.44 1 2023-01-02 01:00:00 71.55 2 2023-01-02 02:00:00 71.60 3 … -
Problemas al momento de hacer manage.py check o manage.py migrate [closed]
buenas tardes estoy tratando de realizar un proyecto nuevo en django y hago un python3 manage.py migrate o python3 manage.py check para verificar si esta en correcto todo y me sale este error, ayuda por favor C:\Users\JOSE\sistemas\proyectoDjango\Test (test19) λ python3 manage.py check Traceback (most recent call last): File "C:\Users\JOSE\sistemas\proyectoDjango\Test\manage.py", line 22, in main() File "C:\Users\JOSE\sistemas\proyectoDjango\Test\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django\core\management_init_.py", l ine 446, in execute_from_command_line utility.execute() File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django\core\management_init_.py", l ine 420, in execute django.setup() File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django\apps\config.py", line 169, in c reate if mod_path and cls_name[0].isupper(): IndexError: string index out of range intente con manage.py migrate me abre el editor de visual vasic extactamente enter image description here -
Django Correct Date / Time not PC date/time
Is there a way to get the exact date/time from the web rather than taking the PC date/time? I am creating a website where the answer is time relevant. But i don't want someone cheating by putting their pc clock back. When i do: today = datetime.datetime.today() or now = datetime.datetime.utcnow().replace(tzinfo=utc) i still get whatever time my pc is set to. Is there a way to get the correct date/time Thanks in advance for any help -
How can I make a password confirmation in Django to access an specific page?
I am looking to add a password confirmation before use can delete their account. I just found one tutorial for this, it is precisely what I want - add a password confirmation like GitHub's when we try to delete a repo or something else. https://simpleisbetterthancomplex.com/media/2016-08-15-how-to-create-a-password-confirmation-view/github.png But, I can not add a new field like in the tutorial. Is there another way that I can do it? For now, I've tried something, but I just got a 405 error. This is my view code: class ConfirmPasswordToDeleteAccountView(LoginRequiredMixin, FormView): form_class = Form template_name = 'dashboard/components/confirm_password_modal' def form_valid(self, form): user = self.request.user password = form.cleaned_data.get('password') if user.check_password(password): user.delete() logout(self.request) else: form.add_error('password', 'Incorrect password. Please try again.') return self.form_invalid(form) This is the modal where it is happening, but after submitting nothing happens, only a 405 error and the account is not deleted: <a href="#" onclick="return toggleModal()"> <button type="button" data-modal-target="authentication-modal" data-modal-toggle="authentication-modal" > Delete Account </button> </a> <div id="authentication-modal" tabindex="-1" aria-hidden="false"> <div> <div> <button type="button"> <svg aria-hidden="false" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg> <span>Close modal</span> </button> <div> … -
If i built a Django Website, can i make an api with Django Rest Framework of the same logic to make a mobile client later?
What i mean is lets say i have a totally functional and regular Django Web App. But then the client tells me they want a mobile client of the same app. So that means i should make an api, to get the data on the client. Django Rest Framework is the way to make api with Django, but i dont know if i can add the api layer after making the regular Django App and leverage or take advantage of the existing logic i have previously created so the both web app and api can coexist. Or if i should have started making the app with django rest framework from the begining.(Wich isnt convenient for me now). What do you think? What are my options? Thanks in advance! -
Error parsing template venv\Lib\site-packages\wagtail\admin\templates\wagtailadmin\bulk_actions\confirmation\form_with_fields.html: form.html
I am using Django for my main project but also wagtail for the blog section. I am also using sass in my project. When I run the command ./manage.py compilescss, I get the above error. There are no form templates in my project and this is obviously referencing wagtail so I don't really know how to remove the error. Anyone have any ideas? -
Django: A None DateInput does not pass through form validate. How can I fix it?
I use UpdateView and created a field called date_updated. When the user creates, e.g., a Group, there are zero updates. In models.py I defined: date_updated = models.DateTimeField(null=True) Then in forms.py I created the update form, e.g., class UpdateGroupForm(forms.ModelForm): class Meta: model = Group fields = ['name','date_updated'] In templates I call my form, as expected in the iteration {% for field in form %}, field.value = None for the specific field date_updated, and because of this I believe is not updating. In views.py I have the following in the UpdateGroup class def form_valid(self, form): if form.instance.owner == self.request.user: form.instance.date_updated = timezone.now() return super().form_valid(form) else: return super().form_invalid(form) I tried to replace the empty value with a fake date considering in my templates the following: {% if field.name == 'date_updated' and field.value == None %} <input type="date" name="date_updated" value="2000-01-01" format="yyyy-mm-dd" required disabled> {% else %} But it doesn't work also, I cannot validate the form and update my values with the first update.. What can I do? The only thing that works is to remove date_updated from forms.py, do the first updated and then restore it forms.py. Now because is not an empty Date everything works and I can proceed with a second … -
Null is passed to todos_id while submitting form eventhough i've changed it
this is my view which is createview and i've used custom form and send current user id to the form class createToDo(CreateView): success_url = 'home' form_class = ToDoForm template_name = 'home.html' user_id = None test = 'vaseem' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user_id'] = self.user_id return kwargs def get(self, request: HttpRequest, *args: str, **kwargs) -> HttpResponse: self.user_id = request.user.id return super().get(request, *args, **kwargs) this is my form class ToDoForm(ModelForm): todos_id = forms.CharField(widget=forms.TextInput(attrs={'value':'test'})) title = forms.CharField(widget=forms.TextInput(attrs={'id':'title'})) description = forms.CharField(widget=forms.Textarea(attrs= {'id':'description','cols':30,'rows':2})) date = forms.DateField(widget=forms.DateInput(attrs={'type':'date'})) class Meta(): model = ToDo fields = ('title','description','date','todos_id') def __init__(self,user_id = None,*args, **kwargs): self.id_data = user_id super(ToDoForm,self).__init__(*args,**kwargs) self.fields['todos_id']= forms.CharField(widget=forms.TextInput(attrs= {'value':self.id_data,'style':'display:none;'})) this is the post-data,from this data it is clear value is not none then what is the problem Variable Value csrfmiddlewaretoken 'QCBi8WL9GYK0LdRx1FQq7sXDNjSaKjjv8IWnLwQ63toz43uNhGtM1H8C50c54zUC' todos_id 'None' title 'test' description 'testdesc' date '2023-02-23' this is my model which is connected to my user moodel class ToDo(models.Model): todos = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=75,null=False) description = models.TextField(null=False) date = models.DateField(null=False) done = models.BooleanField(default=False) this is the error showing, eventhough i can see the value in the todos_id input while inspecting IntegrityError at /createToDo null value in column "todos_id" of relation "ToDoApp_todo" violates not-null constraint DETAIL: Failing row contains (21, test, testdesc, 2023-02-23, f, … -
Save data from several models to one summary by the smallest size of one of this?
I have three databases - table models. In which there is a different amount of data - a different number of rows of elements in the database table. One table has 100 rows - the other model table has 150 rows. I’m going to transfer the data from these models to another one - a general summary table model. Sequentially transferring data from each model. How can I do this - to transfer data to the summary table - only by the size (number of rows) of the smallest model table? -- def file_upload_button(request): context = {} queryset_summ = Model_upload_summ.objects.all() queryset_1 = Model_upload_teplo.objects.all() queryset_2 = Model_upload_gvs.objects.all() queryset_3 = Model_upload_topgas.objects.all() datetime_1 = [d.datetime for d in queryset_1] datetime_2 = [d.datetime for d in queryset_2] datetime_3 = [d.datetime for d in queryset_3] numbers_1 = len(datetime_1) numbers_2 = len(datetime_2) numbers_3 = len(datetime_3) if numbers_1 <= numbers_2 and numbers_1 <= numbers_3: # save numbers_1 (rows of queryset Models) into queryset_summ or Model_upload_summ elif numbers_2 <= numbers_1 and numbers_2 <= numbers_3: # not active if first condition (above) id done elif numbers_3 <= numbers_1 and numbers_3 <= numbers_2: # not active if first condition (above) id done