Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show count of objects of inline objects in inline object Django Admin
I have a FormAdmin where aj I have in inlines a LanguageInline. LanguageInline has model Language. LanguageAdmin that is registered with Language model as "admin.site.register(Language, LanguageAdmin)" has in inlines QuestionInline where is the model Question. Model Question has FK to model Language. What I need to do if I want to display count of questions objects of the language in LanguageInline field in FormAdmin. Thanks. -
Optimising Querys in Django from within a model
I have a model that has a few attributes on it. Each one of these relies on a database call outside the scope of the table itself. I am currently making a query to get the required data. However, I can have anywhere from 30-80 of these models in a single call, resulting in a very high amount of database calls. In addition, is this also done again on the same model for is_last. I can save the instance to a global variable which cuts the call down in half. class ModelA(Model): a = ABCFeild() ... Shortened for brevity def is_first(self): pu = self.user.programusers_set.filter(is_active=True).first() cadence = timedelta(days=pu.program.checkin_cadence) start = pu.start_date if((start + cadence) == self.checkin_date): return True return False I have tried using prefect_related and Prefetch on the original call, but I am finding out the model itself is unaware of these. View.py query.prefetch_related(Prefetch('checkin_set', queryset=Checkin.objects.prefetch_related(Prefetch('answers', queryset=Answers.objects.select_related('question').all()))), 'programusers_set') Any advice on how to reduce the number of calls made? -
Django 2.0 getting all model list
I need a list of django models registered, Just like django admin index page. I'm using django 2.0 where from django.contrib.admin.validation import validate and from django.db.models import get_models is outdated. Advance thanks. -
Inserting ListView Template in a section of the Homepage using Django 1.11
I have a ListView Template in Django 1.11 that renders to group_list.html. However I want the same view to show in a column in the home page I also have screenshots below if that helps understanding what I am trying to achieve I have tried different ways to use {% include 'some.html' %} 1) I tried to make a html page and include it in homepage. but it keeps giving errors 2) I tried to change the group_list.html page into a (insert template) that and tried to insert that, in both the index page and created another template view for groups. but that is giving errors too Below are my views and templates Views.py class GroupCreate(LoginRequiredMixin, CreateView): model = Group fields = ('name', 'description') class GroupList(ListView): model = Group class GroupDetail(DetailView): model = Group Below is my Index.html and group_list.html INDEX.HTML {% extends 'base.html' %} {% block body %} <div class="col-md-8" style="background-color:white; border-right:1px solid grey;"> <h4>Groups</h4> <p>Join a group or make a new Group.</p> <a style="float:left" class="btn btn-success" href="{% url 'groups:new' %}">Start a Group</a> <div class="content"> <!--{ % include 'groups/some.html' % } I am trying to insert my --> </div> </div> <div class="col-md-4" style=background-color:white"> <h4>Second Coloumn</h4> </div> {% endblock %} … -
Django REST - how to see remaining throttle limit?
I've added throttling to my Django REST framework api - but I want to be able to show users how many requests they have left. How can I find this number for each user? Thanks -
Heroku can't find my 'settings.py' file
After deploying my django project on heroku get this in logs: File "/app/django_structure/src/django_structure/wsgi.py", line 16, in <module> 2018-03-23T12:09:10.575053+00:00 app[web.1]: application = get_wsgi_application() 2018-03-23T12:09:10.575056+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2018-03-23T12:09:10.575058+00:00 app[web.1]: django.setup(set_prefix=False) 2018-03-23T12:09:10.575061+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 19, in setup 2018-03-23T12:09:10.575064+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2018-03-23T12:09:10.575067+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ 2018-03-23T12:09:10.575069+00:00 app[web.1]: self._setup(name) 2018-03-23T12:09:10.575072+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup 2018-03-23T12:09:10.575075+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2018-03-23T12:09:10.575077+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ 2018-03-23T12:09:10.575080+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2018-03-23T12:09:10.575083+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2018-03-23T12:09:10.575085+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2018-03-23T12:09:10.591042+00:00 app[web.1]: ModuleNotFoundError: No module named 'django_structure.settings' Settings.py contains here: django_structure->src->django_structure. Procfile: web: gunicorn django_structure.src.django_structure.wsgi Wsgi.py: s.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_structure.settings") Project link: https://github.com/AlfredMulder/Django_work -
Django: Form autopopulated by a select choice Model Form
Hello everyone I want to create a form in django as a country form, when you select a country the next select box of states only shows you the states of that country. Models: class Family(models.Model): name = models.CharField( max_length=50, ) class Detail(models.Model): name = models.CharField( max_length=50, ) family = models.ForeignKey( 'Family', related_name='details', on_delete=models.SET_NULL, blank=True, null=True, ) unit = models.CharField( max_length=50, blank=True, ) unit_price = models.DecimalField( max_digits=15, decimal_places=2, blank=True, ) iva = models.BooleanField( default=True, ) class BudgetItem(models.Model): family_id = models.ForeignKey( 'Family', on_delete=models.SET_NULL, blank=True, null=True, ) detail_id = models.ForeignKey( 'Detail', on_delete=models.SET_NULL, blank=True, null=True, ) quantity = models.FloatField() unit = models.CharField( max_length=50, ) unit_price = models.DecimalField( max_digits=15, decimal_places=2, ) iva = models.PositiveIntegerField( default=16, blank=True, null=True, ) I'm using a normal CreateView but I want to have a create form for budget item that when i select a Family in the next select only shows the Details that have a relation with that Family and when i choose a Detail I want to autocomplete the Budgetitem's fields that are the same with Detail's fields but with the option of edit that strings in the form. The versions of django and python that I'm using are Django 2.0.2 and Python 3.6.4 Thanks! -
Issue with django rest framework when creating new objects
I am trying to use django rest framework to create instances of a Bookmark model for different types of content, for example Book. The code: models.py class Bookmark(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') api.py from django.contrib.contenttypes.models import ContentType from rest_framework import viewsets, mixins, serializers, permissions from .models import Bookmark class BookmarkSerializer(serializers.ModelSerializer): class Meta: model = Bookmark fields = ('id', 'user', 'content_type', 'object_id') class BookmarkViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): content_type = self.request.query_params.get('content_type') app, model = content_type.split(".") ct = ContentType.objects.get_by_natural_key(app, model) object_id = self.request.query_params.get('object_id') serializer.save(user=self.request.user, content_type=ct, object_id=object_id) def get_queryset(self): items = Bookmark.objects.filter(user=self.request.user) content_type = self.request.query_params.get('content_type', None) if content_type: app, model = content_type.split(".") ct = ContentType.objects.get_by_natural_key(app, model) items = items.filter(content_type=ct) object_id = self.request.query_params.get('object_id', None) if object_id: items = items.filter(object_id=object_id) return items get_queryset part is fine. But perform_create fails when I try to create a new Bookmark: var item = new Bookmark({'content_type': 'books.book', 'object_id': self.book_id}); item.save(); The response: {"user":["This field is required."],"content_type":["Incorrect type. Expected pk value, received unicode."]} It is not clear to me how I am supposed to do this. I would appreciate any feedback. -
What is instance in python? How to use it?
In some functions, especially in django signals i often see parametr instance. def client_transaction_pre_save(sender, instance: ClientTransaction, **kwargs): instance.remain = abs(instance.amount) if instance.remain is None else instance.remain if instance.currency.is_primary: instance.internal = instance.amount instance.custom_rate = 1 I can not find answer in the other questions. Was a question with title self vs instance, but there nothing is clear Please explain me -
Prevent Load with Select2 until minimumInputLength is met
I’m a student python/django developer whom is new to select2 4 rc and javascript. I’ve managed to get select2 working properly. However, I have a large list of data that select2 bogs down on. I’ve attempted to use the minimumInputLength, which works fine but the application still bogs down because the amount of data being loaded. The javascript I’m using is below. How can I make initial data load of the template not search data until the minimumInputLength is met? $(document).ready(function () { $('.js-example-basic-multiple').select2({ minimumInputLength: 3, placeholder: 'Select a Student ID', }); }); I’m rendering the select two function in my html below: <div class="col"><h4 style="margin-top: 0"><strong>3-4 ID User Search</strong></h4><select class="js-example-basic-multiple" value = "{{ userid }}" style="width: 1110px" required> {% for user in userid %} <option value="{{ user }}"> {{ user }}</option> {% endfor %} </select> I’ve tried the solution below that I found on stack overflow, but i believe that requires server side pagination, and using this solution my select2 never occurs and it shows the normal select box. So, perhaps it's missing something. $(document).ready(function () { $('.js-example-basic-multiple').select2({ minimumInputLength: 3, allowClear: true, placeholder: { id: -1, text: 'Enter the Student ID.', }, ajax: { type: 'POST', url: '', contentType: … -
Django ModelForm ForeignKey query
I want to have a form which only offers the user to post a question for a project he is participating in. models.py: class Project(models.Model): project_name = models.CharField(max_length=255, unique=True, blank=False) def __str__(self): return str(self.project_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) project = models.ManyToManyField(Project) def __str__(self): return str(self.user) class Question(models.Model): title = models.CharField(max_length=255, blank=False) content = tinymce_models.HTMLField(blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) ... def __str__(self): return str(self.title) class QuestionForm(ModelForm): class Meta: model = Question fields = ['title', 'content', 'project'] in views.py: form = QuestionForm() form.fields["project"].queryset = Project.objects.filter(project_name__in=request.user.profile.project.all()) But somehow the result of the query always stays empty. Does somebody maybe have an idea what I am missing? -
Passing data from Django views/template into the static javascript
This question has been asked in multiple ways, however the solutions such as defining variables before the script tag haven't worked. template.html <script> var locations = {{ some_variable }} </script> <script type="text/javascript" src="{% static 'base/scripts/maps.js %}"></script> I believe this is because maps.js is actually a function. The start of it is as follows: maps.js (function($){ "use strict"; function mainMap() { var ib = new InfoBox(); // Infobox Output function locationData(locationURL,locationImg,locationTitle, locationAddress, locationRating, locationRatingCounter) { return('SOME_HTML_WITH_VARIABLES') } // Locations var locations = [ [ locationData('listings-single-page.html','images/listing-item-01.jpg',"Tom's Restaurant",'964 School Street, New York', '3.5', '12'), 40.94401669296697, -74.16938781738281, 1, '<i class="im im-icon-Chef-Hat"></i>'], ]; What I want to do is to pass location data from my model e.g. {% for model in query_list %} [ locationData('link_to','img_url','{{ model.name }}','{{ model.address }}', '5', '10'), {{ model.latitude }}, {{ model.longitude }}, {{ forloop.counter }}, '{{ model.icon }}'], {% endfor %} Possible solution: Post the whole maps.js file in the template.html, inside the script tag. But this file has 10000+ lines. -
Is a django formset supposed to be used, when only one form should be submitted?
A formset helps create a set of forms, and helps you process them all together. I am creating a view which displays all instances of a certain type of request towards a user (ie. payment requests, friend requests, etc), however, the user should only be allowed to respond to one at a time. Traditionally, there is one submit button for the entire formset (all forms), and you process all the submitted data. In this case, I'd prefer one submit button per form, and detect which form was submitted before processing it. Some ideas to do this via a formset are: - Create submit button per form and labeling them differently, and then searching for the button id in request.POST The question is: is a formset suitable for this situation when you want multiple forms instantiated, but only process the submission of one of them? Thank you. -
django views not able to configure filter
from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView,ListView,DetailView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Post # Create your views here. def index(request): return HttpResponse("Hello, world.") class HomePageView(LoginRequiredMixin,ListView): model = Post template_name = 'home.html' context_object_name = 'deeppost' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['deeppost'] = Post.objects.filter(author=request.user) return context everytime i use author=request.user , i get an error saying the follwing NameError at / name 'request' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.2 Exception Type: NameError Exception Value: name 'request' is not defined Exception Location: C:\Django\Django\MyProject\Pitsnews\views.py in get_context_data, line 24 Python Executable: C:\Users\deepd\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\Django\Django\MyProject', 'C:\Users\deepd\AppData\Local\Programs\Python\Python36\python36.zip', 'C:\Users\deepd\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\deepd\AppData\Local\Programs\Python\Python36', 'C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib\site-packages', 'C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib\site-packages\django-2.0.2-py3.6.egg', 'C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib\site-packages\pytz-2018.3-py3.6.egg'] Server time: Fri, 23 Mar 2018 18:26:02 +0000 Traceback Switch to copy-and-paste view C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib\site-packages\django-2.0.2-py3.6.egg\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib\site-packages\django-2.0.2-py3.6.egg\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib\site-packages\django-2.0.2-py3.6.egg\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib\site-packages\django-2.0.2-py3.6.egg\django\views\generic\base.py in view return self.dispatch(request, *args, **kwargs) ... ▶ Local vars C:\Users\deepd\AppData\Local\Programs\Python\Python36\lib\site-packages\django-2.0.2-py3.6.egg\django\contrib\auth\mixins.py in dispatch return super().dispatch(request, *args, **kwargs) ... ▶ Local … -
How to use Django forms' get_initial_for_field() method?
I have two models Company and Package, defined as follows: class Company(models.Model): default_package = models.OneToOneField( Package, blank=True, null=True, related_name='default_for_%(class)s') class Package(models.Model): company = models.ForeignKey('lucy_web.Company') where lucy_web is the name of the app. So there is a many-to-one relationship between Package and Company, and additionally, a one-to-one relationship between a Company and its default_package. I'm making a ModelForm for the Package object, of which a simplified version is class PackageForm(forms.ModelForm): class Meta: model = Package fields = [ 'is_default', ] is_default = forms.BooleanField(initial=True, required=False) def save(self, *args, **kwargs): package = super().save(*args, **kwargs) if self.cleaned_data['is_default']: package.company.default_package = package package.company.save() return package So when is_default is set to True, the package gets set to its company's default package. The problem is that this form is used in both a generic CreateView and and UpdateView, and in the UpdateView, the is_default is still set to True even if the package is not the default package. This would make it easy for a user to inadvertently change a package to default when actually they just want to change another field. I would like to make the initial for is_default such that it is True for unbound forms, and for bound forms, is True only when … -
django custom groups and permissions
Sorry fro my english. I want create different groups and for this groups different permissions. This is my model for custom permissions: class Companies(models.Model): . . class Meta: permissions = ( ("view_company", "Can view company"), ("create_company", "Can create company"), ("update_company", "Can update company"), ("delete_company", "Can delete ) then i create fixtures group.json [ {"model": "auth.group", "pk": 1, "fields": {"name": "test_group"}, "permissions": ["companies.view_company"]} ] after this i did loaddata group.json then i created test method in view, but before i added user to group test_group like this: user = User.objects.get(email=request.user.email) my_group = Group.objects.get(name='manager') my_group.user_set.add(user) in my view i added permission_classes permission_classes = (TestPermissionForView,) and my test class TestPermissionForView class TestPermissionForView(permissions.BasePermission): def has_permission(self, request, view): my_user = request.user if request.user.has_perm('companies.view_company'): return True else: return False always return False -
Change value of session variable in template Django
In Django, I can get the value of a session variable with {{ request.session.variable_name }} How can I change the value of variable_name inside a template? Something like {% request.session.variable_name.set(new_value) %} -
Edit parameter description for Django REST swagger and other issues
I. I'm new to using Django REST Swagger for API documentation. I'm trying to understand how to edit a) 'Implementation Notes' and b) parameter descriptions. Image below - Here's my viewset for the 'Crash' model. class CrashViewSet(viewsets.ModelViewSet): """ retrieve: Get a single Crash instance list: Get a list of all Crashes """ queryset = Crash.objects.all() serializer_class = CrashSerializer filter_backends = (SearchFilter,DjangoFilterBackend,OrderingFilter,) search_fields = ('crash_id','crash_hr_short_desc','urb_area_short_nm','fc_short_desc', 'hwy_compnt_short_desc','mlge_typ_short_desc', 'specl_jrsdct_short_desc', 'jrsdct_grp_long_desc','st_full_nm','isect_st_full_nm','rd_char_short_desc', 'isect_typ_short_desc','crash_typ_short_desc','collis_typ_short_desc', 'rd_cntl_med_desc','wthr_cond_short_desc','rd_surf_short_desc','lgt_cond_short_desc', 'traf_cntl_device_short_desc','invstg_agy_short_desc','crash_cause_1_short_desc', 'crash_cause_2_short_desc','crash_cause_3_short_desc','pop_rng_med_desc','rd_cntl_med_desc') filter_fields = ('ser_no','cnty_id','alchl_invlv_flg','crash_day_no','crash_mo_no','crash_yr_no','crash_hr_no', 'schl_zone_ind','wrk_zone_ind','alchl_invlv_flg','drug_invlv_flg','crash_speed_invlv_flg', 'crash_hit_run_flg',) ordering_fields = '__all__' I have made some edits to the DocString but don't quite understand how to proceed so as to get a more thorough descriptions of the endpoints and their fields. I tried going through the Django REST Swagger tutorial but I'm not given any direction on how to format the DOCSTRING. What's the best way to do this? II. Another minor issue is that I want to get rid of the 'Django Login' button since this is public API. How do I do this? III. What are some best practices for API documentation? -
Django forms. TypeError: __init__() got an unexpected keyword argument 'instance'
I keep getting error messages and have no idea why. I think it has to do with the variable for instance, but i see a lot of examples all over the internet that work the same way. models.py class Establishments(models.Model): title = models.CharField(max_length=255) town = models.ForeignKey(Town, on_delete=SET_NULL, null=True) addrstreet = models.CharField(max_length=255) addrzip = models.CharField(max_length=12) telephone = models.CharField(max_length=15) email = models.CharField(max_length=255) chamberofcomnr = models.CharField(max_length=25) description = models.TextField(max_length=255) website = models.CharField(max_length=255) categorie = models.ForeignKey(Establishmentcategory, on_delete=SET_NULL, null=True) pub_date = models.DateTimeField('date published') drupuser = models.ForeignKey(Drupalusers, on_delete=SET_NULL, null=True) druppublished = models.BooleanField() drupurl = models.CharField(max_length=255) drupnodeid = models.IntegerField() def __str__(self): return self.title class Impcalendar(models.Model): establishment = models.ForeignKey(Establishments, on_delete=SET_NULL, null=True) active = models.BooleanField() prio = models.IntegerField() url = models.CharField(max_length=255) check_intervalh = models.IntegerField() check_fixedh = models.IntegerField() log = models.BooleanField() cuttag = models.CharField(max_length=255) cuttxt = models.CharField(max_length=255) cuttxtend = models.CharField(max_length=255) comment = models.CharField(max_length=255) page = models.TextField() pageold = models.TextField() change = models.TextField() pagedate = models.DateTimeField() pagedatenext = models.DateTimeField() status = models.IntegerField() errors = models.IntegerField() def __str__(self): return str(self.id) urls.py path('calendar/<int:calendar_id>/', views.calendaredit, name='calendaredit') views.py def calendaredit(request, calendar_id): calendar = get_object_or_404(Impcalendar, pk=calendar_id) print (calendar.url) form = ImpcalendarForm(request.POST or None, instance=calendar) # if this is a POST request we need to process the form data if request.method == 'POST': # create a form … -
How to undisplay the field with empty value in django admin?
I am currently working on django. I created 4 classes in models.py, one of them is ReactionMeta class. This class has 62 columns, which defined as below: class Reactionsmeta(models.Model): id = models.ForeignKey('Reactions', db_column='id', primary_key=True, max_length=255, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=True, null=True) metabolite1 = models.ForeignKey('Metabolites', db_column='metabolite1', blank=True, null=True, on_delete=models.CASCADE) stoichiometry1 = models.CharField(max_length=255, blank=True, null=True) metabolite2 = models.ForeignKey('Metabolites', db_column='metabolite2', blank=True, null=True, on_delete=models.CASCADE, related_name='+') stoichiometry2 = models.CharField(max_length=255, blank=True, null=True) metabolite3 = models.ForeignKey('Metabolites', db_column='metabolite3', blank=True, null=True, on_delete=models.CASCADE, related_name='+') stoichiometry3 = models.CharField(max_length=255, blank=True, null=True) metabolite4 = models.ForeignKey('Metabolites', db_column='metabolite4', blank=True, null=True, on_delete=models.CASCADE, related_name='+') #... Some of the reactions, may have 6 metabolites, however, some of reactions may only have 2 metabolites and stoichiometries, which means there is no value of this reaction in metabolite3,4,5,6...columns and stoichiometry 3,4,5,6...columns. In that case, how can I only display the Charfield with data while undisplay those Charfield with no value in django-admin? -
Django add user to group error "is not a valid UUID"
Sorry for my english. I want add user to group, but i have custom User whith id id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) then i try add user to custom group: user = User.objects.filter(email=request.user.email) my_group = Group.objects.get(name='test_group') my_group.user_set.add(user) but have eroor ["'<QuerySet [<User: nesalexy@gmail.com>]>' is not a valid UUID."] -
Django - updating TimeField in forms/formsets returns value without microseconds
I have problem with updating TimeField in my models - when I want to edit objects using forms/formsets the input field on my site is always cutting microseconds. I made ex. class with TimeField: class Participant(models.Model): surname = models.CharField(max_length = 256) name = models.CharField(max_length = 256) birth = models.DateField(blank = True, null = True) entry_time = models.TimeField(blank = True, null = True) ... Then I made a form: class ParticipantForm(forms.ModelForm): .... entry_time = forms.TimeField(initial="HH:MM:SS.00", required = False, widget=forms.TimeInput(format=('%H:%M:%S.%f'))) .... When I am adding new Participant via my form everything is OK. Value of entry_time is saving in my database with properly format(hours:minutes:seconds.microseconds). But there is a problem when I want to update my participants using this form or formsets. Data loaded to form is always without microseconds (hours:minutes:seconds). The output on my site looks like this (photo) first generated by: {{ formset.time_score }} second: <input type="text" value="{{ participant.time_score|time:"H:i:s:u" }}"> It doesn't metter if I use form or formset - results are the same. Hope for your help guys, i can't figure it out. -
ModelChoiceField always raises
i have a ModelChoiceField that containts clients names selected from my database. but when submiting the form i get : "Select a valid choice. That choice is not one of the available choices" here is my form : class FormVents(forms.Form): client_name=forms.ModelChoiceField(queryset=client.objects.all().values_list('nom', flat=True),required=False) def clean(self): client_name = self.cleaned_data.get('client_name') print(client_name) i tryed to print client_name to check if i can get the value but i get None ! i guess that's why i always get that error Dont know what's the problem? is the way i call the field is not right ? any help please . Thank You so much -
Converting month number to month name
The code below fetches the month number correctly, but I want to retrieve the month name and not the number. I've tried using Django date filters in the template, as well as Calendar utils in views.py but that doesn't seem to work views.py def ticket(request, month, year): airline = Airline.objects.get(id=request.user.airline_id) for ts in Timestamp.objects.filter( airline=airline, usage_on__year=year, usage_on__month=month ): pass return TemplateResponse(request, 'club/al_history.html', { 'usage_month': month, 'usage_year': year, 'timestamp': timestamp, }) al.html {% extends 'base.html' %} {% block content %} <h3>{{ usage_month }}, {{usage_year}}</h3> {% endblock %} -
strange variable environment behavior of python in docker
i use docker-compose services: web_c: build: context: . dockerfile: ./closed/Dockerfile command: /start-dev.sh environment: - C_TYPE=CLOSED env_file: .env volumes: - .:/app - media:/app/media ports: - "8001:8001" # second application use same code base web_d: build: context: . dockerfile: ./depart/Dockerfile command: /start-dev.sh environment: - C_TYPE=DEPART env_file: .env volumes: - .:/app - media:/app/media ports: - "8002:8002" docker file identical, difference only they copy different sh file # web_c # in file start-dev.sh port 8001 COPY ./c/start-dev.sh /start-dev.sh # web_d # in file start-dev.sh port 8002 COPY ./d/start-dev.sh /start-dev.sh # file start-dev.sh echo `hostname -I|tr -d '[:space:]'`:8002 python manage.py runserver `hostname -I|tr -d '[:space:]'`:8002 in django settings.py file i use C_TYPE like C_TYPE = os.environ.get("C_TYPE") after that i have 2 instance with identical code base in /admin/ i check this variable and i have strange behavior when i press F5 inside template /admin/ C_TYPE sometimes change ))) <span>C_TYPE -> NONE: PORT -> 8000: socket.gethostname() ->02295671bdbf </span> <span>C_TYPE -> CLOSED: PORT -> 8000: socket.gethostname() ->3fc771b93db0</span> why? i use different port, i use different ip i dont know what do now (