Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a dynamic django model field that can change its type to charfield, datetimefield, manytomanyfiel...etc?
I am trying to create a change tracker, so when I change any model I register the data of the change for statistical perpese. However, I have this field called field_value I set it to char field and I faced a problem later. Because it is a plane text it is hard to tell what are the data represent. For example, when I have the field_value equal to a manytomanyfield with users ids I got a plan text that look like this "<Ojbect User(1) User(2)>" or like this "[1,2]" which is not pleasant to work with or to make statistics one them. class ChangeTrack(SafeDeleteModel): changed_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='user', on_delete=models.DO_NOTHING, null=True,) date_created = models.DateTimeField(auto_now_add=True, null=True) model_target = models.CharField(max_length=50, blank=True) field_target = models.CharField(max_length=50, blank=True) field_value = models.CharField(max_length=50, blank=True) @receiver(signals.post_save) def __init__(instance, sender, signal, *args, **kwargs): new_change = ChangeTrack.create(...) #.... my code # the problem is here I stringfy all sorft of data evnen if they are manytomany field # so how can I make a dynamic fidl that can be char field if I need , or manytomahy fiedl when I need an dsoo one? new_change.field_value.set(str('any value')) -
Mocking query_params using responses and pytest
I would like some help to mock a query_param using responses and pytest. I have this view: @api_view(["GET"]) @csrf_exempt @permission_classes((AllowAny,)) def get_code_and_extra(request): code = request.GET.get("code", "") extra = request.GET.get("extra", "") if code and extra: # do something return HttpResponse("", status=200) return HttpResponse("", status=400) And my test mocked: @responses.activate def test_receive(self, db, client): responses.add( responses.GET, "https://test.com/?code=some-code&extra=extra", json={}, status=200, content_type="application/json", ) resp = client.get(reverse("my-url")) assert resp.status_code == 200 When I run my test works, but the view does not receive the query_params. I would like to pass it so that the test works as expected. A little more context: this view serves as a webhook that receives these parameters from another site. The view is working, but I wanted to have this test. -
Python dynamic attributes and subclasses
I am using Django 3.2 and Python 3.8 I want to move common methods to a base class. class Base: def common1(self): rname = self.get_relation_name() return rname.filter(some_criteria) @abstractmethod def get_relation_name(self): pass @abstractmethod def get_relation_count_name(self): pass class Child1(models.Model, Base): foos = GenericRelation(Foo) foos_count = models.PositiveIntegerField(blank=False, null=False, default=0, db_index=True) def get_relation_name(self): return self.foos def get_relation_count_name(self): return self.foos_count class Meta: abstract = True class Child2(models.Model, Base): foobars = GenericRelation(FooBar) foobars_count = models.PositiveIntegerField(blank=False, null=False, default=0, db_index=True) def get_relation_name(self): return self.foobars def get_relation_count_name(self): return self.foobars_count class Meta: abstract = True When I run python manage.py check I get no errors - but I am not sure if there are any gotchas that will come to bite me later on in the project. My question is - is it safe to dynamically create attributes like this - and/or is there something I need to be aware of? -
DJango doesn't execute request.method == "post" with ajax data submission
It's time first time working with JQuery and Ajax, I've been stuck on this problem for past few hours, searched through various similar solutions but nothing worked for me Problem: Whenever I click on "submit" button Ajax delivers data to DJango view but that if "post" request part refuses to execute but else part executes no matter how many times i change the code HTML <form id="login-form" class="LoginForm" action="" method="post"> {% csrf_token %} <h3 class="text-center text-info">Login</h3> <div class="error"> </div> <div class="box"> <div class="form-group"> <label for="username" class="text-info">Username:</label><br> <input type="text" name="username" id="username" class="form-control"> </div> <div class="form-group"> <label for="password" class="text-info">Password:</label><br> <input type="text" name="password" id="password" class="form-control"> </div> <div class="form-group"> <label for="remember-me" class="text-info"><span>Remember me</span> <span><input id="remember-me" name="remember-me" type="checkbox"></span></label><br> <input type="submit" name="LoginButton" id="LoginButton" class="btn btn-info btn-md" value="submit"> </div> </div> <div id="register-link" class="text-right"> <a href="#" class="text-info">Register here</a> </div> </form> script <script> $(document).ready(function () { $('#LoginButton').click(function () { var username = $('#username').val(); var password = $('#password').val(); if ($.trim(username).length > 0 && $.trim(password).length > 0) { alert("Username and password were trimmed"); console.log("Username = " + username + "\n Password = " + password); $.ajax({ url: '{% url "loginCheck" %}', method: "post", data: { username: username, password: password, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, cache: false, beforeSend: function () { $('#LoginButton').val('Checking...'); … -
Django FloatField not properly display: 54 instead of 5.4 (data store in Postgresql)
I've been looking for error for hours but could not find where is the problem I have a 2 models (Sociodemographique and Clinique) each with a FloatField (dem_hglvaql and cli_tem respectively) I have apply data-mask on each field that correctly works for data entry model.py dem_hgl_val = models.FloatField("Si non, hémoglobine glyquée (%)", null=True, blank=True) cli_tem = models.FloatField('Température', null=True, blank=True) forms.py self.fields['dem_hgl_val'] = forms.FloatField(label = 'Hémoglobine glyquée (%)',widget=forms.TextInput(attrs={'placeholder': '_ _._ _','data-mask':"00.00"}),required=False) self.fields['cli_tem'] = forms.FloatField(label = 'Température',widget=forms.TextInput(attrs={'placeholder': '_ _ . _','data-mask':"00.0"}),required=False) But when I display the Sociodemographique form, dem_hgl_val is not correctly displayed: 54 instead of 5.4 cli_tem field is correctly displayed dem_hgl_val have validation form control and JS conditional behavior but even if I remove all these controls it doesn't seems to change anything forms.py def clean_dem_hgl_val(self): data = self.cleaned_data['dem_hgl_val'] if data: if data > 100: raise forms.ValidationError("Vous ne pouvez pas saisir un pourcentage supérieur à 100%") if data < 0: raise forms.ValidationError("Vous ne pouvez pas saisir un pourcentage négatif") return data JS script // masque la section 3 'Co-morbidités' si la case 'section non applicable' est cochée $("#id_dem_com_nap").on('change', function() { if ($(this).is(':checked')) { $("#id_dem_hgl_val").val(null); }); // affichage conditionné section 'Diabete' $("#id_dem_dia").on('change', function() { if ($(this).val() == 1) { $("#id_dem_hgl_val").val(null); } … -
Getting Error in Django: DoesNotExist at /add-to-cart-2247/
I'm using Django as a backend and PostgresSQL as a DB and HTML CSS & Javascript as a frontend. While I'm adding the product to the cart it show this error. This is the Error where I get in screen while adding to the cart: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 159, in get context = self.get_context_data(**kwargs) File "D:\Visual studio Projects\Django Project\mainproject\buildpc\views.py", line 35, in get_context_data cart_obj = Cart.objects.get(id = cart_id) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /add-to-cart-2247/ Exception Value: Cart matching query does not exist. Traceback Here is my Code: view.py class AddToCartView(TemplateView): template_name = "status.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) processor_id = self.kwargs['pro_id'] processor_obj = Processor.objects.get(id = processor_id) cart_id = self.request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id = cart_id) this_product_in_cart = cart_obj.cartproduct_set.filter(processor = processor_obj) if this_product_in_cart.exists(): cartproduct = this_product_in_cart.last() cartproduct.quantity += 1 cartproduct.subtotal += processor_obj.price cartproduct.save() cart_obj.total += processor_obj.price … -
Saleor storefront invalid credential when resetting password
Saleor is giving me an error when resetting my password in the store it says invalid credential when I’m resetting and invalid token after does anybody encounter this? Thanks -
Delete password, Last login, Superuser status, Groups, User permissions...filed in User tab in Django admin
I have used Django2 and simpleUI to develop a Django web app. Now I want to delete password, Last login, Superuser status, Groups, User permissions...filed in User tab in Django admin. How could I do that? I tried to unregister my user and rewrite it, but failed to delete anything. admin.py: from django.contrib import admin from django.contrib.auth import forms from .models import * from django.contrib.auth.models import Permission admin.site.register(User) -
How do I get the POST result from a url endpoint? Django/Python
I have a system that sends a pin entry request to a client for payment processing. If client accepts payment and enters PIN, I get below results on my endpoint I have tried to run the code below response = requests.get('https://end9m3so3m5u9.x.pipedream.net/') print(response.text) print(response.status_code) How do I access the ResultCode for further processing in my views.py? Please advice. -
How do I use update_or_create In django?
I have problem on using update_or_create method in django I have following model class Search(BaseModel): booking_id = models.IntegerField(db_index=True, unique=True) trip_type = models.CharField(max_length=20, choices=trip_choice) flight_date = models.DateField() return_date = models.DateField(null=True, blank=True) And I tried creating if not exists or update existing value but I am getting integrity error duplicate key value violates unique constraint "flight_search_booking_id_key" DETAIL: Key (booking_id)=(4) already exists. Here is how I tried saving. def _save_to_db(self): # 14. check if booking id exists previously if exists raise error defaults = {'booking_id': 4} flight_data, _created = Search.objects.update_or_create( booking_id=self._flight_data.get('booking_id'), trip_type=self._query_params.get('flight_type'), flight_date=self._query_params.get('departure_date'), defaults=defaults ) flight_data.save() I learned default should be provided so I did that too but I am getting error. -
django post last_login time of user
I want when user login the last_login case get updated . this is my login view : def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'accounts/login.html', context) and this is my user table : any advices ? -
Django-FIle download issues
In my application, many users can upload files. There is no fixed file type as the user can upload any kind of file. I am trying to create a view through which the file could be downloaded. It goes like this def download_file(request,id): file = t_data.objects.get(id=id) fl_path = "media/file_name.extension" filename = file.file_name fl = open(fl_path, 'r') mime_type, _ = mimetypes.guess_type(fl_path) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response I am able to download .txt files but files with other extensions aren't downloading. Instead, I get this error when i try to download .py file UnicodeDecodeError at /download/9 'charmap' codec can't decode byte 0x9d in position 375: character maps to Request Method: GET Request URL: http://127.0.0.1:8000/download/9 Django Version: 3.1.7 Exception Type: UnicodeDecodeError Exception Value: 'charmap' codec can't decode byte 0x9d in position 375: character maps to Exception Location: C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py, line 23, in decode Python Executable: C:\Users\ukfle\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Python Path: ['C:\Users\ukfle\Documents\pro', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39', 'C:\Users\ukfle\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\paypal_checkout_serversdk-1.0.0-py3.9.egg', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\win32', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\win32\lib', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\Pythonwin'] Server time: Thu, 27 May 2021 11:41:34 +0000 I am quite beginner and don't know whats the problem. Please help me solve it. Thank you. If there is another approach for downloading files of all … -
How to add server-side apis to Django admin website?
I'm creating a Django app that can be installed on any Django website as a reusable PyPi package, Lets name it locations app. It has its own models.py, admin.py and let's assume that the custom models of this app have the following tables: class Country(models.Model): name = models.CharField(max_length=200) class City(models.Model): name = models.CharField(max_length=200) country = models.ForeignKey(Country, on_delete=models.CASCADE) class Location(models.Model): name = models.CharField(max_length=200) country = models.ForeignKey(Country, on_delete=models.CASCADE) city = models.ForeignKey(City, on_delete=models.CASCADE) And all these models are added to the admin website so users can access them from there. What I need to do is to add an API that lists all Cities for a specific Country so that this API is used in the background every time the user selects a country when adding or editing a location so that it then shows a list of all cities in the currently selected country. My problem is that if I define this API as a view in locations/views.py located somewhere by locations/urls.py. The URI of the API will be subject to the main urls.py of the website not only the locations/urls.py* and the URI of the admin website as well might vary depending on the main urls.py. So how can I make … -
How can i use get_queryset()object 'list_object' in other fuction
`class AboutView(ListView): template_name = 'index.html' model = Product def get_queryset(self): object_list = self.model.objects.all() return object_list def get(request, self): new_list = object_list return new_list.order_to(-'price')` -
I put <form> tag in my template into a for loop to show 5-star-rating for each image and user can rate but its only saving response of 1st element
i try to make a website with different images and user can give 5=-star-rating to them so i save the images from admin side and place a card into loop to show all the present data from database and with that i also place 5-star- rate to give rating but it saving the data of 1st image only in the card i want it to save rating of each image, i search it everywhere but cant find any solution please help me with this. This is my HTML page <div class="container"> <div class="row"> {%for a in ab%} <div class="col-4"> <div class="card"> <img class="card-img-top" src="{{a.image.url}}"> <div class="card-body"> <h5 class="card-title">{{a.product}}</h5> <div class="col text-center"> <form class="rate-form" action="" method="POST" id="{{a.id}}"> {% csrf_token %} <button type="submit" class="fa fa-star fa-3x my-btn" id="first"></button> <button type="submit" class="fa fa-star fa-3x my-btn" id="second"></button> <button type="submit" class="fa fa-star fa-3x my-btn" id="third"></button> <button type="submit" class="fa fa-star fa-3x my-btn" id="fourth"></button> <button type="submit" class="fa fa-star fa-3x my-btn" id="fifth"></button> </form> <br> <div id="confirm-box"></div> </div> </div> </div> {%endfor%} </div> </div> This is my java-script // console.log('hello world') // get all the stars const one = document.getElementById('first') const two = document.getElementById('second') const three = document.getElementById('third') const four = document.getElementById('fourth') const five = document.getElementById('fifth') // get the form, … -
unable to import pycryptodome in django
I have created a django-project called dp1 and inside that I have made a djano-app called da1. I am working on Windows inside a virtual env named testing. da1\views.py from django.shortcuts import render # Create your views here. from django.http.response import HttpResponse from django.shortcuts import render import hashlib from Crypto import Random from Crypto.Cipher import AES from base64 import b64encode, b64decode import os class AESCipher(object): def __init__(self, key): self.block_size = AES.block_size self.key = hashlib.sha256(key.encode()).digest() def encrypt(self, plain_text): plain_text = self.__pad(plain_text) iv = Random.new().read(self.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) encrypted_text = cipher.encrypt(plain_text.encode()) return b64encode(iv + encrypted_text).decode("utf-8") def decrypt(self, encrypted_text): encrypted_text = b64decode(encrypted_text) iv = encrypted_text[:self.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) plain_text = cipher.decrypt(encrypted_text[self.block_size:]).decode("utf-8") return self.__unpad(plain_text) def __pad(self, plain_text): number_of_bytes_to_pad = self.block_size - len(plain_text) % self.block_size ascii_string = chr(number_of_bytes_to_pad) padding_str = number_of_bytes_to_pad * ascii_string padded_plain_text = plain_text + padding_str return padded_plain_text @staticmethod def __unpad(plain_text): last_character = plain_text[len(plain_text) - 1:] return plain_text[:-ord(last_character)] # Create your views here. def home(req): return render(req,'home.html',{"name":"Manish"}) def add(req): choice = req.POST['choice'] # value of selected radio button val1 = req.POST['text1'] val2 = req.POST['text2'] result = choice+val1+val2 key_128 = "kuch bhi" iv = "InitializationVe" aesCipher = AESCipher(key_128) print(aesCipher.key) sentence = "manish swami" print(aesCipher.encrypt(sentence)) return render(req, 'result.html' ,{'result': result}) from … -
how can Control/write Temperature value with RS485port, from Django web?
''''Hello, I have PID temperature controller with RS485 communication port. I can read & write the resister values by connecting my 'controller' to serial PORT(com3). I want to Monitor and control the room temperature from Django-Web. please help me with this. I am completely new to Django & python however somehow I managed this much with the help internet. here is my code from where I can read and write the resister values. '''' *import pymodbus import serial from pymodbus.pdu import ModbusRequest from pymodbus.client.sync import ModbusSerialClient as ModbusClient from pymodbus.transaction import ModbusRtuFramer import time,os client= ModbusClient(method = "rtu", port="COM7",stopbits = 1, bytesize = 8, parity = 'N', baudrate=9600) #connect to the serial modbus server connection = client.connect() print(connection) pv=client.read_input_registers(6,3,unit=0x01) print(pv.registers) time.sleep(2) time.sleep(2) #set 1= 184 #controller has 3 different set points which can be seen on device's LCD display. #set 2= 187 #set 3= 189 set=int(input("enter the set => ")) if(set==1): address=184 #communication address for set 1 elif (set==2): address=187 #communication address for set 2 elif (set==3): address=190 #communication address for set 3 else: print("adress not recognised") time.sleep(2) re = client.read_holding_registers(address,3,unit=0x01) print(re.registers) time.sleep(2) value = int(input("Enter the value => ")) result=client.write_registers(address,[value,0,0],unit=0x01) #0xB8= 184 -offset address, 0xB9=185- value, *3= Number of … -
Django models inheriting from ABC: causes TypeError: metaclass conflict
I am using Django 3.2 and I have come across a problem relating to multiple inheritence where one of the parent classes is an ABC: # Interfaces from abc import ABC, abstractmethod class Foo(ABC): @abstractmethod def get_actionable_object(self): raise NotImplementedError('This method must be implemented in concrete subclasses!') class FooBar(models.Model, ActionableModel): items = GenericRelation(Item) # ... class Meta: abstract = True When I run python manage.py check, I get the following error message: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I tried this (from the error message): class FooBar(models.Model, ActionableModel): items = GenericRelation(Item) # ... class Meta(models.Model, ActionableModel: abstract = True But I am getting the same error message. What is causing this error message - and how do I fix it? -
How can I use both safe and truncatechars method?
I trying to solve this problem throughout the day. I want you to use the safe method so no one sees the HTML tags and also want to truncatechars to short the description. I want to do that if anyone wants to read that article must redirect to a detailed page of that article. I've created some dummy posts using faker. When I try to create a post there some HTML tags shown on the home page it's because of Froala Editor so try to use a safe method to remove the tags. So use this way <div class="description"> {{post.description|truncatechars:150|safe}} </div> After using this way my nothing is showing on my post description and also other posts also not showing even the sidebar also gone. After I remove the safe method it's back to normal. You check these images using the safe method and without a safe method.Same thing happens when I use autoescape tag -
Django multiple user types Project Structure
I have a Django project to implement. I have 2 models for different user types : class Applicant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True) telephone = models.CharField(max_length = 10) address = models.CharField(max_length=50) city = models.CharField(max_length=64) country = models.CharField(max_length=50) birthDate=models.DateField() GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) citizenship = models.CharField(max_length=64) def __str__(self): return self.user.username class Evaluator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True) telephone = models.CharField(max_length = 10) committee = models.ForeignKey(Call,on_delete=models.SET_NULL,null=True) def __str__(self): return self.user.username And i have some apps with models: Application Department etc Should i make a new app for each user type :Applicant,Evaluator and make inside them different views and templates for each or should i make views inside the apps for each model and let user types have access by their permissions(I think if I do it that way i will have problems with templates and urls)? Thanks and sorry for my bad English(I am asking for first time) -
How to prevent IntegrityError in a django model
I am learning django and I follow this blog project on codemy youtube channel: https://www.youtube.com/watch?v=_ph8GF84fX4&ab_channel=Codemy.comCodemy.com And I wanted to improve my code with ForeignKey but I got stuck. I want to add a Category into my Post model. So I used the ForeignKey. Not every post has a categroy since I added this model just recently, but I used the default argument in the Category class, which should solve this problem. However, trying several options, I cannot migrate my models and run the server again. My code: from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Category(models.Model): cat_name = models.CharField(max_length=300, default="uncategorized") def get_absolute_url (self): return reverse("blog") def __str__(self): return self.cat_name class Post(models.Model): title = models.CharField(max_length=300) author = models.ForeignKey(User, on_delete = models.CASCADE) body = models.CharField(max_length=30000) date = models.DateField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) def get_absolute_url (self): return reverse("post", args = [str(self.id)]) The error: django.db.utils.IntegrityError: The row in table 'blog_post' with primary key '1' has an invalid foreign key: blog_post.category_id contains a value 'uncategorized' that does not have a corresponding value in blog_category.id. -
Django nginx append slash and redirect issue
I have follwoing server block in my nginx test.conf.Nginx version 1.14.0(Ubuntu) upstream django { server 127.0.0.1:8000; } server{ listen 80; server_name localhost; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location /test { if ($request_uri ~ ^([^.\?]*[^/])$) { return 301 /; } proxy_pass http://django; } } With this I think whenever there is request with prefix /test arrives at server for example /test/debug(no end slash) the if statement inside the location block should redirect to / path. But something weird is happening in my case.When I go to /test/debug without forward slash, I get refirected to /test/debug/ but the strange thing is the server that redirects me is nginx/1.19.0 diff from the one on my host. And after redirect to /test/debug/ by this nginx version the path is handled by version on my main system . This is fine but strange . Also the redirect logs are not visible are not present in my main host access logs. So the main problems here are why is it redirection to diff location and where did this version came from. I have been usnig nginx-1.19.0 inside docker lately but at this moment all the containers are down.I did docker ps no nginx container was running there.I … -
How to compare two partial dates(i.e. todays date with past date) in python?
I am newbie in the programming and stackoverflow as well. I know this point might be discussed earlier but i personally couldn't find the one that can help me out. I am currently working on one of the django projects which has payment interface containing credit card details like credit card number, expiry date, cvv etc.As per client request i have used partial date using django's PartialDateField(Example: February 2025) in expiry date field. What i supposed to do is if any user enter the past date (lets say March 2019 which is not valid for expiry) then i wanted to set javascript alert from django views.py using comparison logic. something like this(just a short demo): Views.py: class billing(View): def get(self, request, *args, **kwargs): pass def post(self,request, *args, **kwargs): if entered_date>current_date: javascript alert submit the form successfully. As a beginner i have no idea how to compare two partial dates so that no one can enter past dates,Any kind of help would be appreciated. Thank you. -
ModelForm Instance vs Initial
I'm super new to Django, so bare with me. I'm trying to write a simple CRUD, using modelforms. In the update view, the form object initialization takes the arguments initial and instance, which confuses me. From django doc: "As with regular forms, it’s possible to specify initial data for forms by specifying an initial parameter when instantiating the form. Initial values provided this way will override both initial values from the form field and values from an attached model instance." Which confuses even more. I know my question isn't specific, but if someone could explain this and honestly, the background connection between the model and modelforms I would really appreciate it. Thanks y'all -
The best way to show some data from db due to 'url' from request in a template (layout)
I need to add some king of a help block to some pages of a website with multiple apps, views etc. I dont want to change all views, i want to get data for current page by its url as an unique id. So in by db it is stored like: ( 'block/page1' -> 'help text for page1', 'block/page2' -> 'help text for page2', etc.). I got a base template with html layout. I want to get the text for current page. How can i do that? Does {% load %} will help me with that? Thanks!