Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get checkboxes to be arranged in a table structure instead of just vertically in Django?
I have a model with a MultiSelectField that I would like to appear on my form as a series of checkboxes. There are a lot of available options, so rather than display the checkboxes vertically, I would like to display them in 3 columns and 10 rows. I'm new to crispy forms and bootstrap but I think that would be the best way to go about it. How can I use them to accomplish this task? -
Django filter not passing value through url
I've been following this tutorial, https://www.youtube.com/watch?v=vU0VeFN-abU, but when I try to pass a value through the form no value appears after the '?' Do I have a typo somewhere? When I enter C34 what I should get in the url is: /?C34 Instead I just get: /? My code: #Urls.py path('', SampleFliterView, name='SampleFliterView'), #views.py def SampleFliterView(request): qs = Sample.objects.all() sample_number_query = request.GET.get('sample_number') container_name_query = request.GET.get('container_name') if container_name_query != '' and container_name_query is not None: qs = qs.filter(sample_number__icontains=container_name_query) context = { 'queryset': qs } return render(request, "container/filter.html", context) #html template <form class="" action="." method="GET"> <div class="form-row"> <div class="form-group col-12"> <div class="input-group"> <input class="form-control py-2 border-right-0 border " type="text" name="" value="" placeholder="Sample Number" name="sample_number"/> <span class="input-group-append"> <div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div> </span> </div> </div> </div> <div class="form-row"> <div class="form-group col-12"> <div class="input-group"> <input class="form-control py-2 border-right-0 border " type="text" name="" value="" placeholder="Container Name" name="container_name"/> <span class="input-group-append"> <div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div> </span> </div> </div> </div> <button type="submit" class="btn btn-primary">Search</button> </form> -
Django hosting for simple websites
I would like to ask for a recommendation for Django hosting service. We are currently developing simple presentation websites in webflow, but as experienced Django developer I would like to change that as webflow doesn't give me full control over code. Reasons for using webflow hosting so far are: - included hosting - included multiple domains (for development, testing, production) - easy to deploy on that domains - ssl certificate included - CMS I would appreciate hosting service with easy to set up and run multiple environments but with Django framework Thanks for your reply -
How can I access a many to one relationship primary key value from the template?
I have a many to one relationship with an Item model, and a Book model which is a type of Item. The Item has a primary key, and the Book has a primary key, and also a foreign key which is an item_id. I run a complex query on the SQLite db, using inner join, to retrieve all data from Item as well as all data from Book. What results from the query, among other data, is two pks as ids: one from the Item, and one from Book data. In SQLite the heading for the Item pk is 'id' while the heading for the Book id is listed as 'id:1'. In views, I run the query to collect the objects into a book_qs queryset. In the template I try to loop thru the queryset to retrieve and display the value of the objects in a table. Because there are two ids or pks, one for Item and another for Book, I cannot figure out to retrieve just the Book id pk which is labelled as id:1 from the queryset. Id returns the Item id. At times in the loop, I only want to retrieve the Book id, but I … -
Problem installing package mysqlclient on shared hosting
I would like to install this package to contact the hosting database but I have a problem installing the package mysqlclient on shared hosting Where these orders were used pip install mysqlclient easy_install mysqlclient Where this error resulted pip install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Complete output from command /home2/ali/virtualenv/myproject/3.7/bin/python3.7 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-j8e2vv1i/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-wtifemuw --python-tag cp37: ERROR: /opt/alt/python37/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.7/MySQLdb creating build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/MySQLdb gcc -pthread -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,4,2,'post',1) -D__version__=1.4.2.post1 -I/usr/include/mysql -I/opt/alt/python37/include/python3.7m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.7/MySQLdb/_mysql.o -g -fstack-protector -m64 -fPIC -g -fabi-version=2 … -
Django 2.1.7: Populate Child field with Selected Parent Attributes in Product Model
i have 3 Models: Category, SubCategory and Product. SubCategory is related to Category with a Foreignkey, and Product is related to Category and Subcategory through a ForeignKey. What My Db looks like: Category: Kids -->SubCategory: Beanies Category: Men -->SubCategory: Hoodies Now, When i want to add a Product and i select Kids, in the Product admin page, i only want related subcategories to show. what have i tried: 1- using formfield_for_foreignkey but i can't seem to grasp how it works. 2- i came accross this question Django Admin Show / Hide Fields If Specific Value Is Selected In A Dropdown but i think that it's more field related than value related. Suggestions i have found online: use ajax to fetch the subcategories and plug them in the child field. My Models (without parameters like unique, max_length and such): class Category(models.Model): name = models.CharField(max_length=250, db_index=True, unique=True) slug = models.SlugField(max_length=250, db_index=True, unique=True) class SubCategory(models.Model): parent = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=250, db_index=True) slug = models.SlugField(max_length=250, db_index=True) class Product(models.Model): parent = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") child = models.ForeignKey(SubCategory, on_delete=models.CASCADE) name = models.CharField(max_length=250, unique=True, db_index=True) slug = models.SlugField(max_length=250, unique=True, db_index=True) My Admin Models: @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = [ 'name', 'slug' ] @admin.register(SubCategory) class SubCategoryAdmin(admin.ModelAdmin): … -
where should i handle things like triggering notifications in django rest framework
From my understanding the objects in django rest framework have specific purposes Model: Representation of the data in a database Serializer: Converts models to json and requests to models (crud operations) View: External interface to the application. Accepting requests and returning the appropriate responses If I want to trigger socket push notifications or do anything else that doesn't exactly fit into the three objects by the definition I gave, where would I put it? Example: Let's say there is an object ChatMessage and whenever it is created some data needs to be send to a web socket to notify users. What is the appropriate place to handle that? -
Errno 2 no such file, even when absolute path is used
I have a script that converts the python code to it's pseudo code and want to integrate the script to website. I have placed the script in my converter app directory. My view function looks like this: def uploadFile(request): if request.method == 'POST' and request.FILES['pythonFile']: pyFile = request.FILES['pythonFile'] fs = FileSystemStorage() filename = fs.save(pyFile.name,pyFile) uploaded_file_url = fs.url(filename) converter.main(uploaded_file_url) return render(request,'converter/index.html',{ 'uploaded_file_url' : uploaded_file_url }) return render(request,'converter/index.html',{ 'error' : 'File not uploaded successfully' }) Here the converter.main() is the entry point of the script and it receives the full file path as an argument. But when I supply the uploaded_file_url which is basically like /media/test.py it throws the error File Not Found I wanted to know what basically went wrong. -
How do I generate a SELECT menu from Django's localflavor.us.models.USStateField utility?
I'm using Python 3.7 and Django. I'm using the "localflavor.us.models" package to store a state field in my model ... from localflavor.us.models import USStateField from phonenumber_field.modelfields import PhoneNumberField ... class UsLocation(models.Model): address_1 = models.CharField(_("address"), max_length=128) address_2 = models.CharField(_("address cont'd"), max_length=128, blank=True) city = models.CharField(_("city"), max_length=64, null=False) state = USStateField(_("state"), null=False) zip_code = models.CharField(_("zip code"), max_length=10, null=False) My question is, in a Django form, I'd like to create a select drop-down menu that mirrors a state selection. Is there a way I can get all the states provided by USStateField in some field in my view's context? I'm open to using another Django utility to validate the state. I'd prefer not to hard-code everything myself (if only to save on writing code). -
How can I get values for Model from DateRangePicker In Django Form
I need to date range eg: 03-05-2019 and 10-05-2019. and my Model has 2 DateField. I want save this values to my Model. Iam new on Django and my js level is low. how can get values from this js. I use this dataRange: http://www.daterangepicker.com/ My model; class dates(models.Model): startDate=models.DateField(verbose_name="Starting Date") lastDate=models.DateField(verbose_name="End Date") My View: def periods(request,id): form=PeriodsForm(request.POST or None) if form.is_valid(): form.save() return redirect('ayar') context = {"form":form} return render(request, "app/period-add.html", context) My Template; <input type="text" name="daterange" class="form-control" value="01/01/2018 - 01/15/2018" /> <script> $(function() { $('input[name="daterange"]').daterangepicker({ "startDate": "04/23/2019", "endDate": "04/29/2019" }, function(start, end, label) { console.log('New date range selected: ' + start.format('DD-MM-YYYY') + ' to ' + end.format('DD-MM-YYYY') + ' (predefined range: ' + label + ')'); }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); </script> -
How to fix Unhandled exception in thread started by <function wrapper at 0x7fd2e88c98c0>, "Cannot import name path"
I'm trying to build my first django server, and something is going wrong with getting the server running. I try running: ~/Documents/Coding Projects/rssReader/rssreader$ python manage.py runserverand it returns the following: Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7fd2e88c98c0> Traceback (most recent call last): File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/kevin/Documents/Coding Projects/rssReader/env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/kevin/Documents/Coding Projects/rssReader/rssreader/rssreader/urls.py", line 17, in <module> from django.urls import path, include ImportError: cannot import name path rssreader/urls.py contains the following: from django.contrib import admin from django.urls … -
How to download csv data from webpage using django management command and also import into db
I need a system which I can download a csv data from webpage using django management command and also import into db. I need download csv data every day from webpage that's why I need automated downloadable from webpage and import into db. Please help me -
Subtraction in Django
I'm doing an inventory, and I have part of the code working correctly: def add_art_view(request, pk, template_name='invstock/art_form.html'): id = get_object_or_404(Stock, pk=pk) form = StockForm(request.POST or None, instance=id) context = { 'form': form } if form.is_valid(): form.save() messages.success(request, ('Register Edited Successfully')) return redirect('invstock:art_list_view') return render(request, template_name, context) {% extends "base.html" %} {% block content %} {% if user.is_authenticated %} <h2><a href="{% url 'invstock:art_list_view' %}">ART FORM</a></h2> <form method="post">{% csrf_token %} <div class="form-group"> <label>Cantidad</label>{{ form.cantidad}} <label>Cantidad a debitar</label>{{ form.var_resta}} <label>Name</label>{{ form.name}} <label>ID</label>{{ form.id}} </div> <input type="submit" value="Submit" /> </form> {% endblock %} My intention is for example: to subtract the AMOUNT field minus the VAR_RESTA field but from the views, and store the resulting value in the AMOUNT field, something like AMOUNT = AMOUNT - VAR_RESTA, I have dilated for weeks this, because in all the research, videos, courses, I have not been able to find the answer, you can only analyze how to do it from the template, but it is not what I need. I Have found some examples like {{ myval|add:"-5" }}, or creating a template tag but this is far from what i want to do. Any help would be really appreciated. -
Django subquery with aggregate
I have two models called User and Transaction . Here i want to get the all the users with total sum of the transaction amount where status is success. I have tried with subquery but i am not getting how to annotate the aggregate of the subquery with conditions class User(models.Model): name = models.CharField(max_length=128) class Transaction(models.Model): user = models.ForeignKey(User) status = models.CharField(choices=(("success", "Success"),("failed", "Failed"))) amount = models.DecimalField(max_digits=10, decimal_places=2) subquery = Transaction.objects.filter(status="success", user=OuterRef('pk')).aggregate(total_spent = Coalesce(Sum('amount'), 0)) query = User.objects.annotate(total_spent=Subquery(subquery:how to do here ?)).order_by(how to order here by total_spent) -
IntegrityError at /add/ NOT NULL constraint failed: myApp_bookdetail.manager_id
I am having IntegrityError at /add/ NOT NULL constraint failed: myApp_bookdetail.manager_id class BookDetail(models.Model): manager = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True) name = models.CharField(max_length=100) author = models.CharField(max_length=100) inum = models.IntegerField() -
How to fix "django.core.exceptions.ValidationError: [“'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.”]"
models.py class Questions: question_text = models.CharField(max_length=200) pub_date = models.DateField(null=True, blank=True, default='') slug = models.CharField(max_length=10, unique=True, default="question") def __str__(self): return self.question_text views.py def import_sheet(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): request.FILES['file'].save_to_database( name_columns_by_row=2, model=Question, mapdict=['question_text', 'pub_date', 'slug']) return HttpResponse("OK") else: return HttpResponseBadRequest() else: form = UploadFileForm() return render(request, 'perfimport/import.html', {'form': form}) -
Django rest framework: There is a model that doesn't create with an id automatically when creating
There is a model that doesn't create with an id automatically when creating. When I get objects on client side, all other models have id but only the model doesn't have id. I send nested objects like this from client side. parent: { children: [ { grandchild: {}, }, ], } serializers.py is like this. And only GrandChild is created without id. What is the cause possibly? class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(many=True) class Meta: model = Parent fields = ... def create(self, validated_data): children = validated_data.pop('children') parent = Parent.objects.create(**validated_data) for child in children: grandchild = child.pop('grandchild', None) new_child = Child.objects.create(parent=parent, **child) if grandchild is not None: Grandchild.objects.create(child=new_child, **grandchild) return parent -
How can i defer a many to many field from object?
Im trying to defer a field from my model, but .defer() seems not working. Im running Django 1.9 with python 2.7. (example code, simplified) models.py class MyModelA(models.Model): title = models.CharField(max_lenght=50) file = models.FileField(upload_to='test/') class MyModelB(models.Model): title = models.CharField(max_lenght=50) defer_this = models.ManyToManyField(MyModelA, blank=True) views.py query = MyModelB.objects.defer('defer_this') for i in query: print i.title, i.defer_this.all() And it prints defer_this objects. Could somebody explain me how it works/why is this happening? -
How to make a test on a regex
I'm new in Django and I have just started to make tests on my web application. Firstly I'm not sure if it's necessary to run tests on regex model fields (like the one in my code), secondly, if the testing is necessary, how can I do it? I've already tried this solution: Unit Tests pass against regex validator of models in Django but it's not working. cf field needs a 16 chars string, but my function test_cf_max_length() is returning seller object even if the cf entered is wrong(<16 chars) models.py class Seller(User): cf = models.CharField(validators=[RegexValidator(regex='^.{16}$', message='Social Security Number', code='nomatch')], max_length=16) iban = models.CharField(validators=[RegexValidator(regex='^.{27}$', message='IBAN', code='nomatch')], max_length=27) is_seller = models.BooleanField(default=False) tests.py def setUpTestData(cls): Seller.objects.create(username='clara', cf='12345690123456', iban='123456789012345678901234567') def test_cf_max_length(self): seller = Seller.objects.get(id=1) with self.assertRaises(ValidationError): if seller.full_clean(): seller.save() self.assertEqual(Seller.objects.filter(id=1).count(), 0) -
Can I create another context to send through sum values
I want to create another context to send another query set through to the HTML. I want to send the sum of all total sales from the Transaction model to the HTML. Is this possible and if so how would I go about it? View Below @login_required def portfolio(request): context2 = { 'totals': Transaction.objects.filter(owner=request.user).annotate( total_spends=Sum('total_price')) } context = { 'transactions': Transaction.objects.filter(owner=request.user).values('currency').annotate( sum_amount_purchased=Sum('amount'), sum_total_price_purchased=Sum('total_price'), sum_amount_sold=Sum('sales__amount_sold'), sum_amount_current=F("sum_amount_purchased") - F("sum_amount_sold"), avg_amount_per_coin=Avg("amount_per_coin"), sum_total_price_current=ExpressionWrapper(F("sum_amount_current")*F("avg_amount_per_coin"), output_field=DecimalField()), sum_total_income=Sum('sales__total_price_sold'), sum_profit_loss=F("sum_total_price_current") + F("sum_total_income") - F("sum_total_price_purchased"), ) } return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio', 'totals': context2}) HTML below <div class = "col-md-6"> {% for total in totals.context2 %} <h1> Total Spent: {{ total.total_spends }}</h1> {% endfor %} </div> Transaction model below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) Sale model below class Sale(models.Model): amount_sold = models.IntegerField() total_price_sold = models.DecimalField(max_digits=8, decimal_places=2) date_sold = models.DateTimeField(default=timezone.now) note = models.TextField(default="") transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="sales") amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def __str__(self): return str(self.pk)+','+str(self.amount_sold) + ', '+self.note def save(self, … -
Django 2.2 AbstractUser and migration issue
I extend the Django user model like this: #core.models class Institute(models.Model): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message=institute_phone_help_text) name = models.CharField(_('name'), max_length=255) description = models.TextField(_('description'), blank=True) abbreviation = models.CharField(_('abbreviation'), blank=True, max_length=100) address = models.TextField(_('address'), blank=True) phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list websites = ArrayField(models.URLField(max_length=255), verbose_name=_('websites'), blank=True, null=True) class Meta: verbose_name = _('institute') verbose_name_plural = _('institutes') def __str__(self): return '{0} ({1})'.format(self.name, self.abbreviation) class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) institute = models.ForeignKey(Institute, on_delete=models.CASCADE) params = JSONField(_('params'), null=True, blank=True,) about_me = models.TextField(_('about me'), blank=True,) With an empty DB each time that I launch ./manage.py makemigrations core it creates always a new migration file import django.contrib.auth.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0002_auto_20190430_1655'), ] operations = [ migrations.AlterModelManagers( name='user', managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), ] I tried different combinations: ./manage.py makemigrations core ./manage.py migrate core ./manage.py migrate ./manage.py makemigrations core ./manage.py makemigrations core ./manage.py makemigrations ./manage.py migrate It always creates the migration file. Thanks. D -
Errno 10060: Page Fails to load on POST Request
I have a problem as the question titles states. Basically what I'm currently trying to do is debugging a POST issue. Where given a template csv file, user fills in cells with data. And on the webpage, the user is prompted to upload the file, hit Submit, and returns success or error message based on whether or not the data has been entered into the database. After fixing some minor data formatting issues in the csv file, I ended up with Error 10060, apparently on Socket module: File "C:\Users\user\AppData\Local\Programs\Python\Python27\lib\socket.py", line 575, in create_connection raise err error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond General code causing this issue is this one: def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a … -
Simplifying code with multiple loops and logic, into queryset aggregates
My models: class customer(models.Model): cstid = models.AutoField(primary_key=True, unique=True) insurance_number = models.CharField(max_length=100, blank=True, null=True) name = models.CharField(max_length=35) ageyrs = models.IntegerField(blank=True) class Admission(models.Model): id = models.AutoField(primary_key=True, unique=True) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) customer = models.ForeignKey(customer, on_delete=models.CASCADE) diagnosis = models.CharField(max_length=2000, default='', blank=True) date_admission = models.DateTimeField(default=timezone.now) ward = models.ForeignKey(Ward, on_delete=models.CASCADE) bed = models.ForeignKey(Bed, on_delete=models.CASCADE) discharged = models.BooleanField(default=False) ip_number = models.IntegerField(blank=True) ip_prefix = models.CharField(max_length=20, default='', blank=True) My objective: Set a variable to a query filter, adding a property, 'is_admitted' to the queryset, so that I can pass this query set to the template and use the property while displaying data. Code: def is_admitted(cust): admission = Admission.objects.filter(customer=cust, discharged=False) admission_results = len(admission) if admission_results > 0: return True return False my_q = or_q_if_truthfull( cstid=HospitalID, name__lower__contains=name.lower() if name else None, ageyrs=ageyrs if ageyrs.isdigit() else None, agemnths=agemnths if agemnths.isdigit() else None, mobile__contains=mobile if mobile else None, alternate__contains=alternate if alternate else None, email__lower__contains=email.lower() if email else None, address__lower__contains=address.lower() if address else None, city__lower__contains=city.lower() if city else None ) ORSearchResult = customer.objects.filter(my_q, linkedclinic=clinicobj) cust_set = [] cust_admission_status = [] for cust in ORSearchResult: cust_set.append(cust) cust_admission_status.append(is_admitted(cust)) print(f"Customer name: {cust.name} Admission status: {is_admitted(cust)}") cust_templ_set = zip(cust_set, cust_admission_status) And in template, I will do: {% for cust, status in cust_templ_set %} {{ cust.name }} {{ … -
JWT signature has expired despite of JWT_AUTH settings
The Problem I have Django (2.1.1) project with djangorestframework (3.8.2), djangorestframework-jwt (1.11.0). In the project I have settings.py with JWT_AUTH part like this: JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=30), 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=30), } On the client side there are Vue.js with axios for authentication process. So, the user can be logged in into the system. And process some operations an accordance with his privileges. But only about 4.30 minutes. After that time the same request to the server response with "Unauthorized" exception. And as I think, the source of the problem is within rest_framework_jwt.authentication: JSONWebTokenAuthentication class. It's raising 'Signature has expired' while debugging. The Question Why do this happen? How can I fix it? JWT_AUTH settings specify 30 days for expiration time, but it still doesn't work. -
Django forloop and all selectable radio buttons
Here is a seemingly simple task, creating a form using a set of records so the user can choose which record to go for, all using a radio button. <form action="" method="GET">{% csrf_token %} {% for record in select_records %} <div class="form-check indent-3"> <label class="form-check-label" for="radio{{forloop.counter}}"> <input type="radio" class="form-check-input" id="radio{{forloop.counter}}" name="{{record.get_model_name}}{{record.id}}" value="{{record.record_name}}"> {% if request.user.userprofile.head_shot_thumb %} <img src="{{ request.user.userprofile.head_shot_thumb }}" alt="Proforma creator"> {% else %} <div class="h2-li "> <i class="fas fa-user"></i> </div> {% endif %} {{ record.record_name }} - {{ record.date_created }} </label> </div> {% endfor %} The problem is that the form creates a list of radio buttons which are all selectable, just like how all the checkboxes are selectable. I have searched and compared my code to simple radio forms such as the one at W3schools, but I cannot figure it out. Any help is appreciated.