Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate Cognito SSO with Django grapehene
We have an up and running django project that already uses graphene and graphql_jwt (along with django's internal auth). We are attempting to integrate SSO with cognito for this project, but since graphene and graphql_jwt already have their inbuilt auth mechanisms, its becoming hard to make sense of how to integrate Cognito with these. My guess was that I will mostly be needing to only add an authentication backend, that sets the user using the cognito. But this is causing issues with the graphql's existing authentication and it is unable to recognise that the user has already been authenticated. How can the cognito's authentication be added to the existing graphql_jwt flow? -
How do I change the value of true or false to a text value type it I am checking the row in the entire table Note the table is of type datatables?
use django How do I change the value of true or false to a text value type it I am checking the row in the entire table name item type items active item1 15.0 True item2 15.0 False change values row active use jquery or django file view.py: name item type items active item1 15.0 displayed item2 15.0 stope help please -
In Django, how do I construct my queryset to filter by time over slices of time?
I'm using Python 3.9 and Django 3.2. I have this price model class Price(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) price = models.FloatField(null=False) created = models.DateTimeField(null=False, default=datetime.now) If I want to get the price per hour over the last 24 hours, I can run a method like this def _get_prices_per_time_slice(self, last_hours=24): now = timezone.now() end_time = now.replace(second = 0, microsecond = 0) start_time = end_time - timedelta(hours=last_hours) qset = Price.objects.filter( created__range=[start_time, end_time], created__minute=end_time.minute ).values('price') return [r['price'] for r in qset] but let's say I want to get the price every last X hours. def _get_prices_per_time_slice(self, last_hours=24, time_slice_in_hours=4): so if the current time is midnight (and zero seconds and minutes), I would want to get the prices for midnight, 8 pm, 4 pm, noon, 8 am and 4 am. How do I add a filter to screen for prices every X hours? -
Django form/formset button to add field
models.py class Car(models.Model): FUEL = ( ('', '---------'), ('1', 'Gasoline'), ('2', 'Diesel'), ('3', 'Electric'), ('4', 'Hybrid'), ) client = models.ForeignKey(Client,on_delete=models.CASCADE, null=True, blank=True) car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) car_model = models.ForeignKey(CarModel, on_delete=CASCADE) fuel_type = models.CharField(max_length=15, choices=FUEL, default=None) engine = models.CharField(max_length=15) service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, blank=True) extra_info = models.TextField(max_length=300, verbose_name='Info.', null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) forms.py CarFormset = modelformset_factory( models.Car, fields=('service', ), extra=1, widgets={'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Whatever' }) } ) class CarForm(forms.ModelForm): class Meta: model = models.Car fields = '__all__' template {% load crispy_forms_tags %} <form action='' method='post'> {% csrf_token %} {{ form|crispy }} <input type='submit' value='Submit'> {% if formset %} {{formset.management_form}} <div id='service-form-test'></div> <div id='empty-form' class=''>{{formset.empty_form}}</div> <button id='add-more' type='button'>Add</button> {% endif %} </form> <script> const addMoreBtn = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') const currentServiceForms = document.getElementsByClassName('service-form') addMoreBtn.addEventListener('click', add_new_form) function add_new_form(event) { if (event) { event.preventDefault() } const currentFormCount = currentServiceForms.length // + 1 console.log(currentServiceForms.length) const formCopyTarget = document.getElementById('service-form-test') const copyEmptyFormEl = document.getElementById('empty-form').cloneNode(true) copyEmptyFormEl.setAttribute('class', 'service-form') copyEmptyFormEl.setAttribute('id', `form-${currentFormCount}`) const regex = new RegExp('__prefix__', 'g') copyEmptyFormEl.innerHTML = copyEmptyFormEl.innerHTML.replace(regex, currentFormCount) totalNewForms.setAttribute('value', currentFormCount + 1) formCopyTarget.append(copyEmptyFormEl) } </script> Hello, i will add an image of what im trying to do, im a beginner and the only place that i can ask … -
How send confirmation email when user perform register method twice?
In register class I wrote method that raise_exception is true and check email must be unique because I used jwt authentication with email. When user perform this method for one time ,he get email confirmation .if user don't confirm and run register method for second time .he occure error email is registered. Because this email for one time has been registered in data base. How can I handle this issue? -
ModuleNotFoundError: No module named 'django_user_agents'
I am using this library to understand if user is coming from PC or mobile but I am getting this error ModuleNotFoundError: No module named 'django_user_agents'.Anyone know the solution for this problem ? I am using Django 3 +. -
Run javascript in each Django for loop?
I have a Javascript function that converts markdown to html: <script> $(function () { editormd.markdownToHTML("content", { //htmlDecode : "style,script,iframe", // you can filter tags decode emoji : true, taskList : true, tex : true, flowChart : true, sequenceDiagram : true, }); $(".reference-link").each(function (i,obj) { console.log(obj) }) }) </script> But when I run this in a for loop the Javascript only runs on the first post. {% for entry in entry_list %} <div id="content"><textarea>{{ entry.content|truncatechars_html:180 }}</textarea></div> {% endfor %} How do I make it run on each loop? -
stay in the same tab after refreshing page
I have a page which contains same url but a lot of tabs after I click on a tab I can see its content but right after I refresh the page tab(0) appear but I want the last used tab. how can I do that. this is the js code <script> const tabBtn = document.querySelectorAll(".tab"); const tab = document.querySelectorAll(".tabShow"); function tabs(panelIndex){ tab.forEach(function(node){ node.style.display="none"; }); tab[panelIndex].style.display="block"; } tabs(0); $(".tab").click(function(){ $(this).addClass("active").siblings().removeClass("active"); }); </script> -
How to get django form to accept a disabled form with intial values
What I'm trying to do is to allow Django to accept a form that's been disabled using form.disabled. When I try to submit it, however, the initial value that's been calculated on the server seems to disappear into the wind, even though the Django documentation seems to imply that it should be doing otherwise. forms.py class SubmitResponseForm(forms.Form): response_text = forms.CharField(label='Choice text', max_length=50) main_text = forms.CharField(label='Main text', max_length=5000) class SubmitResponseLiteForm(forms.Form): response_text = forms.CharField(label='Choice text', max_length=50) main_text = forms.CharField(label='Main text', max_length=5000, disabled=True) views.py #Some unimportant stuff before this if has_role(request.user, 'subscriber'): form = SubmitResponseForm(initial={ 'response_text': split_strings1, 'main_text': split_strings2, }) else: form = SubmitResponseLiteForm(initial={ 'response_text': split_strings1, 'main_text': split_strings2, }) return render(request, 'nodemanager/detail.html', { 'node': node, 'editchoiceform': form }) def SubmitGeneration(request, pk): node = get_object_or_404(Node, pk=pk) time = timezone.now() if has_role(request.user, 'subscriber') == False: form = SubmitResponseLiteForm(request.POST) else: form = SubmitResponseForm(request.POST) if form.is_valid(): main_text = form.cleaned_data['main_text'] response_text = form.cleaned_data['response_text'] node.children.create(main_text=main_text, response_text=response_text, pub_date=time, creator=request.user) return redirect('nodemanager:detail', pk=node.id) else: return render(request, 'nodemanager/detail.html', { 'node': node, 'editchoiceform': form }) -
Python ModuleNotFoundError on pyphen?
This project is Django web application and it has some custom script running and when web app asks for it. Here's the folder structure, And i'm calling the main method of freq_rank_score.py from webapp->views.py. And getting this error, File "C:\Users\pathum\Documents\alteducation_web\word_processor\freq_rank_score.py", line 5, in <module> import pyphen ModuleNotFoundError: No module named 'pyphen' It worked fine when running it outside django project. I have no idea why ? -
want to use email field as a username field for users, vendors but for django-admin I want to use username field as usual
models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.fields import EmailField class CustomUser(AbstractUser): email = models.EmailField(('email address'), unique=True) mobileno = models.IntegerField(blank=True, null=True) is_customer = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class VendorDetails(models.Model): vendoruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE) aadhar_number = models.CharField(max_length=200) pan_number = models.CharField(max_length=200) store_name = models.CharField(max_length=200) brand_name = models.CharField(max_length=200) admin.py from django.contrib import admin from customer.models import CustomUser, VendorDetails # Register your models here. admin.site.register(CustomUser) admin.site.register(VendorDetails) when attempting ----- python manage.py createsuperuser----(File "D:\Yabesh\Django\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username') need help. Thanks in advance. -
In Django how to get specific user's data stored in profiles module
I am working on a project where I need to get some data into a chart but I don't know how to get the only data belongs to a specific user. I am the Using original user modell that I extended with a Profile modell. I'm storing in the Profile a column called "csoport". I like to write a query where I get some other data from my "Kapcsolodasok" modell that joined to Profile modell. I'm not so experienced in Django ORM so I'm using raw query. HTML (just the query part) {% for k in kapcsolodasok %} { id: "{{ k.user.get_full_name }}", label: "{{ k.user.get_full_name }}", group:{% for cs in csoport %}{{ cs.csoport }}{% endfor %} }, {% endfor %} models.py class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=1) csoport = models.CharField(max_length=100) class Kapcsolodasok(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) kap_bar_01 = models.TextField(max_length=200) kap_bar_02 = models.TextField(max_length=200) ... class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) views.py @login_required def project_details_report(request, projekt_id): csoport = Profile.objects.raw('SELECT stressz_profile.projekt_id, stressz_profile.id, stressz_profile.id FROM stressz_profile INNER JOIN stressz_projekt ON … -
Django 3.2 update AutoField to BigAutoField backward compatibility with foreign key relations
I'm running into a problem after updating my project from Django 2.2 to Django 3.2. In Django 2.2 primary keys are created using AutoField meaning in MySql they are considered int(11) and all foreign keys from this table must also be int(11) In Django 3.2 primary keys are now created with BigAutoField which in MySql creates type bigint(20) therefor I can't create any foreign key relations with old tables. According to the documentation this can be changed in settings using DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'. This works in creating primary keys as int(11) however foreign key fields are still being created as bigint(20) meaning a relation can't be created because they must be of the same type. Here says that you can change all your existing tables to BigAutoField but this also doesn't take care of foreign key relations. Is there any way to change all primary keys and their relations to a different type easily? Am I missing something in the Django documentation where they also provide compatibility to related keys and well as primary keys? I would obviously prefer to change all my current data to work with BigAutoField if all future releases of Django will now use this as … -
Django execute sql raw
I want to print the result by running a mssql query on any page in my postgresql project, how can I do it? for exam. SELECT TOP(11) * FROM dbo.UserObject WITH (NOLOCK) WHERE u_logon_name='cc@gmail.com' My default db setting is postgresql but I want to run mssql query; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'ALIAS': 'XX', 'USER': 'XX', 'PASSWORD': 'XX', 'HOST': 'XX', 'PORT': 'XX', } } -
Where are variables passed into the view in Django?
I'm refactoring code in a Django view. I'm working with a view with the below arguments: def title_views(request, key, group, sort): group = get_object_or_404(Group, group=group, main_id = key) default_sort = sort I know by default each view should have the request argument. But in terms of key, group, sort, where can I expect these items to be passed? Is it through the template that the view is called in? I come here for help because the documentation isn't that clear on this, at least in my experience. Thanks! -
How to display the latest 3 items in django
Is there a way to query django model to display the latest 3 items in a section of my template and display the next 3 on the next part of my template in order? -
how paginate json response data django - jquery
I'm trying to paginate django JsonResponse data , which is an ajax call , here is my views.py def lists(request): lists = CostType.objects.all().order_by('-pk') data = [] for i in lists: item = { 'id':i.id, 'cost_type':i.cost_type, 'admin':i.admin.username, 'user':request.user.username, } data.append(item) return JsonResponse({'data':data}) i want to show 10 posts per page ! and here is my ajax call function listCostTypes(){ $.ajax({ type:'GET', url:'/posts/list_posts', success:function(data){ cost_types = data.data var k = '<tbody>' if(cost_types.length > 0){ for(i = 0;i < cost_types.length; i++){ const id = parseInt(cost_types[i]['id']) k+= '<tr>'; k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple">' + cost_types[i]['id'] + '</td>'; k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple">' + cost_types[i]["admin"] + '</td>'; k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple">' + cost_types[i]["cost_type"] + '</td>'; k+= '</tr>' } } else{ k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=4>no data found</td>' } k+='</tbody>' document.getElementById('types_list').innerHTML = k },});} <table class="table table-bordered table-striped text-center" id="lists" > <thead> <tr> <th>#</th> <th>admin</th> <th>costs</th> </tr> </thead> <tbody id="types_list"> </tbody> </tfoot> </table> please is there away to make a pagination with JsonResponse data ?! or combine backend pagination with data table pagination please ?! Thank you in advance .. -
Running unit test with TestCase on async method causes django.db.utils.InterfaceError: connection already closed
I want to test some async method that I use on an async view, but I want to be very clear that right now I am not testing my view, I already saw the documentation on django but it is only for views.... So I have this class containing multiple method and even contacting database asynchronously. class SessionService: """ Session service. Attributes: uuid (str): system uuid gcloud (str): console gcloud_id start (str): start time of the period end (str): end time of the period """ def __init__(self, uuid: str, gcloud: str, start: str, end: str): self.system_uuid: str = uuid self.gcloud_id: str = gcloud self.start: str = start self.end: str = end @database_sync_to_async def __vision_data(self) -> Tuple[List[str], List[str], List[int]]: """ Async method to get vision module's data from a uuid Returns ---------- QuerySet List where 1st element are gcloud id, 2nd UUID and last system IDs """ return System.objects.get_vision_conf_data(self.system_uuid) @async_property async def __vision_system_ids(self) -> List[int]: """ get visions Ids Returns: List[int] """ data = await self.__vision_data() return data[2] async def get_session_list(self) -> List[Dict[str, Union[str, bool, int]]]: """ Get all session for a period for a system Returns: List[Dict[str, Union[str, bool, int]]] """ spraying_session: SprayingSessionSumUpGetter = SprayingSessionSumUpGetter(self.gcloud_id, self.start, self.end) vision_systems_ids: List[int] = … -
PayPal SDK - AttributeError: 'HttpResponse' object has no attribute 'get'
I am using the PayPal SDK with Django (Django REST Framework) to create and capture transactions. Following this guide I get the error in the title. It looks like self.client.execute(request) returns paypalhttp.http_response.HttpResponse object but Django won't let me return that from my view. Any ideas? Thank you. -
Django ValueError The given username must be set from form self on form overridden save method
I´m in a django simple 3.2.9 project. When i try to override my form save method, y get next error: ValueError The given username must be set from form self It´s quite annoying, cause if I don´t override and call the save functionality from the view, it works just fine, but if I override method, it seems it can´t get self attributes from form, though it can do that on other validation methods within the class. This, my RegisterForm class. class RegisterForm(forms.Form): username=forms.CharField( required=True, min_length=4,max_length=50, widget=TextInput(attrs={ 'class':'form-control' }) ) email=forms.EmailField( required=True, min_length=4,max_length=50, widget=TextInput(attrs={ 'class':'form-control' }) ) pwd=forms.CharField( required=True, min_length=4,max_length=50, widget=PasswordInput(attrs={ 'class':'form-control' }) ) pwdr=forms.CharField( required=True, min_length=4,max_length=50, widget=PasswordInput(attrs={ 'class':'form-control' }) ) def clean_username(self): username=self.cleaned_data.get('username') if User.objects.filter(username=username).exists(): raise forms.ValidationError('Ese nombre de usuario ya se encuentra en uso') return username def clean_email(self): email=self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError('Ese email ya se encuentra en uso') return email def clean(self): cleaned_data=super().clean() if cleaned_data.get('pwd')!= cleaned_data.get('pwdr'): self.add_error('pwdr','Las contraseñas no coinciden') return redirect('register') return redirect('home') def save(self): username=self.cleaned_data.get('username') email=self.cleaned_data.get('email') pwd=self.cleaned_data.get('pwd') return User.objects.create_user( username, email, pwd ) This self contents from print(self) inside save method label for="id_username">Username:<input type="text" name="username" value="vidalon" class="form-control" maxlength="50" minlength="4" required id="id_username"> Email: Pwd: Pwdr: Thanks in advance -
TypeError: 'NoneType' object is not callable in [class CacheableModel(models.Model):] with Django (2.2.6) and Python 3.8.10
I am getting the error "TypeError: 'NoneType' object is not callable" as shown. Any help would be really appreciated! Traceback (most recent call last): File "C:\DCT\dct-server\Move-DCT-Server-to-AWS-with-azure-dev-secrets-manager-codepipeline-082019\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Python\Python38-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\DCT\dct-server\Move-DCT-Server-to-AWS-with-azure-dev-secrets-manager-codepipeline-082019\server\models.py", line 15, in <module> class CacheableModel(models.Model): File "C:\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "C:\Python\Python38-32\lib\site-packages\django\db\models\options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Python\Python38-32\lib\site-packages\django\db\__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Python\Python38-32\lib\site-packages\django\db\utils.py", line 202, in __getitem__ conn = backend.DatabaseWrapper(db, alias) File "C:\Users\yhuang\AppData\Roaming\Python\Python38\site-packages\mysql\connector\django\base.py", line 336, in __init__ super(DatabaseWrapper, self).__init__(*args, **kwargs) File "C:\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 102, in __init__ self.client = self.client_class(self) TypeError: 'NoneType' object is not callable the code … -
Is there a proper way to make factory boy connect to the test database
I'm experiencing a very annoying error on my project's test suites, because factory boy is running every test case on the main/default database, instead of running the queries on the proper test database. I tried adding the Meta class configuration to a factory class (as recomended in this post), but as soon as I try to run the django test suite, the application throws an error stating that the connection to the test database does not exist. I would very much appreciate any help, since the documentation is not clear at all about this situation. My settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": 'DB_NAME', "USER": 'DB_USER', "PASSWORD": 'DB_PSSWD', "HOST": 'DB_HOST', "PORT": 3306, "TEST":{ "NAME": 'TEST_DB_NAME', }, "OPTIONS": { "init_command": "SET sql_mode='STRICT_TRANS_TABLES'; SET foreign_key_checks = 0;", }, } } my factory.py: import factory class CustomModelFactory(factory.django.DjangoModelFactory): class Meta: model = models.CustomModel database = 'TEST_DB_NAME' django_get_or_create = ('nu_cnpj',) nm_razao_social = factory.Faker(locale='pt_BR', provider='company') nu_cnpj = factory.Faker(locale='pt_BR', provider='company_id') my model.py: from django.db import models class CustomModel(models.Model): nu_cnpj = models.CharField(unique=True, max_length=20, blank=True, null=True) nm_razao_social = models.CharField(max_length=255, blank=False, null=False) The error: python manage.py test flux.tests.test_data_leak_main_db --keepdb Traceback (most recent call last): File "C:\Users\project\venv\lib\site-packages\django\db\utils.py", line 172, in ensure_defaults conn = self.databases[alias] KeyError: 'TEST_DB_NAME' During handling of … -
How to access and use Django's SchemaEditor?
The docs say Each database backend in Django supplies its own version of SchemaEditor, and it’s always accessible via the connection.schema_editor() context manager: with connection.schema_editor() as schema_editor: schema_editor.delete_model(MyModel) Note: In this question, they have the object and method reversed from the docs: schema_editor.connection! But how do you find it to use it? I tried this in the repl: with connection.schema_editor() as schema_editor: NameError: name 'connection' is not defined ModuleNotFoundError: No module named 'SchemaEditor' ModuleNotFoundError: No module named 'DatabaseSchemaEditor' NameError: name 'BaseDatabaseSchemaEditor' is not defined import BaseDatabaseSchemaEditor ModuleNotFoundError: No module named 'BaseDatabaseSchemaEditor' Then i dove into the source, after which I tried: from django.db.backends.base import base from django.db.backends.base.base import BaseDatabaseWrapper se = schema_editor() se = schema_editor() NameError: name 'schema_editor' is not defined se = BaseDatabaseWrapper.schema_editor() TypeError: schema_editor() missing 1 required positional argument: 'self' se = BaseDatabaseWrapper.schema_editor(self) NameError: name 'self' is not defined bdw = BaseDatabaseWrapper() TypeError: __init__() missing 1 required positional argument: 'settings_dict' from BaseDatabaseWrapper import schema_editor ModuleNotFoundError: No module named 'BaseDatabaseWrapper' ...even though it let me import it.... settings_dict = { ...: 'ENGINE': 'django.db.backends.sqlite3', ...: 'NAME': 'db.sqlite3', ...: } bdw = BaseDatabaseWrapper(settings_dict) TypeError: 'NoneType' object is not callable And after all that, I quit and came here. Help? Thanks. -
How do I post on a django model when it has another model (manytomany ) inside nested serializers, I want at the same time to create both
My models are: Period ClassStudentSubject Period has a manytomany relationship with ClassStudentSubject When I POST a period I don't want to choose which existing ClassStudentSubject object I use, I want to create a new one together with the period. ClassStudentSubject - I created this model for the sake of structuring some data of period into an object -
Get exact date format in excel from Python Datetime field
I have some question how can I get exact format date in excel.I need create excel cheat from some data(in my models.py "date_result_stamp" it's DateTime field) in Django project and I don't know how I can pass to excel exact date not str or another type of data result["date_result_stamp"] = datetime.strftime(result["date_result_stamp"], "%Y-%m-%d") but it's str format I need get in excel date format. Can you help me