Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hide subset of queryset used as Foreign Key by default....show complete queryset in Django admin
In my Django models a Product belongs to a ProductCategory class FinancialProduct(models.Model): product_category = models.ForeignKey(ProductCategory, null=True) I want to be able to create a new ProductCategory 'behind-the-scenes', so that by default they don't show up in any queries. The exceptions to this are Django admin, and one very specific other query. To achieve this, I created a Manager for ProductCategory: class ProductCategoryManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=ProductCategory.STATUS_PUBLIC) def get_complete_queryset(self): return super().get_queryset() Then in admin.py: @admin.register(FinancialProduct) class ProductAdmin(admin.ModelAdmin): model = Product def get_queryset(self, request): return Product.objects.get_complete_queryset() Generally this works great, but when I go into Product on Django admin and try to add a hidden ProductCategory, it can't find it: product category instance with id 3 does not exist. Should I carry on down the path of trying to override the querysets Django admin uses, or is there a smarter way? Ideally I want to avoid having to use a filter everywhere, as it's the kind of thing people forget. Note: I've spotted the docs actually do not recommend this approach -
Status 500 for POST requests in django on IIS
Dear StackOverflow community, your help would be greatly appreciated. I have zero experience with IIS. Unfortunately, a Windows Server 2012 with IIS 8.5 is all I can get for the current project. I followed this post by Matt Woodward to get my Django app running on IIS. I serve static files by means of an application that references the static folder. The app looks the way it is supposed to look and all GET requests are processed properly. However, the response to all POST requests (on localhost and remotely) is Status 500 Server Error. If I run my Django app with the runserver command, the POST requests are processed properly. POST is NOT blocked in IIS Request Filtering -> HTTP Verbs. POST requests are sent to URLs like http:/site_title/update_plan/, not to html. The StackOverflow posts found here and here were not helpful. I suspect the problem is in the IIS settings, but maybe some special Django settings are required and I am missing it. Any ideas on what can be done to fix the problem would be of great help. Thanks! -
add new record to many to many relation in django rest framework
I was trying to add new relation to many to many records, for example i got this models models.py class Team(models.Model): name = models.CharField(blank=True, unique=True, max_length=100) players = models.ManyToManyField(User, blank=True, related_name='players') class TeamInvite(models.Model): from_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='invite_by', blank=True, null=True) to_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='invite_to', blank=True, null=True) team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='invite_to_team', blank=True, null=True) status = models.NullBooleanField(blank=True, null=True, default=None,) and my serializer serializers.py class TeamInviteCreateSerializer(serializers.ModelSerializer): team = serializers.PrimaryKeyRelatedField(queryset=Team.objects.all()) from_user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) class Meta: model = TeamInvite fields = ('id', 'from_user', 'to_user', 'team', 'status') after that the user which in to_user will take an action to TeamInvite like accept or decline. what I need the serializer that will take the new user and add him to the existing team like the following serializer class TeamInviteAcceptDeclineSerializer(serializers.ModelSerializer): method_name = serializers.SerializerMethodField() class Meta: model = TeamInvite fields = ('id', 'from_user', 'date_time', 'team', 'method_name', 'status') def get_method_name(self, *args, **kwargs): method_name = None # kwargs['context']['request'].method_name return method_name def update(self, instance, validated_data): instance.team = validated_data.get('team', instance.team) method_name = validated_data.get('method_name') instance.status = validated_data.get('status', instance.status) instance.to_user = validated_data.get('to_user', instance.to_user) if method_name == 'decline': instance.status = False else: instance.status = True team = Team.objects.get(pk=instance.team.pk) team.players.add(instance.to_user) # team.players.create(team_id=team, user_id=instance.to_user) team.save() instance.save() return instance now in def update work fine but it … -
Django template {%load templatetags%} insert chars?
I'm triyng to use the django template system to generate a plain text file, but it seems that inserting this: {%load label_template_tags%} generate some strange variation to the row. If I look at the text with notepad++ with compare it show a warning on the row. This is my template: <?xml version="1.0" encoding="utf-8"?>{%load label_template_tags%}\r\n This is how should result: <?xml version="1.0" encoding="utf-8"?>\r\n Why this happen, which char is added by the load? Is there a way to avoid this? -
Django: UnboundLocalError: local variable 'company' referenced before assignment
I am trying to make a url field in my detail view by passing two primary key in it... This is what I have done in urls.py: url(r'^company/(?P<pk1>\d+)/groupdetail/(?P<pk2>\d+)/$',views.group1DetailView.as_view(),name='groupdetail'), And in my views: def get_object(self): pk1 = self.kwargs['pk1'] pk2 = self.kwargs['pk2'] company = get_object_or_404(company, pk=pk1) group1 = get_object_or_404(group1, pk=pk2) return group1 I am getting error in this line: company = get_object_or_404(company, pk=pk1) And in my group1 list view I have done this: <a href="{% url 'accounting_double_entry:groupdetail' pk1=company_details.pk pk2=group1_details.pk %}">{{group1.group_Name}}</a> Can anyone tell me what I am doing wrong in this code? Thank you -
Django REST Framework slow on Gunicorn
I deployed a new application made on Django REST Framework running with Gunicorn. The application is deployed on 4 different servers and they are listening on a port (8001) which is consumed by an HAProxy load balancer. Unfortunately I am suffering many performance problems: many requests takes seconds to be served, even 30 or 60 seconds. Sometimes even the basic entry endpoint (like https://my.api/api/v2 which basically returns the list of the available endpoints) requires 10/20 seconds to respond. I don't think the problem is the load balancer because I have latencies connecting directly to any backend servers with my client, so bypassing the load balancer. And I don't think the problem is the database because the call to https://my.api/api/v2 as guest (not logged with any user) shouldn't make any database query. This is a performance test made with hey (https://github.com/rakyll/hey) on the basic endpoint without authorization: me@staging2:~$ hey -n 10000 -c 100 https://my.api/api/v2/ Summary: Total: 38.9165 secs Slowest: 18.6772 secs Fastest: 0.0041 secs Average: 0.3099 secs Requests/sec: 256.9604 Total data: 20870000 bytes Size/request: 2087 bytes Response time histogram: 0.004 [1] | 1.871 [9723] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 3.739 [0] | 5.606 [175] |■ 7.473 [0] | 9.341 [35] | 11.208 [29] | 13.075 … -
How to fix UI of BS DataTable on row append/prepend using mustache templating
I am using mustache templating to prepend a row on my bs_datatable upon successful submit using ajax. But the problem is that the datatable's UI becomes ruined after append. I have tried redrawing the datatable using .draw() but the newly prepended row now won't appear. What am I doing wrong? Or is it necessary for me to use mustache for this? Here's my codes: html: <div class="row mt10"> <div class="col-12"> <table id="data_table" class="table nowrap table-striped table-bordered"> <thead> <tr role="row"> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> </tr> </thead> <tbody id="data_table_row_cont"> {% for item in data %} <tr role="row"> <td>{{item.column_1}}</td> <td>{{item.column_2}}</td> <td>{{item.column_3}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> //mustache template <script type="text/template" id="mustache_row_content"> <tr role="row"> <td>{{item.column_1}}</td> <td>{{item.column_2}}</td> <td>{{item.column_3}}</td> </tr> </script> script: datatable = $('#data_table').DataTable({ responsive: true, info: false, paging: false, scrollCollapse: true, "ordering": true, searching: false, }); $("#form").submit(function(e){ e.preventDefault(); jQuery.ajax({ type: "POST", url: url, dataType: "json", data: data, cache: false, contentType: false, processData: false, success: function(response){ if(response.success){ //get mustache template (row template) var template = $("#mustache_row_content").html(); //assigning values to mustache template var html = Mustache.to_html(template, {'item': response.data}); //prepending the row template to datatable's tbody $('#data_table_row_cont').prepend(html); datatable.draw(); } } }); }); -
How do i add <input type="button"> as a formfield in django
I want to have an input field as a button in my template. Just like this.I am manually rendering form fields in my template.So, how do i create a field like that in my form. -
What is the best database design for a digital document platform?
I need to create a database that sources data to multiple documents. These documents have multiple fields with few field names being common and sometimes data of few fields being common too. A school mark sheets Marksheet_1: Name: xxxx, Roll No.####, Section:## ------------------------------------ Mathematics: ##/## Physics: ##/## Chemistry: ##/## --------------- Total: ###/## --------------- Result: passed/promoted/xxx * A note to remember Marksheet_2: Name: xxxx, Roll No.####, Section:##, Sub-Section: #xx ------------------------------------------------------ Mathematics: ##/## Algorithms: ##/## Data Analysis: ##/## Physics: ##/## -------------------------------- Total: ###/## -------------------------------- Result: passed/promoted/failed/xxx * A note to remember Things to consider in the school marksheet: different classes have different subjects. students of same class can have an elective subject with different total marks. What would be the best way to implement this in a database? -
Customize Django Serializer output with to_representation
i want to add Status and place the output of serializer into DATA: My Model: class UserDetails(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) user_group_id = models.ForeignKey(UserGroup, on_delete=models.CASCADE) admin_photo = models.ImageField(upload_to='user_image',blank=True) My Serializer: class UserDetailSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(many=False) user_group_id = serializers.StringRelatedField(many=False) class Meta: model = UserDetails fields = [ 'user', 'user_group_id', 'admin_photo', ] depth = 1 def to_representation(self, instance): data = super(UserDetailSerializer, self).to_representation(instance) return { 'STATUS' : 'SUCCESS', 'DATA' : data } the response i got is this: [ { "DATA": { "user": "user1", "user_group_id": "Super Admin", "admin_photo": "http://www.someurl.com/media/22-black-wallpaper.jpg" }, "STATUS": "SUCCESS" }, { "DATA": { "user": "user2", "user_group_id": "Admin", "admin_photo": "http://www.someurl.com/media/fox.jpg" }, "STATUS": "SUCCESS" } ] but i want response like this, status are basic text, and i want to put the result from Class meta into DATA { "STATUS": "SUCCESS", "DATA": [ { "user": "user1", "user_group_id": "Super Admin", "admin_photo": "http://www.someurl.com/media/22-black- wallpaper.jpg" }, { "user": "user2", "user_group_id": "Admin", "admin_photo": "http://www.someurl.com/media/fox.jpg" } ] } -
how to create a middleware for validation all text field in django
how to create a middleware for validation all text field in django such as prevent insert dngerous charachter for prevent sql injection by django or exist other way to do validation on all request in center location -
How to store python list in django?
I have a list of np arrays. Each time i make a post, the image is converted to an numpy array, and that array is compared to my list of arrays. How do i store my list of numpy arrays in Django? Currently i have stored the list as a string in the List class, and recoverting it everytime i need to use it. class List(models.Model): encodings = models.TextField(max_length=20000) def __str__(self): return self.encodings so unknown_face_encoding is the list of numpy arrays that i wish to store: unknown_face_encoding = face_recognition.face_encodings(unknown_image) unknown_face_encoding_lists = [] for encoding in unknown_face_encoding: unknown_face_encoding_lists.append(encoding.tolist()) unknown_face_encoding_strings = json.dumps(unknown_face_encoding_lists) known_face_encoding_stored = List(encodings = unknown_face_encoding_strings) and then when i need to retrieve it, i do this: known_faces_str = List.objects.first().encodings known_faces_lists = json.loads(known_faces_str) known_faces_array =[] for encoding in known_faces_lists: known_faces_array.append(np.array(encoding)) what's the right way to do this ? -
Most simple way to check object exist and give responce
I have a code snippet which repeats several times in my ViewSets: def accept(self, request, pk): if not Company.objects.filter(pk=pk).exists(): return Response({"message": "Error"}, status=status.HTTP_405_METHOD_NOT_ALLOWED) It looks like I'm doing this too complex. Is it a way to make it simpler? Thanks! -
Using two settings (prod and dev) with django site, dev doesn't allow admin
Currently I am using two separate settings. One of them is the prod settings file that I upload to heroku in every push(postgres). The other one I use for development(sqlite3). All works well in production (thank heavens) however, the admin site doesn't work in production. I am using python manage.py --settings=djangoroot.devsettings to run the dev server. However, the admin site is giving me the following: DoesNotExist at /admin/login/ Site matching query does not exist. Here is my devsettings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'c(s+3-(=_22lr86m)6km!kn&q9irg7fn$19=--wl*p=)k_bgl&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['djangoandreact.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'corsheaders', 'rest_auth', 'rest_auth.registration', 'rest_framework', 'rest_framework.authtoken', 'articles' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'djangoroot.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = … -
SMTPAuthenticationError: (535, 'Authentication failed: account disabled') Python app
My Python app using sendgird account on Heroku to send email for user when they forgot password or login by link. Problem is the sendgrid account, after 1-2 month using get disable, and I must change to new account. Blockquote Full log: Error: Traceback (most recent call last): File "user_profile/services/profile.py", line 595, in send_mail_with_perm msg.send(fail_silently=fail_silently) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/message.py", line 292, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python2.7/site-packages/email_log/backends.py", line 27, in send_messages num_sent += message.send() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/message.py", line 292, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages new_conn_created = self.open() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 67, in open self.connection.login(self.username, self.password) File "/app/.heroku/python/lib/python2.7/smtplib.py", line 623, in login raise SMTPAuthenticationError(code, resp) SMTPAuthenticationError: (535, 'Authentication failed: account disabled') Anyone get same problem ? -
Django unit testing for Verbose_name
Below is a class in model.py class UnitUsers(models.Model): unit = models.ForeignKey(Unit, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) create = models.BooleanField(default=False) mark = models.BooleanField(default=False) submit = models.BooleanField(default=True) def __str__(self): return str(self.unit) + " - " + str(self.user) class Meta: verbose_name = _('Unit User') verbose_name_plural = _('Unit Users') Tried to write test case for verbose_name as below class UnitUsersTest(TestCase): @classmethod def setUpTestData(cls): unit = Unit.objects.create(name='Python', start='2018-10-25 14:30:59', end='2017-10-25 14:30:59', description='111', deleted='False') user = get_user_model().objects.create_superuser(username='admin', email='admin@decent.mark', password='password') UnitUsers.objects.create(unit=unit, user=user, create='False', mark='False', submit='True') def test_verbose_name(self): unit_user = UnitUsers.objects.get(id=1) field_label = unit_user._meta.get_field('user').verbose_name self.assertEquals(field_label, 'Unit User') Getting error as FAIL: test_verbose_name (decentmark.tests.test_model.UnitUsersTest) Traceback (most recent call last): File "C:\Users\Prabhanjan\Documents\GitHub\decentmark\decentmark\tests\test_model.py", line 54, in test_verbose_name self.assertEquals(field_label, 'Unit User') AssertionError: 'user' != 'Unit User' - user + Unit User Ran 11 tests in 0.505s FAILED (failures=1) -
Create a Django's model which can have one of two types
I have a model Client which can be one of two types: PJ or PF. That means that a Client can have the fields of a PJ model or the fields of a PFmodel. But I'm not sure how I can do it using the Django's models and admin app. I would like to give the user the option to select which type the Client is and then the appropriate fields will be shown to him/her. Can someone help me with this problem? Should I use some kind of Design Pattern or how should I create my models? Thanks in advance. Model PF: class PF(models.Model): name = models.CharField(max_length=512) card = models.IntegerField(unique=True) Model PJ: class PJ(models.Model): ie = models.IntegerField(unique=True, null=True, blank=True) Model Client: class Client(models.Model): type = models.SmallIntegerField(default=0) # 0=PF, 1=PJ -
Is it possible for a uid to be repeated or duplicated by Django if two different models have one?
Let's say I have two models both with uuidfields: class ModelA(models.Model): did = models.UUIDField( unique=True, editable=False, default=uuid.uuid4, ) class ModelB(models.Model): did = models.UUIDField( unique=True, editable=False, default=uuid.uuid4, ) Is it possible that over time and many model instances created that Django will serve the a modelA instance and a modelB with identical uids? If so how do I avoid this? Is there a way to append a number to the value of the field to help prevent this from happening? -
Wagtail render any path in index page
I need to enable some pages to write an arbitrary URL that does not depend on the structure of the site. class IndexPage(RoutablePageMixin, Page): ... @route(r'^(?P<path>.*)/$') def render_page_with_special_path(self, request, path, *args, **kwargs): pages = Page.objects.not_exact_type(IndexPage).specific() for page in pages: if hasattr(page, 'full_path'): if page.full_path == path: return page.serve(request) # some logic But now, if this path is not found, but I need to return this request to the standard handler. How can I do it? -
Problem with django rest auth and react native
I am trying to make a login page with a react native frontend and a django-rest-auth backend, but when I send my request: `login = () => { fetch('http://myIp/rest-auth/login/', { method: 'POST', header: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.state.username, password: this.state.password, }) }) .then((response) => response.json()) .then((res) => { if (res.success === true) { AsyncStorage.setItem('user', res.user) this.props.navigation.navigate('Profile') } else { alert(res.message) } }) } }` My backend returns: Unsupported Media Type I only use django-rest-auth api endpoints. What is the problem ? Thank you for your help ;D -
Django, how to assign a record to a different staff member?
class Enquiry(models.Model): CONSULTANT = { ('JAS', "do@do.com"), } first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) email = models.EmailField(max_length=100) phone_num = models.CharField(max_length=35) message = models.TextField(max_length=3000, blank=True, default='') processed = models.BooleanField(default=False) assigned_to = models.CharField(max_length=30, choices=CONSULTANT, default='JAS') date_added = models.DateTimeField(auto_now_add=True) These records are submitted from the website. The problem is, i am trying to initially have all enquiries go to me. do@do.com, but on the admin dahsboard i have created, I will have a href for enquiries. The staff memeber will only get enquiries that have been assigned to them. I dont know how to go about this. should i make assigned_to field a ForeignKey, if so i have a custom user that inputs email and password. or should i use something like request.user.id. should i somehow find my id, and set this as default. or is there a better method. Maybe i should asssign the user or email address as a dictionary in the view. any advice will be greatly appreciated. -
Setting the original field as the default. [django-modeltranslation]
I am experimenting with django-modeltranslation at the moment and have created a toy based on polls. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') My settings.py has: LANGUAGE_CODE = 'en-GB' LANGUAGES = [ ('en', 'English'), ('de', 'Deutsch') ] MODELTRANSLATION_DEFAULT_LANGUAGE = 'en' MODELTRANSLATION_LANGUAGES = ('en', 'de',) My translation.py includes: class QuestionTranslationOptions(TranslationOptions): fields = ('question_text',) translator.register(Question, QuestionTranslationOptions) Everything is working fine and I know have the following tables in the database. id question_text pub_date question_text_de question_text_en However, it just seems to me to be a bit redundant to have "question_text_en" if the default language is English. I tried taking out 'en' from MODELTRANSLATION_LANGUAGES but then I get "django.core.exceptions.ImproperlyConfigured: MODELTRANSLATION_DEFAULT_LANGUAGE not in LANGUAGES setting." -
Django and Mongoengine updating Embeddedfiel
I am currently using Django 2.1 with Mongoengine. I am trying to update a list of an embedded field, but keep running into errors. currently, I have an entry that looks like this { "_id" : ObjectId("5bb28c8b2dba311eac0a1dd9"), "user_id" : 1, "custom_list_id" : "76I7C680", "list_name" : "Test List", "contacts" : [ ] } I would like it to add to the contacts sections of that entry. After it adds it can be something like { "_id" : ObjectId("5bb28c8b2dba311eac0a1dd9"), "user_id" : 1, "custom_list_id" : "76I7C680", "list_name" : "Test List", "contacts" : [{email:'test@test.com',fname:'john', lname:'doe'....}, {email:'test@test.com',fname:'john', lname:'doe'....} ] } so that everytime a new `contacts entry is added it will add a new spot to the array. Model.py class Tags(EmbeddedDocument): tags = ListField(StringField(max_length=50)) class Contact_Info(EmbeddedDocument): email = EmailField(required=True) first_name = StringField(max_length=200, required=True) last_name = StringField(max_length=200, required=True) address = StringField(max_length=600, required=True) tags = EmbeddedDocumentField(Tags) date_added = DateTimeField(default=datetime.datetime.utcnow) date_changed = DateTimeField(default=datetime.datetime.utcnow) class Customer_List_Info(Document): user_id = IntField(required=True) custom_list_id = StringField(max_length=9, required=True) list_name = StringField(max_length=200, required=True) contacts = ListField(EmbeddedDocumentField(Contact_Info)) -
Filtering a model on a foreign key
Alright, I am pulling my hair out (and I don't have much) I have created a FormView that uses 2 models. One model simply displays some information from a table (not editable) the other Model is a form that a user selects two items from a drop down box. I need to filter the first Dropdown box. Below is the code I am using that is not working: views.py def assign_load(request): form = DispatchForm(request.POST or None) loads = Load.objects.all().filter(active=True, dispatched=False, picked_up=False, delivered=False, billed=False, paid=False).order_by('start_pickup_date') context_dict = {'dispatch' : form, 'load' : loads} if form.is_valid(): save_it = form.save() save_it.save() new_dispatch = Dispatch.objects.get(id=save_it.id) fix_load = Load.objects.get(id=new_dispatch.load_number_id) fix_load.dispatched = True fix_load.save() return HttpResponseRedirect('/dispatch/dispatch/') return render(request, 'dispatch/dispatch_form.html', context_dict) forms.py class DispatchForm(ModelForm): class Meta: model = Dispatch fields = ['load_number', 'truck', 'start_mileage', 'end_mileage', 'pickup_date', 'pickup_time', 'delivery_date', 'delivery_time', 'driver_pay', 'fuel_cost', 'miles', 'status'] def get_queryset(self): return self.model.objects.filter(load_number__dispatched=False) I am trying to filter the model in forms.py I have tried using def get(), def get_queryset() and def get_context_data, none of them are returning a filtered queryset...I know I am missing something simple but I am running out of ideas any help would be great...if you need more information let me know that as well. Thanks for all your … -
Create Date Range Slider in Django Form
I am facing some implementation issue in Django. My app reads data from excel uploaded by the user. It extracts dates from it such as earliest date and recent date. I am able to show these two date extracts in html form and let users custom select the time range. (thru' django forms.py). To make a better user experience, I want to create a date range slider in the form that will allow the users. So far, I am able to find a Django package called django_range_slider. (https://github.com/shaklev/django_range_slider/tree/master/test_slider) I can also implement this packages features correctly as long as I have an integer values for the range. The moment I put date values on, it does not work very well. Here is forms.py: from django import forms from .fields import RangeSliderField from .models import TestModel from django.forms.widgets import SelectDateWidget class TestFieldForm(forms.Form): class Meta: model = TestModel fields = ['range_field','name_range_field','label_range_field'] def __init__(self, *args, **kwargs): super(TestFieldForm, self).__init__(*args, **kwargs) self.fields['name_range_field'] = RangeSliderField(minimum=30,maximum=300,name="TestName") self.fields['range_field'] = RangeSliderField(minimum=10,step=10,maximum=102) self.fields['label_range_field'] = RangeSliderField(label=True,minimum=1,maximum=100) class fcPForm(forms.Form): label_range_field = RangeSliderField(label="Date Range",minimum="",maximum="") # with label (no name) Here is models.py: from __future__ import unicode_literals from django.db import models class TestModel(models.Model): #range_field = models.CharField(max_length=200) #name_range_field = models.CharField(max_length=200) label_field = models.DateField() Here is …