Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WSGI problem on Eleastic Beanstalk with Django
Some days ago I have deployed a Django on AWS elastic beanstalk(EB) and it worked fine. Today, after a new deploy, where I did minor changes in view.py, the Django APP on EB has a very big problem and it becomes not accessible anymore. Looking at the log file in AWS EB I read this errors: Script timed out before returning headers: wsgi.py End of script output before headers: wsgi.py, referer ... Do you have any ideas how to solve this issues? I would like to thank you in advance, -
Image not being uploaded .I want to upload the image and save it into the database i've given the media root and media url
applyonline.html(I have given file fields for adhaarcopy and idcopy) <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="custom-file"> <input type="file" class="custom-file-input" id="customFile" name="adhaaarcopy"> <label class="custom-file-label" for="customFile">Choose file</label> </div> </div> <!--logic for no--> <div ng-if="showHideTest=='false'"> <div class="form-group"> <div class="form-group"> <label for="adhaar_eid">Aadhaar Enrollment ID(EID):</label> <input name="adhaar_eid" id="identityno" class="form-control" required> </div> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Identity Card)* </label> <input name="beneficiary_id_name" class="form-control" id="formGroupNameInput" placeholder="Enter your name" required> </div> <div class="form-group"> <label for="idno">Identity Number(Enclose Copy of Identity Card)*:</label> <input name="idno" id="identityno" class="form-control" required> </div> <div class="custom-file"> <input type="file" class="custom-file-input" name="idcopy" id="customFile"> <label class="custom-file-label" for="customFile">Choose file</label> </div> </div> </div> <button type="submit" class="btn btn-primary" style="margin-bottom:10px ">Submit</button> </form> </div> {% endblock %} </body> this is my views.py i've used POST.get @login_required def personal_detail(request): … -
Export HTML table to excel without page refresh using python
I have a web page in which user can generate a table with no of rows and no of columns input. Now I want to export this HTML table to an excel file using python. After some googling, I came to know about the to_excel snippet as shown below. import pandas as pd # The webpage URL whose table we want to extract url = "https://www.geeksforgeeks.org/extended-operators-in-relational-algebra/" # Assign the table data to a Pandas dataframe table = pd.read_html(url)[0] # Store the dataframe in Excel file table.to_excel("data.xlsx") As you can observe from the above code that the program navigates to the specified url, but in my web page, if the url is hit, all the data is gone (after page refresh) because I am generating number of rows and columns on the go without page refresh. Can someone suggest alternate approach for excel export of HTML table using python? -
Why si widthratio (multiplication) not working in my template?
I'm using Django 2.0 and Python 3.7. I've read I can do multiplication in templates by using widthratio -- multiplication in django template without using manually created template tag . However, in a template of mine, I'm trying this to no avail. I'm trying {% if widthratio articlestat.score 1 TRENDING_PCT_FLOOR >= articlestat.weighted_score %}style="font-weight:bold;"{% endif %} When my template is executed with this code, it gives the error ... Unused 'articlestat.score' at end of if expression. I want my if expression to say if the multiple of "articlestat.score" and "TRENDING_PCT_FLOOR" is greater than "articlestat.weighted_score," print this out, but I can't seem to figure out how to do that. -
Using prefetch_related on category, subcategory and features
I'm trying to loop over my FeatureCatergories, FeatureSubcategories and Features. I'm able to loop over my feature categories just fine. Now I want to loop over my feature subcategories and finally features. I'm not sure what to call in my template for subcategories.. Should it be {{featuresubcategory.title}}? What about features? views.py def features_view(request): context = { "feature_categories": FeatureCategory.objects.prefetch_related('featuresubcategory_set').all(), } return render(request=request, template_name="main/features.html", context=context) template.html {% for category in feature_categories %} {{category.title}} {% for subcategory in featuresubcategory %} {{ subcategory.title }} {% endfor %} {% endfor %} models.py class FeatureCategory(models.Model): title = models.CharField(max_length=50) featured_image = models.ImageField(blank=True, upload_to="features/") category_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Feature Categories" def __str__(self): return self.title class FeatureSubcategory(models.Model): title = models.CharField(max_length=50) category = models.ForeignKey('FeatureCategory', on_delete=models.CASCADE) category_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Feature Subcategories" def __str__(self): return self.title class Feature(models.Model): title = models.CharField(max_length=150) category = models.ManyToManyField(FeatureSubcategory) description = models.TextField() featured_image = models.ImageField(upload_to=image_dir) class Meta: verbose_name_plural = "Features" def __str__(self): return self.title -
Django EmailMultiAlternatives - When attach a file: Body becomes blank in email
I use EmailMultiAlternatives to send mail in my django application. Please find below code for reference: email = EmailMultiAlternatives( subject=subject, body=body_text, from_email=from_email, to=to_email, reply_to=reply_to_email, cc=cc_email, bcc=bcc_email ) email.attach_alternative(body_html, 'text/html') # attachments for attachment in attachments: email.attach(attachment.name, attachment.document.read()) email.send() Now problem is whenever there is any attachment, email body gets blank. Is there any conflict between attach_alternative and attach. Let me know if any doubt/confusion! Thanks -
Backward lookup in Django
Following are my model classes. class Categories(models.Model): name= models.CharField(max_length=255, unique=True) class Values(models.Model): category = models.ForeignKey(Categories) language = models.CharField(max_length=7) category_name = models.CharField(max_length=50) Lets say I have already got list of Values. Now I want to get name of the Category to which this Value object is related to. How can I do that ? Will appreciate your help. -
How do I create a field in my serializer to avoid a "TypeError: cannot unpack non-iterable Address object" error?
I'm using Django 2.0, Python 3.7 and the django-address module -- https://github.com/furious-luke/django-address . In short, the Address object depends on Locality objects (cities) and I have created my own model that depends on the Address object ... class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() Then I have created the below serializers to handle processing JSON being uploaded to create my model and its address object ... class AddressTypeField(serializers.PrimaryKeyRelatedField): queryset = Address.objects def to_internal_value(self, data): if type(data) == dict: locality = data['locality'] locality, created = Locality.objects.get_or_create(**locality) data['locality'] = locality address, created = Address.objects.create(**data) # Replace the dict with the ID of the newly obtained object data = address.pk return super().to_internal_value(data) ... class CoopSerializer(serializers.ModelSerializer): type = CoopTypeField() address = AddressTypeField() class Meta: model = Coop fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site'] def to_representation(self, instance): rep = super().to_representation(instance) rep['type'] = CoopTypeSerializer(instance.type).data rep['address'] = AddressSerializer(instance.address).data return rep def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Coop.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Coop` instance, given the validated data. … -
Django: OR with multiple statements
I want to fetch an object, sometimes with one condition and some other time adding (OR) another condition. With Laravel (PHP), this is easy to do: $q = MyModel::where('col1', $val1); if ($userWantsToAddAnotherOrCondition) { $q = $q->orWhere('col2', $val2); } At the end I have a query either with condition 'col1' = $va1 or 'col1' = $va1 OR 'col2' = $val2. In Django (python), I only know this way: q = MyModel.objects.filter(Q(col1=val1) | Q(col2=val2)) How can I add the second condition (col2=val2) with another statement ? -
Confirm user owns a social account without switching to a different logged user (django social auth)
I'm using Django social auth to log users in using Facebook, Twitter, etc as described, for example here. Scenario: A user is logged onto my platform using my native login system. I want them to validate that they own a particular Twitter account without redirecting them to a view where request.user is a new UserSocialAuth associated with their Twitter account. I want to show the user the Twitter login page but, after they provided their credentials, keep them logged in as they were rather than log them in as a different user. -
haystack and solr takes 1 positional argument but 2 were give
update_index.Command().handle( app_label, using=None, remove=indexJob.remove ) I am migrating from django 1.8 to django 2.2 and python 2.7 to python 3. I am having that error there, how can i fix it? -
Setting default value of field in model to another model instance
Model class SlackPermission(models.Model): STATUS_CHOICES = [ ('A', 'ACTIVE'), ('P', 'PASSIVE') ] account_type = models.CharField(max_length=100) status = models.CharField(max_length=1, choices=STATUS_CHOICES) class GithubPermission(models.Model): STATUS_CHOICES = [ ('A', 'ACTIVE'), ('P', 'PASSIVE') ] ACCOUNT_TYPE_CHOICES = [ ('A', 'ADMIN'), ('B', 'BASIC') ] field1 = models.CharField(max_length=100) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE_CHOICES) status = models.CharField(max_length=1, choices=STATUS_CHOICES) class Employee(models.Model): full_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) slack_permission = models.OneToOneField(SlackPermission, on_delete=models.CASCADE, related_name='Slack',default=SlackPermission.objects.get(pk=1)) github_permission = models.OneToOneField(GithubPermission, on_delete=models.CASCADE, related_name='Github',default=GithubPermission.objects.get(pk=1)) Error: ValueError: Cannot serialize: <GithubPermission: GithubPermission object (1)> There are some values Django cannot serialize into migration files. I am creating API just to create Employee. Where there is not option of giving slackpermissions and githubpermissions. How do I give default value in there? -
Why with SlugField model cannot be updated and without slugfield it can be updated?
In general, the data didn't change, I decided to remove the slug in the model and it all worked. Before that, when I changed something through the admin panel, and generally through any means nothing changed, but for some reason when I removed the slug field, any field changes. Why did it happen? Models (BEFORE REMOVING) from .for_slug import slugify as my_slugify class Quiz(models.Model): """Quiz model""" slug = models.SlugField('Url-адрес', max_length=50, blank=True) ..... def save(self, *args, **kwargs): """Use the custom slugfiy (for_slug.py)""" if not self.slug: slug = my_slugify(self.title) exists = Quiz.objects.filter(slug=slug).exists() if exists: slug += f'-{str(int(time()))}' self.slug = slug super().save(*args, **kwargs) for_slug.py from django.template.defaultfilters import slugify as django_slugify alphabet = { 'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo', 'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'j', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'kh', 'ц': 'ts', 'ч': 'ch', 'ш': 'sh', 'щ': 'shch', 'ы': 'i', 'э': 'e', 'ю': 'yu', 'я': 'ya' } def slugify(s): return django_slugify(''.join(alphabet.get(w, w) for w in s.lower())) If it matters I use PostgreSQL. Why it happens? -
Django Getting Connection refused Error When Creating PDF Using xhtml2pdf
I have deployed a Django app in digitalocean and I getting this error when creating PDF file using xhtml2pdf. In my local environment everything works OK, no errors at all. In anyone has ideas about how to solve, please share those. Thanks in advance [Errno 111] Connection refused Request Method: GET Request URL: Django Version: 2.2.7 Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connection refused Exception Location: /usr/lib/python3.7/socket.py in create_connection, line 716 Python Executable: /home/eslcrm/bin/python3.7 Python Version: 3.7.6 -
How to fix django settings rest_flex_fields import error?
I have a django app deployed in a docker container and I used drf-flex-fields for performing ?expand on my serializer. I'm looking to enable query optimization as you can see here I updated my settings.py with: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ( 'rest_flex_fields.filter_backends.FlexFieldsFilterBackend', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'PAGE_SIZE': None } In requirements.txt, I included: drf-flex-fields==0.7.5 But when I run docker-compose build and docker-compose up on my app, I get the following error: app_1 | ImportError: Could not import 'rest_flex_fields.filter_backends.FlexFieldsFilterBackend' for API setting 'DEFAULT_FILTER_BACKENDS'. ImportError: cannot import name 'GenericViewSet'. -
Ignoring Django Migrations in pyproject.toml file for Black formatter
I just got Black and Pre-Commit set up for my Django repository. I used the default config for Black from the tutorial I followed and it's been working great, but I am having trouble excluding my migrations files from it. Here is the default configuration I've been using: pyproject.toml [tool.black] line-length = 79 include = '\.pyi?$' exclude = ''' /( \.git | \.hg | \.mypy_cache | \.tox | \.venv | _build | buck-out | build | dist )/ ''' I used Regex101.com to make sure that ^.*\b(migrations)\b.*$ matched apps/examples/migrations/test.py. [tool.black] line-length = 79 include = '\.pyi?$' exclude = ''' /( \.git | \.hg | \.mypy_cache | \.tox | \.venv | _build | buck-out | build | dist | ^.*\b(migrations)\b.*$ )/ ''' When I add that regex line to my config file, and run pre-commit run --all-files, it ignores the .git folder but still formats the migrations files. -
Django OperationalError: no such column
I'm trying to read values from an sqlite db I added to my Django project but it doesn't work. I did a test in the Python shell and all it returned was the following error when I tried looking into the data (I entered 'from myapp.models import my_data' followed by 'my_data.objects.all()'): OperationalError: no such column: my_table_name.id This is how my models.py file looks like: class my_data(models.Model): status = models.TextField(db_column='STATUS', blank=True, null=True) name_1 = models.TextField(db_column='NAME_1', blank=True, null=True) name_2 = models.TextField(db_column='NAME_2', blank=True, null=True) dep = models.IntegerField(db_column='DEP', blank=True, null=True) name_reg = models.TextField(db_column='NAME_REG', blank=True, null=True) reg = models.IntegerField(db_column='REG', blank=True, null=True) name_com = models.TextField(db_column='NAME_COM', blank=True, null=True) avgp = models.IntegerField(db_column='AVGP', blank=True, null=True) class Meta: managed = True db_table = 'my_table_name' My settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'my_table_name': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db_my_table_name.sqlite3'), } } Also, I performed the 'python manage.py makemigrations' and 'python manage.py migrate' commands. Any idea what I am doing wrong? -
Test discovery fails using DRF APITestCase but not django's TestCase
Using Django Rest Framework's APITestCase class, Visual Studio Code does not discover my unittest tests. I've configured vscode to use unittest and given it the path to my django app. I have toggled between jedi and ms's language server for python. I can run the tests manually, using python manage.py test. If I switch to using Django's provided django.test.TestCase, vscode discovers the tests and creates the adornments. I have also tried rest_framework's two other test cases: APISimpleTestCase, APITransactionTestCase and neither worked. My test class is very simple, essentially the following: from django.test import TestCase # * cannot get vscode to discover tests with this from rest_framework.test import APITestCase service_path = "/api/v0.1/service" # class PathLookupTests(TestCase): class PathLookupTests(APISimpleTestCase): def test_responding(self): uri = "valid_uri" resp = self.client.get(f"{service_path}/?uri={uri}") self.assertEqual(resp.status_code, 200) In the Python Test Log I saw the following traceback once, but cannot repeat it: File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 1123, in setUpClass super().setUpClass() File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 197, in setUpClass cls._add_databases_failures() File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 218, in _add_databases_failures cls.databases = cls._validate_databases() File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 204, in _validate_databases if alias not in connections: TypeError: argument of type 'ConnectionHandler' is not iterable -
How to allow users In Django to see specific data from same model
I am facing a problem while giving permission to admin users in Django that how to restrict users to see only user specific data from same model. I mean that if 2 user can add data to same model, then how to restrict them to access only that data. -
How to Make Multi Databases in Python Django
What I mean is how to insert a model into another model in Python Django So I am working on a simple project of an online school. we have classes, and in the classes we have subjects and in the subjects we got lessons so how to make a model in python django to add subjects to an individual class only. and add lessons to individual subject in a specific class, this is it, hope understand me well, thanks. -
Nginx and Gunicorn doesn't work (with Django 2.2.4)
I installed and configured Django 2.2.4 with MySQL, Nginx and Gunicorn, it works locally but at the time of seeing it on the web, the page is not visible, I already checked the terminal and there is no error, there is no error in the console of the browser, I used this documentation to configure Nginx and Gunicorn. https://platzi.com/tutoriales/1318-django/3302-instalar-un-proyecto-de-django-en-un-servidor-centos/ This is the image that my server runs the local server but when I deactivate "runserver" it is not published https://drive.google.com/file/d/1NgpapxTuU5VkHgvIqw8I76mg5-3mCGwb/view -
How to use django orm in not django-project?
I have a project with structure like that: . ├── app │ ├── data │ │ ├── ... │ │ └── orm │ │ ├── app_1 │ │ ├── app_2 │ │ ├── ... │ │ └── orm │ │ ├── ... │ │ └── settings.py │ └── ... ├── ... └── main.py I want use django orm in my project but i want to have simple way to change Django ORM to any other ORM. Accordingly that i want isolate django project inside my main project. I have some class app.data...DataController which use Models in any cases. And code in main.py use DataController to get or load data from DB, other code works already with data but not with Models directly. To achieve this I wrote this code in app.data.__init__.py: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.data.orm.orm.settings") import django from django.conf import settings django.setup() Also if i paste that code anywhere else, in main.py for example, that's does not working, django says ImproperlyConfigured: Requested setting INSTALLED_APPS. And then in settings.py i was change dotted pathes to apps like that 'app_1' -> 'app.data.orm.app_1'. But for now i can't use django-commands from manage.py not from project root directory nor from app/data/orm. First, project root … -
Django prompt :A server error occurred. Please contact the administrator
I have tried everything I can find, and it has been 6 hours. I have nothing, I just created a django project, and the first time I run, I get an error. I've tried both, reinstall django, python 'encoding format, file encoding format. I am frustrated, please help me.enter image description here -
django admin: how to deal with broken foreign keys in unmanaged table?
I have unmanaged model which looks like this: class Foo(models.Model): parent = models.ForeignKey('Foo', on_delete=models.SET_DEFAULT, default=0) name = models.CharField(max_length=128) class Meta: managed = False db_table = 'foo' Previous developer decided to do a strange thing: add parent_id field which can be either ID of existing Foo row/instance or 0 (instead of just making field nullable). Foo with ID 0 doesn't exist. When I try to display this model in admin panel django doesn't complain: @admin.register(Foo) class FooAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'parent') What django does is just skipping foo's with parent_id == 0. Without parent in list_display all objects will be displayed. When I run something like Foo.objects.filter(parent_id=0) it returns 0 objects, but I know for sure that there are plenty of them in the database. Foo.objects.all() will return only objects with non-zero parent ids. So how should I deal with situation like this (aside from making database migration which might potentially break existing frontend which is not related to django but speaks to existing database)? Or at least how to make model manager return all objects and not just Foo instances with non-zero parent_id? First think that come in mind is to use another model field: parent_id = models.IntegerField(default=0) -
Django - update individual fields of a model
Im working on a django project and I have a user model and each user has a UserProfile. I want to implement a form so that a user can update his profile picture. This is what I have so far: views.py def update_image(request,username): response_data = {} if request.method == 'POST': image = request.POST.get('image') response_data['image'] = image UserProfile.objects.create( image = image ) return JsonResponse(response_data) context = { 'image':image } return render(request, 'userprofile.html', context) forms.py class ProfileUpdateForm(forms.Form): image = forms.ImageField(required=False,label='image') def clean(self): blocked_chars = set(punctuation) cleaned_data = super(ProfileUpdateForm, self).clean() image = cleaned_data.get('image') filename, file_extension = os.path.splitext(image) if not ".jpg" or '.png' in file_extension: raise forms.ValidationError(filename + 'is not an image') return image urls.py url(r'^(?P<username>[\w-]+)/update-image/$', update_image, name='update_image'), index.html <form id="profile_form" class="profile_form" method='POST' enctype="multipart/form-data" form_data="{{ request.user.profile.get_update_image_url }}"> {% csrf_token %} <div class="profile_form_group"> <div class="profile_table"> <div class="utable_row"> <div class="utable_th_1"> <span class="user_detail"> {{ form }}</span> </div> <div class="utable_th_2"> <span class="user_detail"> <input class='profile_img_btn' type="submit" value="Update Image"/> </span> </div> </div> </div> </div> </form> main.js var i_link = $('.profile_form').attr('form_data'); console.log(i_link) $(document).on('submit', '#profile_form',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: i_link, data:{ image :$('#id_image').val(), csrfmiddlewaretoken :$('input[name=csrfmiddlewaretoken]').val(), action : 'post' }, success:function(json,data,i_link){ console.log("HEY, THIS IS WORKING !" + data + i_link) document.getElementById("profile_form").reset(); }, error : function(xhr,errmsg,err) { console.log("HEY, THIS IS NOT WORKING !") …