Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pagination - for loop in all pages
I have a list of objects that I would like to display in an ul/li. For that I do the code below: <ul id="myUL"> {% for l in lpps %} <li id="lpps"><a href="#">{{ l.codeACL }} {{ l.libelle }}</a></li> {% endfor %} </ul> The problem is that in my view, I ask to display only 15 objects per page. But I want to ignore this and display all the objects on all the pages. Is there something like for l in lpps.page(all)...? -
Translating cards
i am only one month django learning. i wanna do cards with word on eng so user can send translate in form and he will get true or false result so i have card like this: class Cards(models.Model): class Meta: verbose_name = "Карточка" verbose_name_plural = "Карточки" category = models.CharField(max_length=30, db_index=True) word = models.TextField(max_length=100, db_index=True) def __str__(self): return self.title so i need to compare request from user with 'word' i have in my database field and print result so can u tell me what i need to google to do this, because i can find nothing all day -
Inspect list of Celery jobs on command line
In a Celery setup with Django, I registered two tasks, email_slow_track and email_fast_track. I would like to inspect the list of jobs for each task on the command line, but I was unable to find the right command. Here's what I tried (my application name is api): inspect registered: This appears to list registered tasks, not jobs submitted under these tasks. However, it at least shows that the connection is set up properly, and that the tasks are known. $ celery -A api inspect registered -> celery@a5dac4396c0b: OK * api.celery.debug_task * email_fast_track [rate_limit=1/s] * email_slow_track [rate_limit=10/m] inspect query_task <task_name>: Empty result. I'm not sure what this command should do, and whether this is the expected result. $ celery -A api inspect query_task email_slow_track -> celery@a5dac4396c0b: OK {} inspect query_task <task_id>: Empty result. Just thought I'd give it a try ... $ celery -A api inspect query_task cb1ecc1c-5746-4d08-ad50-4bff4d57855b -> celery@a5dac4396c0b: OK {} Note that my tasks do run properly. I'm not trying to fix task execution; the issue here is getting a list of tasks. I am able to see all jobs with Celery Flower, so things are fine in general. But can I get that information from the command line? -
Django - can I do this without a raw query
I am learning Django, and have got quite a long way using the documentation and various other posts on stackoverflow, but I am a bit stuck now. Essentially I want to query the database as follows SELECT w.wname, w.act_owner_id, wi.act_code, wi.act_provider, SUM(ft.quantity) AS "position", prices.Current, prices.MonthEnd, prices.YearEnd, cost.avgcost, sec.securityName AS "security" FROM finance_wrapperinstance as wi INNER JOIN finance_wrapper as w ON (w.id = wi.wrapperType_id) INNER JOIN finance_security as sec ON (ft.security_id = sec.id) left outer JOIN finance_transaction as ft ON (wi.id = ft.investwrapperID_id) left outer Join (SELECT hp.security_id as secid, max(Case when hp.date = '2019-11-18' then hp.price end) as 'Current', max(Case when hp.date = '2019-10-30' then hp.price end) as 'MonthEnd', max(Case when hp.date = '2018-12-31' then hp.price end) as 'yearEnd' FROM finance_historicprice as hp GROUP BY hp.security_id ) AS prices ON (prices.secid =ft.security_id) INNER JOIN (SELECT trans.security_id AS secid, trans.investwrapperID_id as iwID, SUM((CASE WHEN trans.buysell = 'b' THEN trans.quantity ELSE 0 END)* trans.price) / SUM(CASE WHEN trans.buysell = 'b' THEN trans.quantity ELSE 0 END) AS avgCost FROM finance_transaction as trans GROUP BY trans.security_id, trans.investwrapperID_id) AS cost ON (cost.secid = ft.security_id and cost.iwID = wi.id) GROUP BY w.wname, wi.wrapperType_id, wi.act_code, wi.act_provider, ft.security_id but I don't know how to use the Django … -
Is there a way to handle admin radio buttons changes?
I have model (Object) which have some fields + rating: class Object(PolymorphicModel): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, db_column='author') title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.IntegerField(default=10) created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" There is also Comment model to these objects: class Comment(models.Model): object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, db_column='author') content = models.TextField() rating = models.TextField() approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.content}" Ok here is the deal, I have approved_object and admin_seen which are represented to radio buttons in Django Admin. I want, when, some of admins, open comment, which is not approved and check radio buttons for admin_seen and approved_object the script should update ratings and average rating with Comment.objects.filter(object_id=pk).aggregate(Avg('rating'))['rating__avg'] So I found how to rewrite save method with def save_method but I don't know how to handle if radiobutton is checked or not and update ratings? admin.py: class CommentScreenAdmin(admin.ModelAdmin): raw_id_fields = ('author', 'object') def save_model(self, request, obj, form, change): #to do... -
Python Django Countdown
well I write again because I implemented a timer in my test portal, the time is defined at the time of creating the exam, use the code of http://www.keith-wood.name/countdown.html for my html and Well, I need help on how to get the exam over when the timer reaches zero. takenquiz_form.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <!--Barra de progreso--> <div class="progress mb-3"> <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria- valuenow="{{ progress }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ progress }}%"></div> </div> <!--Cronometro--> <div class="mb-3" id="defaultCountdown" style="float: right"></div> <h2 class="mb-3">{{ quiz.name }}</h2> <hr> <div class="d-md-flex flex-md-equal w-100 my-md-3 pl-md-3"> <div class=" mr-md-3 pt-3 px-3 pt-md-5 px-md-5 overflow-hidden"> <p >Contenido: {{question.category}} </p> <h5 class="lead"> <strong>{{question.number}}.</strong> {{ question.text }} ({{ question.puntaje}} puntos)</h5> <!--Audio de la pregunta--> {% if question.document == 'False' %} {% else %} {% if question.document %} <audio controls> <source src="{{ question.document.url }}" type="audio/mpeg"> </audio> {% endif %} <p></p> {% endif %} {% if question.description %} <h5 class="lead">{{ question.description }} </h5> {% endif %} <form method="post" name="takenquiz" id="takenquiz" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary redirect" href="javascript:void(0)" onClick="document.takenquiz.submit();" >Siguiente →</button> </form> </div> <div class= " mr-md-3 pt-3 px-3 pt-md-5 px-md-5 … -
How to email specific users when a new question is registered
I would like to send an email to all teachers who teach subjects related to a new question (whether it is created by the admin panel or the question creation form) so that they can approve the question. How to do this? models.py class Usuario(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,verbose_name="Usuário") USUARIO_CHOICES = ( (UM,'Aluno'), (DOIS,'Professor'), ) tipoUsuario = models.IntegerField('Tipo de Usuário',choices=USUARIO_CHOICES,default=1) class Questao(models.Model): aOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra a") bOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra b") cOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra c") dOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra d") eOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra e") settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@outlook.com' EMAIL_HOST_PASSWORD = 'Mypassword' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'MySite <myemail@outlook.com>' views.py def add_questoes(request): if request.method == 'POST': # If the form has been submitted... form = QuestaoForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass form.save() subject = 'Questão adicionada' message = 'Há uma nova questão adicionada' recepient = str(sub['Email'].value()) send_mail(subject, message, EMAIL_HOST_USER, [recepient], fail_silently = False) return redirect('/') # Redirect after POST else: form = QuestaoForm() # An unbound form return render(request, 'polls/add_question.html', {'form': form}) forms.py class QuestaoForm(forms.ModelForm): aOpcao = forms.CharField(max_length=500,label="Letra a") bOpcao = forms.CharField(max_length=500,label="Letra b") cOpcao= forms.CharField(max_length=500,label="Letra c") dOpcao = forms.CharField(max_length=500,label="Letra d") eOpcao = forms.CharField(max_length=500,label="Letra e") … -
Django REST testing - how to specify pk argument referring to the model instance created in setUp function
I have a model "Article" and I want to test if authorized user can GET an individual article. The testing class is: class TestPost(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.user = User.objects.create_user( username='Name', email='test@company.com', password='secret') self.article = Article.objects.create( author = 'Author', title = 'Article title', body = 'Body content ...') def test_detail_user(self): request = self.factory.get(reverse('article_id', kwargs={'pk': 1})) request.user = self.user response = ArticleDetail.as_view()(request, pk=1) self.assertEqual(response.status_code, 200, f'Expected Response Code 200 - OK, received {response.status_code} instead.') The URL pattern is: path('<int:pk>/', ArticleDetail.as_view(), name = 'article_id'), And when running tests I get the following error: f'Expected Response Code 200 - OK, received {response.status_code} instead.') AssertionError: 404 != 200 : Expected Response Code 200 - OK, received 404 instead. I suppose the problem is in the specified 'pk', but I cannot figure out how to specify pk without stating an exact figure of 1. How can I refer to the article created in setUp function instead? -
How to render a radio button choice in Django Modelform based on enum field defined at the model level?
I have an enum field ("type") defined at the model level like below, how should I implement the corresponding ModelForm field in my model field? Actually the rendered HTML code don't output radio button and wraps this field within an empty list. Should "replicate" the enum choices within the form class in order to populate radio button choices, is there another to take advantage of choices already defined at the model level? Rendered HTML <div class="form-group"> <label for="id_type_0">Type</label> <ul id="id_type" class="form-control"> </ul> </div> models.py class Foo(models.Model): name = models.CharField(max_length=50, blank=False, null=False) TYPE_LIST = [ ('EXT_CL', 'Customer'), ('INT_TP', 'Internal third party'), ('INT_OW', 'Owner'), ] type = models.CharField(max_length=6, choices=TYPE_LIST,default='EXT_CL') class Meta: managed = True db_table = 'foos' fields = ('name','type') def __str__(self): object_name = self.name return object_name forms.py class FooCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix = '' self.fields['name'] = forms.CharField(label='Name',widget=forms.TextInput(attrs={ 'class': 'form-control' })) self.fields['type'] = forms.ChoiceField(label='Type',required=True,widget=forms.RadioSelect(attrs={ 'class': 'form-control' })) class Meta(object): model = Foos fields = ('name','type') def clean_name(self): name = self.cleaned_data['name'] return name def clean_type(self): type = self.cleaned_data['type'] return type template.html <form id="foo-create-form" method="post" action=" " role="form"> {% csrf_token %} <div class="form-group"> {{ foo_create_form.name.label_tag }} {{ foo_create_form.name }} </div> <div class="form-group"> {{ foo_create_form.type.label_tag }} {{ foo_create_form.type }} </div> </form> -
Cannot resolve django error. "Apps aren't loaded yet."
"python manage.py runserver" Tried to run. Receive “Apps aren't loaded yet.” Fixing INSTALLED_APPS doesn't help. I checked Traceback and thought that there was a cause in "init.py", but I couldn't understand. I think that there is a mistake in the method because "model" is split. Traceback File "/Users/t.a/Desktop/apasn/apasn_rest/apasn_back/apps/models/commons/__init__.py", line 1, in <module> from .accounts import * File "/Users/t.a/Desktop/apasn/apasn_rest/apasn_back/apps/models/commons/accounts.py", line 4, in <module> from django.contrib.auth.base_user import BaseUserManager File "/Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. settings/base.py INSTALLED_APPS = [ ... 'apps.apps.AppsConfig', ] apps/apps.py from django.apps import AppConfig class AppsConfig(AppConfig): name = 'apps' models/commons/init.py from .accounts import * apps/models/commons/accounts from django.db import models from django.utils import timezone from django.core.mail import send_mail from django.contrib.auth.base_user import BaseUserManager from django.core.validators import RegexValidator from django.utils.translation import gettext_lazy as _ import uuid as uuid_lib from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class UserManager(BaseUserManager): ... class User(AbstractBaseUser, PermissionsMixin): ... -
DateTimeField to str and read from str
I have a problem with understating how to deal DateTimeField. I have model with DateTimeField, view which returns jsons containing this field and another view which use provided data (as string) to filter result # model date = models.DateTimeField(auto_now=True) # first view return str((self.date.isoformat() for date in ...)) # f. exp: ['2019-11-19T15:22:47.788254+00:00'] # second view Row.objects.filter(data__lte=data_from_GET) If I have used 2019-11-19T15:22:47.788254+00:00 I reciver error ValidationError at /csv/ ["'2019-11-19T15:22:47.788254+00:00' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] I can not find an easy way (without string manipulation) to return data in a format acceptable by the filter method. What is interesting: 2019-11-19T15:22:47.788254-00:00 not ok 2019-11-19 15:22:47.788254+00:00 not ok 2019-11-19 15:22:47.788254-00:00 ok -
React & Django - How can I automatically reflect server changes on front-end?
Looking for a bit of advice. I have a current architecture of Django and PostgreSQL, where a whole lot of activity is happening to the data via the ORM, through scheduled jobs. The data on the backend is being processed and updated on roughly 30 second intervals. The data is available to the front-end through a bunch of DRF serialisers (basic REST API). This is just being piped to standard HTML templates at the moment. I'd like the React front-end to mirror this behaviour, and am looking for best-practice advice on how this is typically done. I know in practice how this works in other frameworks but am not certain of doing this well (namely, connecting React's DOM automation to server-side updates). (I don't want to get involved with websockets, at all.) Theoretically, I understand there is two ways to do this: Front-end AJAX polling the API for new data HTTP/2 Server Push Something built into React that will load stuff in incrementally? Appreciate the advice - (short examples would be really helpful if possible). -
How to re-initialize session variable?
I have develop a Django project with authentification app developped using Vitor Freitas's tutorials (https://simpleisbetterthancomplex.com). Now I wonder how can be my sessions variables re-initialized when user logout? Currently it does not re-initialize my sessions variables I did not develop any views for authentification so I do know how to do it -
how to upload multiple images in django
models.py from django.db import models class Ads(models.Model): business_id = models.CharField(max_length=20, blank=True, null=True) description = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) forms.py from django import forms from .models import Ads class AdsForm(forms.Form): class Meta: model = Ads fields = '__all__' view.py from .models import Ads from .forms import AdsForm from django.core.files.storage import FileSystemStorage def ads_view(request): if request.method == 'POST': form = AdsForm(request.POST, request.FILES) if form.is_valid(): business_id = request.POST.get('business_id') description = request.POST.get('description') image = request.FILES['image'] print(business_id) print(description) print(image) file_storage = FileSystemStorage() ads_obj = Ads(business_id=business_id, description=description, image=file_storage.save(image.name, image)) ads_obj.save() return redirect('/ads/') else: form = AdsForm() return render(request, 'ads/myads.html', {'form': form}) myads.html <form action="#" method="post" enctype="multipart/form-data"> <input type="text" name="business_id" class="form-control form-control" id="colFormLabelSm" placeholder=""> <textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea> <input type="file" name="image" class="form-control" id="exampleFormControlInput1" multiple> <button type="submit" class="btn btn-primary mt-5">Submit</button> </form> Here I'm trying to upload multiple images but in view i'm getting lastly selected one image only. How to get all images and save all images. Help me in this problem. -
Django "before dispatch" mixin
I am trying to define a mixin to set up a member and check for permissions before the view's dispatch is called but class hierarchy is "getting in the way". The behavior for a specific view would be: class Page1View(TemplateView): # ... def dispatch(self, request, *args, **kwargs): self.object = self.object() if not object_permission(request.user, self.object): raise PermissionDenied return super(Page1View, self).dispatch(request, *args, **kwargs) I would like to extract the bit before the super().dispatch() call into a mixin so that I can reuse it in different views: class Page1View(TemplateView, BeforeDispatchMixin): # ... class BeforeDispatchMixin(object): def get_object(self): # ... return object def dispatch(self, request, *args, **kwargs): self.object = self.object() if not object_permission(request.user, self.object): raise PermissionDenied # ??? # here we would want to call the inheriting class' dispatch method As per design doing what I am trying to do is impossible. What's an alternative here? -
How to upload multiple files in django rest framework?
I amm very new to django rest framework so sorry for the bad code.Here I am trying to upload multiple files at once with this code.But it is not uploading .I tested it into the postman but I get the 500 internal server error. What should I done to upload multiple files. models.py class Package(models.Model): name = models.CharField(max_length=255,unique=True) slug = AutoSlugField(populate_from='name') package_desc = models.TextField() class PackageGallery(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE,related_name='galleries') image = models.ImageField(upload_to='package_gallery') serializers.py class PackageGallerySerializer(serializers.ModelSerializer): image = serializers.ListField(child=serializers.FileField()) class Meta: model = PackageGallery fields = ['package','image','alt_text'] def create(self, validated_data): package= self.context['request'].data.get('package') image = validated_data.pop('image') for img in image: gallery = PackageGallery.objects.create(image=img, package=package, **validated_data) return gallery views.py class CreatePackageGallery(generics.CreateAPIView): serializer_class = PackageGallerySerializer parser_classes = [MultiPartParser,FormParser] queryset = PackageGallery.objects.all() -
in django admin page cannot add object there is error
enter image description here OperationalError at /admin/jobs/job/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/jobs/job/add/ Django Version: 2.0.2 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\codering\Desktop\myenv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: C:\Users\codering\Desktop\myenv\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\codering\Desktop\portfolio', 'C:\Users\codering\Desktop\myenv\Scripts\python38.zip', 'C:\Users\codering\Desktop\myenv\DLLs', 'C:\Users\codering\Desktop\myenv\lib', 'C:\Users\codering\Desktop\myenv\Scripts', 'c:\users\codering\appdata\local\programs\python\python38\Lib', 'c:\users\codering\appdata\local\programs\python\python38\DLLs', 'C:\Users\codering\Desktop\myenv', 'C:\Users\codering\Desktop\myenv\lib\site-packages'] Server time: Wed, 20 Nov 2019 10:45:27 +0000 this page is opeaning when i am trying to add object plzz need help -
How to create tabs for django admin?
How to create tabs for admin languages. Example like: Change book English Japanese Some models -
When creating models.py ,the row size too large issue is found ,how to solve this problem
** how to solve this issue ,raise errorclass(errno, errval) django.db.utils.InternalError: (1118, u'Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs'),can please help to solve this problem** from __future__ import unicode_literals from django.db import models Create your models here. class Newsdeatils(models.Model): news_provider_id = models.CharField(max_length=5000) news_title = models.CharField(max_length=5000) news_details = models.CharField(max_length=5000) news_image = models.CharField(max_length=5000) news_page_url = models.CharField(max_length=5000) next_page = models.CharField(max_length=5000) news_des = models.CharField(max_length=5000) -
Django Rest Framework combine 2 queries
i have machine model, supposing machine has different status such as produce, maintain, pending and etc. I would like to build an api to response the latest machine status by calling: http://127.0.0.1:8000/api/machinestatus/?machines=2,7 this endpoint should response the status for machine ID 2 and 7, I've tried many ways but still cannot make it work, please help model: class MachineStatus(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False) machine = models.ForeignKey( Machine, on_delete=models.CASCADE, blank=False, null=False) upt_time = models.DateTimeField(blank=False, null=False) status = models.CharField( max_length=1, choices=JOB, blank=False, null=False) def __str__(self): return f"{self.machine} {self.upt_time} {self.status}" class Meta: verbose_name_plural = "MachineStatus" serializer: class MachineStatusSerializer(serializers.ModelSerializer): upt_time = serializers.DateTimeField(read_only=True) status = serializers.CharField(read_only=True) user = serializers.SlugRelatedField(read_only=True, slug_field='username') machine = serializers.SlugRelatedField( read_only=True, slug_field='name') class Meta: model = MachineStatus fields = '__all__' view: class MachineStatusView(viewsets.ModelViewSet): ''' Machine Status View ''' queryset = MachineStatus.objects.all() serializer_class = MachineStatusSerializer def get_queryset(self): queryset = MachineStatus.objects.all() machines = self.request.query_params.get('machines') if machines: machines = machines.split(',') for i in machines: queryset = MachineStatus.objects.all() queryset = queryset.filter(machine=i).order_by('-upt_time')[:1] \\ question: how to combine queries' result? return queryset each "i" would call queryset with result of corresponding latest machine status, but the problem is how to combine these queryset in the for loop? thanks alot or is there any better other … -
Django model + Unique column on two tables (inheritance)
How to create constraint (on database to keep integrity) base on columns from child and parent table? Model: class DBMaster(models.Model): col1 = models.CharField() class DBOne(DBMaster): col_own .... col1 - should be this same how in DBMaster class Meta: constraints = [ models.UniqueConstraint(fields=['col_own', 'col1'], name='CON_UNIQUE_1') ] We can use materialized view but we wont. Any sugestions? -
How to get check box value in django
Views.py; def export_selectd_data_to_excel(request): if request.method == 'POST': chk_values = request.POST.getlist('chkselect') print(chk_values) return redirect(user_details) Html: <td> <input type="checkbox" name="chkselect" class="checkboxall" value="{{i.id}}"/> </td> Please help me with this https://i.stack.imgur.com/vzCtL.png -
Django datetime.date.min and Mysql DATE minimum value is different
Actual Question How can i deal with different minimum date in Django DateField and Mysql DATE type. What can be done to deal with the issue? TL:DR datetime.date.min has lower value than minimum supported in Mysql for DATE type. Saving datetime.date.min to Mysql is possible but it is not guaranteed to work. Context I'm working with Django (v1.11) model: class MyModel(model.Model): begin_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) Currently the fields with NULL value designate the lower and higher date range limits respectively. Example: Date range from beginning of time to today will be: mymodel.begin_date = None mymodel.end_date = datetime.date(2019, 11, 20) mymodel.save() The usage of None/NULL creates a need to convert it to datetime.date.min/datetime.date.max on any sorting operations etc. Simply put: its inconvenient and adds unnecessary complexity. My though was to do necessary migrations and start putting datetime.date.min/datetime.date.max instead of None/`NULL' But there is a problem: Mysql has different min/max date range According to the mysql docs: The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'. According to python docs: The smallest year number allowed in … -
ValueError: Cannot add "": instance is on database "default", value is on database "None"
I am trying to add data from excel into many-to-many relationships, but I have encountered an error like bellow, I have added the save () method to the individual object the way people say that error, but It still does not work, what should I do? ValueError: Cannot add "": instance is on database "default", value is on database "None" max_col = sheet_obj.max_column max_row = sheet_obj.max_row for i in range(2, max_row+1): cell_sv = sheet_obj.cell(row = i, column = 2) if cell_sv.value != None: sv = MyUser.objects.get(msv=cell_sv.value) MaLHP = sheet_obj.cell(row = i, column = 4).value HocPhan = sheet_obj.cell(row = i, column = 5).value TC = sheet_obj.cell(row = i, column = 6).value GiangVien = sheet_obj.cell(row = i, column = 7).value LopMonHoc = sheet_obj.cell(row = i, column = 8).value Thu = sheet_obj.cell(row = i, column = 9).value Tiet = sheet_obj.cell(row = i, column = 10).value GiangDuong = sheet_obj.cell(row = i, column = 11).value mh = MonHoc(MaLHP=MaLHP, HocPhan=HocPhan, TC=TC, GiangVien=GiangVien, LopMonHoc=LopMonHoc, Thu=Thu, Tiet=Tiet, GiangDuong=GiangDuong) svmh = SvMonHoc(Sv=sv) svmh.save() svmh.MonHoc.set([mh]) -
Django design for full and partial views
Title sucks, sorry. Here's what I mean. Our site has a navigation sidebar and I want it to behave like follows: when any of the navigation links is clicked, the corresponding page is loaded with AJAX when browsing to the page's URL, the full page is loaded This means we need to implement two versions of each page. My question is about what's the best way to go about this on Django. Two different views and two different routes There would be a Page1PartialView and a Page1View, each routed differently: url(r'^page1/partial/$', Page1PartialView.as_view(), name='page1_partial'), url(r'^page1/$', Page1View.as_view(), name='page1') The implementation would go something like this: class Page1PartialView(TemplateView): template_name = 'page1_content.html' class Page1View(Page1PartialView): template_name = 'page1.html' def get_context_data(self, **kwargs): context = super(Page1View, self).get_context_data(**kwargs) # build "full page" context on top of "content" context # ... return context Single view with different behavior There would be a unique view Page1View, which would behave differently depending on the type of request. class Page1View(TemplateView): template_name = 'page1.html' content_template_name = 'page1_content.html' def render_to_response(self, context, **response_kwargs): if not self.request.is_ajax(): return super(Page1View, self).render_to_response(context, **response_kwargs) html = render_to_string(self.content_template_name, context, RequestContext(self.request)) return JsonResponse({'html': html}) def get_context_data(self, **kwargs): context = self.get_partial_context_data(**kwargs) if not self.request.is_ajax(): # update "content" context data with extra "full …