Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Coordinates intersecting with bounding box after forcing right hand rule
I am trying to query for locations within a bounding box. The bounding box of the country Russia renders east-to-west, covering basically all of Canada and none of Russia (which is obviously incorrect) and returns cities in Canada, Poland, and Slovakia. I used ForceRHR (Django 1.11) and ForcePolygonCW (Django 2.2) to force the right-hand-rule, and it appears to order the bounding box coordinates properly, but I get the same query results for the regular bounding box and the RHR bounding box. Here are the relevant fields in the Location model... from django.contrib.gis.db import models as gis_models point = gis_models.PointField(blank=True, null=True, geography=True) bounding_box = gis_models.PolygonField(blank=True, null=True) And here's what I've tried... from locations.models import Location from django.contrib.gis.db.models.functions import ForceRHR, ForcePolygonCW russia = Location.objects.annotate(rhr=ForcePolygonCW('bounding_box')).get(pk=1646) print(russia.bounding_box) in_russia = Location.objects.filter(point__intersects=russia.bounding_box) print(in_russia) print(russia.rhr) in_russia2 = Location.objects.filter(point__intersects=russia.rhr) print(in_russia2) Here are the results of the code above: SRID=4326;POLYGON ((19.638861 41.185902, 19.638861 81.856903, -168.997849 81.856903, -168.997849 41.185902, 19.638861 41.185902)) <QuerySet [<Topic: 00-001 Warsaw, Poland>, <Topic: 048 01 Rožňava, Slovakia>, <Topic: 053 51 Richnava, Slovakia>, <Topic: 50.2112, -170.2624>, <Topic: 50.9566, -170.7638>, <Topic: 51.5734, -170.2439>, <Topic: 51.7759, -169.4604>, <Topic: 51.8281, -170.4743>, <Topic: 51.9097, -170.0422>, <Topic: 51.9108, -169.5701>, <Topic: 51.9771, -169.6288>, <Topic: 51.9782, -169.3368>, <Topic: 52.0036, -170.8657>, <Topic: 52.0231, -170.4362>, <Topic: … -
Differences between get_by_id() vs objects.get() vs objects.filter()
I'm just looking to see what the differences are between: obj = ClassModel.get_by_id(object_id) obj = ClassModel.objects.get(object_id) obj = ClassModel.objects.filter(pk=object_id) Obviously the first one is more concise, but I didn't find a good resource about it, and I'm not sure if I should use it throughout my code. In addition, what are the consequences of using the first option over the second option? Is it safe to use it or is it going to add code debt to my code? I'm in Django 1.11, but looking to migrate to Django 2 within the next months. -
date_facet in Django Haystack not faceting by date
I'm using Haystack 2.8.1 with Django 2.1 and Solr 6.6.6. I have no problems using facets, however date faceting is not working. My index: class ConflitoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) data_inicio = indexes.DateField(model_attr="data_inicio", faceted=True, null=True) def get_model(self): return Conflito def index_queryset(self, using=None): return self.get_model().objects.all() The following script on shell: from haystack.query import SearchQuerySet import datetime sqs = SearchQuerySet().date_facet("data_inicio", start_date=datetime.date(1980, 1, 1), end_date=datetime.date(2019, 1, 1), gap_by="year") results in: In [1]: sqs.facet_counts() Out[1]: {'fields': {}, 'dates': {}, 'queries': {}} However, the following script results in: In [1]: from haystack.query import SearchQuerySet In [2]: import datetime In [3]: sqs = SearchQuerySet().facet('data_inicio') In [4]: sqs.facet_counts() Out[4]: {'fields': {'data_inicio': [('1500-01-01T00:00:00Z', 212), ('1986-12-29T00:00:00Z', 148), ('2010-01-01T00:00:00Z', 141), ('1979-12-29T00:00:00Z', 130), ('2018-01-01T00:00:00Z', 104), ('1984-12-29T00:00:00Z', 100), ... ('2013-10-16T00:00:00Z', 17), ('1982-12-02T00:00:00Z', 16), ('1988-02-28T00:00:00Z', 16), ('1996-05-29T00:00:00Z', 16), ('1998-03-29T00:00:00Z', 16), ('2000-01-31T00:00:00Z', 16)]}, 'dates': {}, 'queries': {}} Thus, faceting is not working for dates. What can be wrong in my code? Unfortunately there are very few examples for date faceting in Haystack documentation. best, alan -
REST API serializer doesn't return Primary Key (PK)
I am setting up React-native app that talks to Django REST API using Axios. My problem is that I can't get primary key from the database via API in to the React-native app. I want to build a list that users can tap on and do something with it in next step, so I would like to have the PK of the chosen object. I have following Viewset: class PermitViewSet(viewsets.ModelViewSet): serializer_class = PermissionSerializer queryset = Permit.objects.all() def get_queryset(self): return Permit.objects.filter(user=self.request.user).values('permit_id','work_place_name','valid_to_date')[:2] and when I print the result in the console, I see the primary key: <QuerySet [{'permit_id': 100, 'work_place_name': 'mjest', 'valid_to_date': datetime.datetime(2019, 9, 29, 23, 0, tzinfo=<UTC>) When I try to get this response using Postman or in my React-native app using axios, there is no PK: permit_id -
Filter by Django EncryptedCharField
I'm using the cryptographic_fields.fields library to encrypt some of my fields, more specifically the customer's routing number. Here is how my model.py looks like: class Account(models.Model): account_number = EncryptedCharField(max_length=20, null=True, blank=True) I'm looking to see if it's possible to filter by this field. Account.objects.filter(account_number='123') Of course, this is going to return an empty queryset because there is definitely not an account number with the values 123 because it has already been encrypted (encoded). Is there a way of doing this. I was looking at the source code, and tried encoding the string and searching with the new encode value. from cryptographic_fields.fields import get_crypter CRYPTER = get_crypter() account_number = CRYPTER.encrypt('123'.encode('utf-8')) Account.objects.filter(account_number=account_number) But this doesn't work as it seems the CRYPTER products a new different encrypted value every time I use it. My ultimate goal is to be able to check if an account_number has been used in other accounts already. -
Django , how to use annonation for minus two model
How to find the total sum of the two Field using minus. class Car(models.Model): name = models.CharField(max_length=255) class Supplier(models.Model): name = models.CharField(max_length=255) class Buyer(models.Model): name = models.CharField(max_length=255) class Car(models.Model): name = models.CharField(max_length=255) class Buy(models.Model): car= models.ForeignKey(Car, on_delete=models.CASCADE) Supplier= models.ForeignKey(Supplier, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Sell(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def order(request): cars = Car.objects.filter() buy = Car.objects.filter().annotate(totals=(Sum('buy__quantity'))) sell = Car.objects.filter().annotate(total=(Sum('sell__quantity'))) total = Car.objects.annotate(tota=Sum(F('buy__quantity')-F('sell__quantity'))) #does work when i add the same car to another buyer when I multiply work fine. total = Car.objects.annotate(tota=Sum(F('buy__quantity')*F('sell__quantity'))) Total sum of the two Field using minus. when I add a to (Model Buy: car = quantity 4) and in the - (Model Sell : car = quantity 2) work fine (value = 2), but when I go to add the same car for another Buyer on the (model Sell: car = quantity 2) give the wrong (value = 4) not 0 -
Django: Could not parse the remainder: '{{' from '{{
when i execute my HTML Code, it gives me the following error: Could not parse the remainder: '{{' from '{{ I tried to nest the conditions too, but I am an absolute beginner in HTML so I wanted to get this version at least correct, but it is not working... {% block content %} <p align="justify"> So far you donated {{ donated_trees }} Tree(s). </p> {% if treatmentgroup == 'two' or treatmentgroup == 'three' %} Your current position is {{ player.end_position }} of {{ anzahlspieler }} for the most donated trees. {% endif %} {% if treatmentgroup == 'two' or treatmentgroup == 'three' and {{ player.rival }} == 0 %} <P> No other player has the same.</P> {% endif %} {% if treatmentgroup == 'two' or treatmentgroup == 'three' and {{ player.rival }} == 1 %} <P> One other player has the same.</P> {% endif %} {% if treatmentgroup == 'two' or treatmentgroup == 'three' and {{ player.rival }} > 1 %} <P> {{ player.rival }} other players have the same.</P> {% endif %} The error occurs from line 8 on -
Anonymous user encountered while accessing rest-api with simplejwt
I am able to obtain access and refresh token using SimpleJWT. I have a custom decorator which tries to identify type of user from user profile. Code fails here because it can not find authenticated user. I have repeatedly tried to get user via debug mode in VS Code but not successful. Here is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', # Add this line 'rest_auth', # Add this line 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', # we will not be using this but not keeping this entry results in error while deleting user. A known issue https://github.com/Tivix/django-rest-auth/issues/412 'crispy_forms', 'users', ] 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', ] AUTH_USER_MODEL = 'users.User' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } REST_USE_JWT = True ''' #https://www.techiediaries.com/django-rest-framework-jwt-tutorial/ JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_RESPONSE_PAYLOAD_HANDLER': 'custom_jwt.jwt_response_payload_handler', # 'JWT_PAYLOAD_HANDLER': 'custom_jwt.jwt_payload_handler', # 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300) } ''' SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' SITE_ID = 1 Here is … -
Instance of 'ImageField' has no 'save' member - working with PIL and Django
I am attempting to put a qrcode into the image field of my model. I saw this answer: Save a generated PIL image into an ImageField in django and tried to recreate it, but I encountered the following error: Instance of 'ImageField' has no 'save' member pylint(no-member) Any ideas as to why? class Customer(models.Model): user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() number_of_guests = models.PositiveIntegerField() url_link = models.CharField(max_length=200) qr_image = models.ImageField(upload_to='qrcodes', default='default.jpg', blank=True, null=True) def __str__(self): return (self.first_name + " " + self.last_name + " " + str(self.user_id)) def save(self, *args, **kwargs): self.url_link = "http://127.0.0.1:8000/" + str(self.user_id) qrcode_img = qrcode.make('some data') canvas = Image.new('RGB', (500, 500), 'black') canvas.paste(qrcode_img) blob=BytesIO() canvas.save(blob, 'JPEG') self.qr_image.save('qrcode-filename.jpg', File(blob), save=False) super().save(*args, **kwargs) -
Issue setting up celery/redis in docker/django
Here is my current setup: requirements.txt celery[redis] Dockerfile RUN curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash ENV PATH "/home/appuser/.pyenv/bin:$PATH" RUN echo "export PATH=/home/appuser/.pyenv/bin:$PATH" >> /home/appuser/.bashrc RUN echo 'eval "$(pyenv init -)"' >> /home/appuser/.bashrc RUN echo 'eval "$(pyenv virtualenv-init -)"' >> /home/appuser/.bashrc RUN pyenv install 3.7.0 RUN pyenv global 3.7.0 ENV PATH "/home/appuser/.pyenv/versions/3.7.0/bin:$PATH" WORKDIR /code COPY ./back-python/project/requirements.txt /code/ RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt project/settings CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' projects/init.py from .celery import app as celery_app __all__ = ['celery_app'] projects/celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) docker-compose.yml version: '3' services: ui: build: ./front-vue/. volumes: - ./front-vue/:/code ports: - "8888:8888" links: - django command: "npm run dev" redis: restart: always image: "redis:alpine" sysctls: - net.core.somaxconn=511 django: build: . volumes: - ./back-python/project/:/code - ./front-vue/dist/pwa/:/code/public expose: - "8000" command: "python manage.py runserver [::]:8000" depends_on: - redis celery: build: . command: celery -A project worker -l info volumes: - ./back-python/project/:/code depends_on: - redis When I run docker-compose up, I keep getting this error celery_1 | Traceback (most recent call last): celery_1 | File "/home/appuser/.pyenv/versions/3.7.0/bin/celery", line 11, in <module> celery_1 … -
request.session isn't saved or is somehow modified
It seems that my request.session isn't saved or is somehow modified in other ways, despite using request.session.modified = True after changing the value. Here is the debug output: This should run first. This should run second. I have set main category to 2 (Shoes) Main category is 1 (Books) The code below should display a different ModelForm based on selected category, however when I select, for instance, Books, ShoesModelForm is displayed and vice-versa. This currently works as follows: whenever a value in a combobox is changed, two AJAX requests are fired. First one calls a view (load_categories) that renders another if a category has children, otherwise returns an HttpResponse which stops attaching the listener. Second one calls a view (load_modelform) that renders a specific ModelForm if selected category is root node (main category). mappings = { '1': BookProductForm, '2': ShoesProductForm } def load_categories(request): print("This should run first.") category_id = request.GET.get('category') request.session['category'] = category_id request.session.modified = True if Category.objects.get(id=category_id).is_root_node(): request.session['main_category'] = category_id request.session.modified = True print(f"I have set main category to {request.session['main_category']} ({Category.objects.get(id=category_id).name})") subcategories = Category.objects.get(id=category_id).get_children() if subcategories: return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories}) return HttpResponse('leaf_node') def load_modelform(request): print("This should run second.") main_category = request.session['main_category'] print(f"Main category is {main_category} ({Category.objects.get(id=main_category).name})") form = … -
Configure Python to Complex Django Project
I need to configure pytest in my django application. But the structure of the directories is different of what I'm used to. . ├── apps │ ├── __pycache__ │ ├── admcore │ ├── ... │ ├── cauth │ ├── webservice │ └── webshell ├── doc │ └── ... ├── lib │ └── ... ├── ... └── project ├── __init__.py ├── globalsettings.py ├── local │ ├── __init__.py │ ├── app.uwsgi │ ├── manage.py │ ├── settings.py │ └── wsgi.py ├── mailconf.py └── urls.py I created pytest.ini [pytest] DJANGO_SETTINGS_MODULE=sgp.local.test_settings addopts = --nomigrations --cov=. --cov-report=html and test_settings.py files #!/usr/bin/env python import os import sys from project import globalsettings SECRET_KEY = "12341234AFDQFDQSDFAZR123D" ROOT_PATH = '/usr/local/sgp' BASEURL_ROOT = '' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } } And I put the two files in project directory. . ├── apps │ ├── __pycache__ │ ├── admcore │ ├── ... │ ├── cauth │ ├── webservice │ └── webshell ├── doc │ └── ... ├── lib │ └── ... ├── ... └── project ├── __init__.py ├── globalsettings.py ├── local │ ├── __init__.py │ ├── app.uwsgi │ ├── manage.py │ ├── pytest.ini │ ├── settings.py │ ├── test_settings.py │ └── wsgi.py ├── mailconf.py └── urls.py … -
how can install virtual environment in multiple folder before install django
i install virtual environment in my folder for my web app now i want to install virtual environment in other folder for my other app but it not install virtual env it shows Requirement already satisfied: virtualenv in c:\users\DEll\appdata\local\programs\python\python37-32\lib\site-packages (16.7.5) How can fix this and install -
when i was using PUT method in postman through Basic Auth i got an error ,i was working on django rest-framework
{ "detail":"Unsupported media type \"text/plain\" in request." this image is from postman} -
Django best practices for creating private user groups
I'm creating a group app and I want it to be invitation only, but I'm wondering if there's a better way to do this. This setup works fine, but if anyone sees any issues I might run into please let me know. I've included the models and the views related to invitations, this should give you a good idea of my thought process here. models.py Account = get_user_model() class FriendGroup(models.Model): owner = models.ForeignKey( Account, on_delete=models.SET_NULL, related_name="group_owner", null=True) name = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) administrators = models.ManyToManyField( Account, related_name="group_admin") members = models.ManyToManyField(Account, related_name="group_member") thumbnail = models.ImageField(upload_to='images/groups/', blank=True) image_lg = models.ImageField(upload_to='images/groups/', blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class GroupInvite(models.Model): group = models.ForeignKey( FriendGroup, on_delete=models.CASCADE, related_name="invite") sender = models.ForeignKey( Account, on_delete=models.CASCADE, related_name="sent_by") invitee = models.ForeignKey( Account, on_delete=models.CASCADE, related_name="invitee") def __str__(self): return "Join " + self.group.name views.py class SendGroupInvitesView(APIView): def post(self, request, pk, format=None): group = FriendGroup.objects.filter(id=pk) invitees = request.data.get('invitees') if group.exists(): if request.user in group[0].members.all(): if invitees: for invitee in invitees: account = Account.objects.filter(id=invitee) if account.exists(): invite = GroupInvite.objects.create( group=group[0], sender=request.user, invitee=account[0]) invite.save() return Response({'success': 'Invites sent.'}, status=status.HTTP_201_CREATED) return Response({'error': 'You must invite at least one friend.'}, status=status.HTTP_400_BAD_REQUEST) return Response({'error': 'Group does not exist.'}, status=status.HTTP_400_BAD_REQUEST) class AcceptGroupInviteView(APIView): def post(self, request, … -
How to handle KeyError in HTTP response when grabbing data (using Django requests)
I try to make API requests to fetch data from a third party API to manipulate/render the data into my dashboard. Including the responsed data everything runs well so far, but it seems something is wrong with the dictionary/keys within the json api data. In particular I would like to grab the values of the keys 'name' and 'country' which are correctly fetched via the http response according to the Django debug. I always end up with a KeyError as shown below. What do I miss here? (I am not sure if this is important, but my linter tells me that json is imported but unused within the views.py) This is the response: 'name': team_data['name'], … ▼ Local vars Variable Value request <WSGIRequest: GET '/dashboard/'> response <Response [200]> team_data 'WARNING': 'THIS IS A DEMO AND DOES NOT REPRESENT THE ENTIRE API. THE ' 'DATA IS LIMITED AND NOT UP TO DATE AND SERVES ONLY AS AN ' 'EXAMPLE. FOR PRODUCTION ENVIRONEMENT USE : ' 'HTTPS://API-FOOTBALL-V1.P.RAPIDAPI.COM/V2/', 'results': 1, 'teams': [{'code': None, 'country': 'Brazil', 'founded': 1909, 'logo': 'Not available in Demo', 'name': 'Internacional', 'team_id': 33, 'venue_address': 'Avenida Padre Cacique 891, Bairro Menino ' 'Deus', 'venue_capacity': 50128, 'venue_city': 'Porto Alegre, Rio Grande do … -
AttributeError: module 'calc.views' has no attribute 'home'
I know there are some questions asked already but none of worked for me server is not running with the command throwing this error calc urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home') ] calc views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Hello World !") saish urls.py from django.contrib import admin from django.urls import path , include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ] -
Django: Same model with different features?
Object Model: class Object(models.Model): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) category = models.ForeignKey(Category, on_delete=models.CASCADE) address = models.CharField(max_length=300) content = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" Category model: class Category(models.Model): title = models.CharField(max_length=50) def __str__(self): return f"{self.title}" For example I have some categories, like hotels, restaurants etc. So I want for each category to have different features (radio buttons when adding new), but I'm not sure, how to handle it properly. Hotels must have rooms, pool etc. Restaurants must have country kitchen, seats etc. In future I will have and other categories. Quesion is: Which is the best way (practice) to do this. My solution: To create third table with features and every category to have column features and store features separate by comma, but it's not very good solution based on DB normalization. -
How fix ImportError: cannot import name '_mysql' in Django 2.2.5
I'm Deploying a Django Application on an AWS instance (amazon2 64-bit, Linux/4.14.128-112.105.amzn2.x86_64). I spent a lot of time looking and searching in stack overflow without finding a solution. My problem: correctly install mysqlclient. The error: mod_wsgi (pid=14418): Failed to exec Python script file '/var/www/html/project_x/project_x/wsgi.py'. mod_wsgi (pid=14418): Exception occurred processing WSGI script '/var/www/html/project_x/project_x/wsgi.py'. Traceback (most recent call last): File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: cannot import name '_mysql' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/html/project_x/project_x/wsgi.py", line 17, in <module> application = get_wsgi_application() File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager … -
django 2.1 how to fetch value from db and assign it to foreign key
i am new to python django, i found it a bit challenging to fetch data from database and assign it to foreign key. i am using a postgres database. model: class Company (models.Model): author = models.ForeignKey ( User , on_delete = models.CASCADE ) comapny_name = models.CharField ( max_length = 32 , null = False , blank = False ) class owner (models.Model): company = models.ForeignKey ( Company, on_delete = models.CASCADE ) owner_name = models.CharField ( max_length = 32 , null = False , blank = False ) how should i go about it as i dont want to pass the value of FK through URl instead i want to query the value and assign it during form processing. Each User is allowed to create one company only so i want to assign comoany_name which is related to the user that h created the company name and assign it to the FK. views: def ownerform (request): q = Company.objects.all() if request.method == 'POST' : form = businessmodelform ( request.POST ) if form.is_valid ( ) : instance = form.save ( commit = False ) instance.company_id = q.id instance.save ( ) return redirect ( 'str_dashboard' ) else : form = businessmodelform ( ) … -
Template tag as filter value in Django
I have defined one custom tag which is working fine in templates. Like -- {% get_setting "DATE_FORMAT_UI" %} Above statement is returning correct value in template. Now i want to use the same in a filter like this - {{extra_info.to_date|date: '{% get_setting "DATE_FORMAT_UI" %}' }} But this is giving error. I tried in different ways of using quotes for the {% get_setting "DATE_FORMAT_UI" %} But every time bad luck. So could any body help me in solving this. I want to pass date format in filter . That date format is saved into config file. but how to pass that value dynamically in filter. -
How to get the list of columns in a Django Queryset?
I have a code that creates multiple complicated querysets from different tables, using lots of annotations, etc... The code is then joining those querysets using union. Each of those querysets by itself seems to be fine. Calling print(len(qset)) works for each of them. But after combined_qset = qset1.union(qset2), I get the following error: django.db.utils.ProgrammingError: each UNION query must have the same number of columns LINE 1: ..., '') AS "owner" FROM "t1") UNION (SELECT "field_x... ^ When I look at the code, I count the number of fields in .only(...) and .values(...) calls, count the numbers of annotations, etc, it seems that all those querysets have exactly the same number of columns. The error message shows just a tiny little part of the SQL generated (see above), so it's not really helpful. Is there a simple way to get the list of columns of a queryset, so I can find the discrepancy and fix it? -
.png image doesn't show in html template email through django
I made a django website that sends an email after a form has been filled out – the email contains a png image made through django qrcode. Even though the other elements of the html template is shown in the email, the qr code isn't visible. How can I solve this problem? I am doing this all on a local server if that is relevant. Email template: {% extends "event/base.html" %} {% load qr_code %} {% block content %} {% qr_from_text the_user.url_link size="M" image_format="png" %} <h2>cwecmccev</h2> {% endblock content%} Views: def buy(request): if request.method=='POST': form=forms.Purchase(request.POST) if form.is_valid(): form.save() name=form.cleaned_data.get('first_name') + form.cleaned_data.get('last_name') messages.success(request, f'Payment completed for {name}') subject, from_email, to = 'Subject Test', 'tasselsas@gmail.com', form.cleaned_data.get('email') html_content = render_to_string('tickets/mail_template.html', {'varname':'value'}) text_content = 'ereijfij' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return redirect('thankyou') else: form=forms.Purchase() return render(request, 'tickets/buy.html', {'form': form}) Thanks in advance! -
Redirect from .com/ to just .com
I have a web page served by Django, and i want to make it to 301 redirect from mysite.com/ to mysite.com without a slash on the end. Is it possible to do with Django? Last version of Django, python 3.6. path("", views.home, name="main_page") -
Should I learn flask before i learn Django? [on hold]
I am new to backend web development and am starting with django but should I start with flask instead? I am resorting to these two options as I know python quite well.