Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'DateField' object has no attribute 'value_from_datadict'
I've been researching everywhere for an answer for this, but I'm just trying to add a widget to my DateField created on my models.py, where you can see the actual calendar, as if you were doing it directly through html with an input type=date. Since I have a few date fields, this has become a problem because they all need to have the same format as the rest of the form and the widget. Feel like the question has been answered but none of the answers or things I've found have returned a correct answer. models.py class InfoPersonal(models.Model): Fecha = models.DateField() cargo_act = models.CharField(max_length=100) Nombres_y_Apellidos_completos = models.CharField(max_length=100) Lugar = models.CharField(max_length=100) Fecha_de_Nacimiento = models.DateField(null=True) Discapacidad= models.BooleanField() grado = models.CharField(max_length=100, blank=True) Edad = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(80)]) Tipo_de_Sangre = models.CharField(max_length=50, choices=sangre_choice) Estatura = models.FloatField(validators=[MaxValueValidator(3.0), MinValueValidator(0.5)]) Direccion_Domicilio_actual = models.CharField(max_length=100) Manzana = models.CharField(max_length=100) Villa = models.CharField(max_length=100) parroquia = models.CharField(max_length=100) Telefono_Domicilio = models.IntegerField(blank=True, null=True) Telefono_Celular = models.IntegerField(blank=True, null=True) Telefono_Familiar = models.IntegerField(blank=True, null=True) cedula = models.IntegerField() estado_civil = models.CharField(max_length=50, choices=list_estado_civil) #Conyuge Nombre_completo_del_conyuge= models.CharField(max_length=100,blank=True) Direccion_Domiciliaria=models.CharField(max_length=100,blank=True) Telefono=models.IntegerField(blank=True, null=True) Cedula_de_Identidad=models.IntegerField(blank=True, null=True) Fecha_de_NacimientoC=models.DateField(blank=True, null=True) Direccion_Trabajo=models.CharField(max_length=100,blank=True) Telefono_del_trabajo=models.IntegerField(blank=True,null=True) #Hijos Nombres= models.CharField(max_length=100,blank=True) Lugar_y_Fecha_de_NacimientoH = models.CharField(max_length=100,blank=True) Esposo_con_Discapacidad = models.BooleanField(blank=True) Hijos_con_Discapacidad= models.BooleanField(blank=True) #InfoFamiliares Apellidos_y_Nombres_1= models.CharField(max_length=100,blank=True) Telefono_Familiar_1 = models.IntegerField(blank=True,null=True) Fecha_Nacimiento_1 = models.DateField(blank=True,null=True) Relacion_de_Parentesco_1 = models.CharField(max_length=100,blank=True) Apellidos_y_Nombres_2= models.CharField(max_length=100,blank=True) Telefono_Familiar_2 … -
lower() was called on None
I have created a custom function to create custom username in a class Inheriting DefaultSocialAccountAdapter. The code is as follows. def _build_username(self,data): from allauth.utils import generate_unique_username if(not data.get('username')): first_name=data.get('first_name','').lower() last_name=data.get('last_name','').lower() suggested_username = (f"{first_name}{last_name}",) username = generate_unique_username(suggested_username) return username But it throws lower() was called on None I was trying to convert the name to lowercase because that is how our database supports usernames. This happens when i try to perform google login authentication method. -
django MultiValueDictKeyError when trying to retrieve "type"
I have a django page that exports the contents of a list to a csv. The filename is set up to include the organization name, but I want it to also include the type of file as well. As far as I can tell, the values are being pulled from here: <div class="p-1 col-12 fw-bold mb-2"> <label class="text-r mb-1">Select File Type:</label> <select name="type" class="form-select" aria-label="Default select example"> <option value="accounts">Accounts</option> <option value="contacts">Contacts</option> <option value="membership">Membership</option> <option value="cg">Community Group</option> <option value="cgm">Community Group Member</option> <option value="so">Sales Order</option> <option value="item">Item</option> <option value="event">Event</option> <option value="tt">Ticket Type</option> <option value="si">Schedule Item</option> <option value="attendee">Attendee</option> </select> </div> <div class="p-1 col-12 fw-bold mb-2"> <label class="text-r mb-1">Organization Name:</label> <input class="form-control" placeholder="Organization Name" type="text" name="name" required /> </div> The python function that calls it is as follows: class CsvView(View): def post(self, request, *args, **kwargs): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() data = request.POST["raees"] name = request.POST["name"] d_type = request.POST["type"] data = list(data.split(",")) last = data[-1] first = data[0] data[0] = first.replace("[", "") data[-1] = last.replace("]", "") row = 0 col = 0 for i in data: i = i.replace("'", "") worksheet.write(row, col, i) row = row + 1 workbook.close() output.seek(0) filename = f"{name} {d_type} Issue Tracker.xlsx" response = HttpResponse( output, … -
Django querry set sql
please i want to whrite this sql code in a django code to extract data inside SELECT * FROM tblInsuree FULL JOIN tblServices ON tblInsuree.AuditUserID = tblServices.AuditUserID -
linux shell script won't change to directories/sub directories as expected
I trying to build a shell script to setup a Django directory structure. I know the PC/DOS batch language fairly well and I'm trying to accomplish a directory structure setup. I'd like help having my sh script change/create directories and to run commands.. However... I'm getting an error far below when I run the script immediately below... $ sh setup3.sh proj222 app222 mkdir $1 cd $1 python3 -m venv venv$1 source venv$1/bin/activate pip install django && pip install django-oso && pip install django-debug-toolbar && sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib && pip install Django psycopg2 && python3 -m pip install Pillow django-admin startproject config . mkdir apps mkdir templates mkdir tests mkdir utils cd apps ls django-admin startapp $2 ls cd $2 touch urls.py ls # cd .. python3 manage.py migrate python3 manage.py runserver No such file or directory thalacker@HPLaptop17Linux:~/codeplatoon/djangoProjects$ sh setup3.sh proj222 app222 setup3.sh: 28: source: not found Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django in /home/thalacker/.local/lib/python3.10/site-packages (4.1.1) Requirement already satisfied: asgiref<4,>=3.5.2 in /home/thalacker/.local/lib/python3.10/site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /home/thalacker/.local/lib/python3.10/site-packages (from django) (0.4.2) Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django-oso … -
Django rest framework ModelViewSet displying cuttom HTML instead of default
I am new to Django & DRF and I am trying to replace the default api view given from ModelViewSet (scr1,scr2,scr3) with custom HTML templates. Default view works just fine, i've tested with postman and it can do CRUD functions(at least it seems so), but I have no idea how to substitute the default views with custom html pages. I did follow DRF docs - it worked, also searcged solutions(this one was promising), but I simply can't adopt it my situation. Please help! models.py: from django.db import models class Package(models.Model): prod_name = models.CharField(max_length=255, default=0) quantity = models.IntegerField(default=0) unit_price = models.IntegerField(default=0) def __str__(self): return self.prod_name class Orders(models.Model): order_id = models.CharField(max_length=255, default=0) package = models.ManyToManyField(Package) is_cod = models.BooleanField(default=False) def __str__(self): return self.order_id serializers.py: from rest_framework import serializers from .models import Package, Orders class PackageSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField() prod_name = serializers.CharField(max_length=255, default=0) quantity = serializers.IntegerField(default=0) unit_price = serializers.IntegerField(default=0) class Meta: model = Package fields = "__all__" class OrderSerializer(serializers.HyperlinkedModelSerializer): package = PackageSerializer(many=True) def get_or_create_packages(self, packages): print("this is package in gocp:", packages) package_ids = [] i = 0 for package in packages: print("i=", i) i += 1 package_instance, created = Package.objects.get_or_create(pk=package.get('id'), defaults=package) print("package id:", package.get('id')) package_ids.append(package_instance.pk) print("package_ids:", package_ids) return package_ids def create_or_update_packages(self, packages): package_ids = … -
Django - How to style search filter?
I am having issues styling the search filter. I tried using widget and i was only able to adjust the size of the search filter. My search filter still looks very generic and as a beginner, i have trouble understanding how to style it. I know how to style it using css which is shown in the code below This is my filter code: class Product (django_filters.FilterSet): search = CharFilter( field_name="search", lookup_expr="icontains", widget=forms.TextInput(attrs={ 'size': 100, }) ) css for search bar: .search{ float: right; padding: 6px; border: none; margin-top: 8px; margin-right: 16px; font-size: 17px; } -
How to validate the json format of request in django middleware?
I am creating a new middleware in django. In that I am checking the input in request_body. For that I need to check if the request body is json or not. But while raising exception like malformed request or bad request data I am getting 500 server error. How to handle this? def validate_json(request): try: req_data = json.loads(request) except: raise api_exception.BadRequest() json_body = validate_json(request) You can refer to above psuedo code. I want bad rrequest data 400 as response but getting 500 server error. -
How can I post HTML element value to MySQL Database in Django using Ajax (Without using Form)
I am new to Django and currently facing a problem to post html tag data into database. tables.html <div class="containers pt-5 pb-3 px-4 py-4"> <input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' /> <div class="d-none"> <p>User ID: </p><p class="user-id">{{id}}</p> </div> <h3>Case Number:</h3><h2 id="number"></h2> <h4>Description:</h4> <p class="mb-5" id="display"></p> <div class="button d-inline-block" style="max-width: 50%;"> <button type="submit" id="pick" class=" pick-button btn btn-outline-primary border-radius-lg p-3">Pick Case</button> </div> <div class="d-inline-block float-lg-end" style="max-width: 50%;"> <button class="btn btn-outline-danger border-radius-lg p-3">Close</button> </div> </div> <script> $("#pick").click(function(){ var user = $('.user-id').text(); var ca = $('#number').text(); ca = $.trim(ca); $.ajax({ type:"POST", url:"{% url 'dashboard:pick_case' %}", data:{ user_id:user, case_id:ca, csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function(data){ alert(data); } }); }); </script> Views.py def pick_view(request): if request.method == 'POST': case_id = request.POST.get('case_id') print(case_id) status = 2 picked = Transaction() picked.Case_ID = case_id picked.Status = status picked.save() return HttpResponse("Case Picked Successfuly!") else: return HttpResponse("POST ERROR") urls.py urlpatterns = [ path('dashboard', views.dashboard_view, name='dashboard_view'), path('tables', views.case_view, name='case_view'), path('tables', views.pick_view, name='pick_case'), ] models.py class Transaction(models.Model): ### Case Progress Table Case_ID = models.ForeignKey(CaseTable, on_delete=models.CASCADE) Status = models.ForeignKey(Status, on_delete=models.CASCADE) Date_Time = models.DateTimeField(default=timezone.now) I tried the above code and i am able to retrieve the data from the HTML tags but not able to store in the Database. Please Help!! -
change attrs in a CheckboxSelectMultiple widget on every item with django form
I need to build a pre-filled field in a form that have CheckboxSelectMultiple widget. I thought to use different attrs={"checked":""} value on each id of the form filed. Is possible to loop on items? from django import forms from myapp.models import MyModel class MyForm(forms.Form): qs = MyModel.object.value_list("id","value") qsa = MyModel.object.value_list("id", "is_checked") myfield = forms.ModelMultipleChoiceField(queryset=qs, widget=form.CheckboxSelectMultiple) extrafield = forms.CherField(widget=forms.Textarea) def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) for id, is_checked in self.qsa: if is_checked is true: self.fields["myfield"].widget.attrs["checked"] = "" <form action="some_action"> <input type="checkbox" id="1" name="1" value="value_1"> <label for="value_1"> value_1</label><br> <input type="checkbox" id="2" name="2" value="value_2"> <label for="value_2"> value_2</label><br> <input type="checkbox" id="3" name="3" value="value_3"> <label for="value_3" checked="checked"> value_3</label><br><br> <input type="submit" value="Submit" > </form> -
How to stop the celery when the function finishes its task?
I created a countdown and I put this countdown in a context_processor file, the mission is that when someone creates an order this order has a time and every category has a different time to make that order so when if I created more than one category the time will be different in the countdown. the code worked for me but there's a problem which is sometimes the countdown works and when the time gets to "00:00:00" the countdown breaks (that is the target) and other sometimes when the countdown works and when the time gets to "00:00:00", the time repeat itself once again (which results in unexpected behavior). I'm trying to stop the celery worker by that condition but it didn't work for me: if _order_time == "00:00:00": # _order.update(in_progress=False) TODO self.expires = 0 in fact, I tracked what happens over there then I got the issue, so when the countdown works I shouldn't do any kind of request to get the expected time but if there are any requests happened even if it can be "back" or "forward" the unexpected behavior for countdown starts to appear. Note: when I start the celery worker I do the following command: … -
Get prevoius day total daily km in models property method
Hello Developers i am stuck in a problem , i want to get sum of daily km on models @property. so i can easily render data in templates. class Log(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) date_time = models.DateTimeField(default=timezone.now, blank=True, null=True) @property def daily_km(self): return Logsheet.objects.filter(log=self).aggregate(Sum('total_km'))['total_km__sum'] and related_name models is below class Logsheet(models.Model): log = models.ForeignKey(Log, on_delete=models.CASCADE, related_name="logsheets") driver = models.ForeignKey(Driver, on_delete=models.CASCADE, blank=True, null=True) trip = models.IntegerField(blank=False, null=False) distance_from = models.FloatField(blank=True, null=True, ) distance_to = models.FloatField(blank=True, null=True, ) time_from = models.TimeField(blank=False, null=False, default=timezone.now) time_to = models.TimeField(blank=False, null=False, default=timezone.now) source = models.CharField(max_length=100, blank=True, null=True) destination = models.CharField(max_length=100, blank=True, null=True) total_km = models.FloatField(blank=True, null=True,) and while i am successfully get sum of daily km on that day,i case of previous day sum of daily km is not calcutaed by me help me out. Thank You! -
the user created in the admin panel cannot log in to the admin panel
I have a custom user model: class CustomUser(AbstractUser): ACCESS_LEVELS = ( ('user', 'Авторизованный пользователь'), ('admin', 'Администратор') ) email = models.EmailField( max_length=254, unique=True, verbose_name='Эл. почта' ) access_level = models.CharField( max_length=150, choices=ACCESS_LEVELS, blank=True, default='user', verbose_name='Уровень доступа', ) @property def is_admin(self): return self.is_superuser or self.access_level == 'admin' class Meta: verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def __str__(self): return ( f'email: {self.email}, ' f'access_level: {self.access_level}' ) Registered in the admin panel: @admin.register(CustomUser) class UserAdmin(admin.ModelAdmin): list_display = ('username', 'email', 'access_level') search_fields = ('email', 'access_level') list_filter = ('email',) def save_model(self, request, obj, form, change): if obj.is_admin: obj.is_staff = True obj.save() When I create a superuser or a user with staff status and try to log in, a message appears: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. So I Googled the issue and tried everything I could. Here are all the problems I investigated: Database not synced: I synced it and nothing changed. No django_session table: I checked; it's there. Problematic settings: I just added the created apps to INSTALLED_APPS. User not configured correctly: is_staff, is_superuser, and is_active are all True. Old sessions: I checked the django_session table and it's empty. Missing or wrong URL pattern: … -
How to aggregate filtered listapiview queryset and return value once
How to perform aggregations on filtered querysets and return the value only once? My existing code below. In the serializer, of course PZ.objects.all() makes it aggregate all items. I don't know how to get the queryset from the serializer level. To make the total value appear once, it would be a good idea to add a field in the view. However, overriding def list(): makes the filtering stop working. I need this because I am working on a table that shows documents with filtering capabilities. In addition, there will be pagination. After selecting, for example, a creation date range, the values of the documents must be summed. View: class PZListAPIView(ListAPIView): queryset = PZ.objects.all() serializer_class = PZModelSerializer filterset_fields = { 'id': ['exact', 'in', 'contains', 'range'] } Serializer: class PZModelSerializer(serializers.ModelSerializer): net_value_sum = serializers.SerializerMethodField('get_net_value_sum') class Meta: model = PZ fields = '__all__' def get_net_value_sum(self, obj): return PZ.objects.aggregate(Sum('net_value'))['net_value__sum'] Response: [ { "id": 41, "net_value_sum": 28.0, "status": "C", "net_value": "6.00" }, { "id": 42, "net_value_sum": 28.0, "status": "S", "net_value": "10.00" } ] Desired response: [ "net_value_sum": 28.0, { "id": 41, "status": "C", "net_value": "6.00" }, { "id": 42, "status": "S", "net_value": "10.00" } ] -
How to format DurationField input as min:sec:millisec Django
I want to force users to input lap times into a Form using the format min:sec:millisec (e.g. 00:00:000). I also want to display these times in this format in a DetailView but I want to store them as milliseconds to calculate personal bests and lap differences. I have tried to set the default DurationField value as 01:01:001 but it displays in the format HH:MM:SS.MS Here is my model: class SwimTime(models.Model): swimmer =models.ForeignKey(Swimmer, on_delete=models.CASCADE) time = models.DurationField(_('Time'), default= timedelta(minutes=1, seconds=1, milliseconds=1)) distance = models.PositiveIntegerField(_('Distance'),null = False, default=50) strokeType = models.CharField(_('Stroke Type'),max_length=20, choices=strokeTypes, default='FC') date = models.DateField(_('Date Recorded'),default = timezone.now) def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) -
Adding custom godaddy domain to railway web app
I deployed my web app on Railway. They gave the following settings: I went to GoDaddy where I bought a custom domain - and it was impossible to enter @ as Name. I called support - their representative entered the following settings himself. But it still doesn't work, 72 hours have passed. How should I resolve this? -
Django Form : cleaned_data.get(field name) is returning None in clean() method
I am following the Django documentation of Django form but unable to understand what is the issue in my code. I am writing the below code in the clean method to check if both name and email starts with lowercase s or not but Django is returning None in cleaned_data.get(field name) method and I am getting "Attribute error" : 'NoneType' object has no attribute 'startswith'. Please help me on this: Reference: https://docs.djangoproject.com/en/4.1/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other from django import forms from django.core.exceptions import ValidationError class GirlsFeedback(forms.Form): name = forms.CharField(label = 'Enter Your Name', label_suffix = " ", required=True, disabled=False, min_length = 5, max_length = 100, strip=True) password = forms.CharField(label='Enter Your Password', label_suffix = " ", required=True, disabled=False, min_length=8, max_length=10, help_text="Minimum 8 and Maximum 10 characters are allowed.", widget=forms.PasswordInput) email = forms.EmailField(error_messages={'required': 'Email is mandatory'}) def clean(self): cleaned_data = super().clean() name = cleaned_data.get('name') email = cleaned_data.get('email') if name.startswith('s') and email.startswith('s') !=True: raise ValidationError('Name and email both should start with a lowercase s') Error: AttributeError at /feedback3/ 'NoneType' object has no attribute 'startswith' Request Method: POST Request URL: http://localhost:8000/feedback3/ Django Version: 4.1.2 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'startswith' Exception Location: C:\Users\singh\Desktop\Journey\Django Journey\Geeky Shows\Eleven\Feedback3\forms.py, line 72, in clean Raised during: Feedback3.views.feedback Python … -
Django TestCase using self.client.post() is sending a GET resquest
I'm creating a integration Test Class. The self.client.get is working fine, but self.client.post is sending GET and I'm receiving a [httpResponse("Method Not Allowed", 405)]. from django.test import TestCase import json class Test_Integration(TestCase): def test_create_exist_product(self): response = self.client.post('http://127.0.0.1:8201/v1/products/create', {"name": "product7", "latest_version": "0"}, follow=True, secure=False) print(response) self.assertEqual(response, "Product name already exists") Function def create_product(request): logger.info("Entering function create_product..") logger.info("REQUEST TYPE: "+str(request.method)) if request.method == "POST": CODE HERE return HttpResponse("Method Not Allowed", 405) Log errors: Found 4 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). INFO 2022-11-16 13:45:12,066 views 13612 19052 Entering function create_product.. INFO 2022-11-16 13:45:12,068 views 13612 19052 REQUEST TYPE: GET <HttpResponse status_code=200, "405"> ====================================================================== FAIL: test_create_exist_product (project.Tests.test_integration.Test_Integration) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\backend\project\Tests\test_integration.py", line 23, in test_create_exist_product self.assertEqual(response, "Product name already exists") AssertionError: <HttpResponse status_code=200, "405"> != 'Product name already exists' ---------------------------------------------------------------------- Ran 4 tests in 6.523s FAILED (failures=1) Destroying test database for alias 'default'... -
How can I display total likes received to an user to his post on django
I want to display total likes received to an user to his posts on django and display it by monthly basis def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["views"] = posts.objects.filter(likes=self.request.user) return context -
Create a new record using another for default values
What would be the best way to implement a feature whereby a user selects an existing record as a template for the creation of a new one? Ideally I'd like a list of all existing records in a ListView and the user clicks on one of these records and is taken to a CreateView whereby the fields are populated with the selected record's values as new default, starting values. Would this method essentially be a standard ListView-to-UpdateView however the save method would instead create a new record instead of updating? -
How to get the data from a post request using Django Python Templates
I have two projects, the first one is Node.JS. jsonobj = JSON.stringify(generateMockData) xhrToSoftware.send(jsonobj); xhrToAPI.open("POST", "http://127.0.0.1:8000/path/", true); xhrToAPI.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhrToAPI.send(jsonobj); It's sending data to the second project Django Python. I can receive the data using my views.py. post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) But I want to directly get the data from Node.JS to my Django Templates (javascript or jquery) is that possible? for example: <script> //get the data that posted by the node.js </script> I tried using this one: fetch('http://127.0.0.1:8000/path/') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => console.error(error)); but I'm having an error it says that: SyntaxError: Unexpected token '<', "<!-- <d"... is not valid JSON I think that's because I'm returning an html file in my views.py: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return render(request, 'waterplant/iot/data.html') so, I change it to jsonresponse like this: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return JsonResponse({"msg": value}, status=200) After that I'm having an error ValueError: The view views.data didn't return an HttpResponse object. It returned None instead. I think that's because the value is empty yet. How can I prevent that? … -
one upload function for pdf and a second upload function for excel
I have a template with two upload functionaliteis: one for pdf and one for excel. And I have two texareas for showing the data from the uploaded file: one textarea for data from the pdf and one texarea for the data from excel But my problem now is, how to combine this two in the views.py? So this is how the template looks: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-warning">Upload!</button> </div> </form> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" cols="70" rows="25"> {{content}}</textarea > </div> </div> </div> </form> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-warning">Upload!</button> </div> </form> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" cols="65" rows="25"> {{content_excel}}</textarea > </div> </div> </div> </form> </div> </body> </html> {% endblock content … -
How to overwrite a default value in Views
I have several views which use the same model and template due to the need for unique urls. Each view needs to set its own unique default values for several of the model's fields. For example in View 1, the models' field titled 'name' should have a default value of 'Name for a View 1 item', likewise 'Name for a View 2 item' under View 2 etc. How would I specify / overwrite a default value for a field in a view? -
SQL User History Table, Get last updated SPECIFIC FIELD
I have such a user_history table. Every time my users table is updated, records are dropped here as well. How can I get the date when my user updated his last salary information, that is, 2.01.2022 with SQL? I need to get the date it went from 200 to 300 (money field),so "2.01.2022" I need to do this with DJANGO ORM but I couldn't even do more normal SQL query. I tried to use sql lag,lead methods, but I could not succeed. -
My AWS pipeline keeps on failing, but not sure why one of the instances fails there?
My set up is : - Elastic Beanstalk Env - GitHub - S3 Bucket (for storage of static-files) The source stage is fine but thank it fails. ERROR: Latest action execution message Deployment completed, but with errors: During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version. Failed to deploy application. Unsuccessful command execution on instance id(s) 'i-08ec1ec805e434ba5'. Aborting the operation. [Instance: i-08ec1ec805e434ba5] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. Instance deployment failed. For details, see 'eb-engine.log'.