Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django API permission decorator
Objective: I want to allow some endpoint only to users with specifics permission. For exemple to call the endpoint that allow the creation of users you need the permission "user.create" Problem: I tried to create a middle ware to use it with decorator_from_middleware_with_args class PermissionMiddleware: def __init__(self, view,permission): self.permission = permission def process_request(self, request): if not request.user.has_perm(permission_name): if raise_exception: raise exceptions.PermissionDenied("Don't have permission") return False return True Then inside my views i use the decorator_from_middleware_with_args class UtilisateurViewSet(viewsets.ViewSet): permission = decorator_from_middleware_with_args(PermissionMiddleware) @permission('view_utilisateur') def list(self, request): queryset = Utilisateur.objects.all() serializer = UtilisateurSerializer(queryset, many=True) return Response(serializer.data) But there is an error when i call the endpoint: AttributeError: 'UtilisateurViewSet' object has no attribute 'user' I think it's because the django.contrib.sessions.middleware.SessionMiddleware is not executed yet. Is there a way to define the order of the middlewares, or an other way to achieve what a want ? -
Celery Django Body Encoding
Hi does anyone know how the body of a celery json is encoded before it is entered in the queue cache (i use Redis in my case). {'body': 'W1sic2hhd25AdWJ4LnBoIiwge31dLCB7fSwgeyJjYWxsYmFja3MiOiBudWxsLCAiZXJyYmFja3MiOiBudWxsLCAiY2hhaW4iOiBudWxsLCAiY2hvcmQiOiBudWxsfV0=', 'content-encoding': 'utf-8', 'content-type': 'application/json', 'headers': {'lang': 'py', 'task': 'export_users', 'id': '6e506f75-628e-4aa1-9703-c0185c8b3aaa', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '6e506f75-628e-4aa1-9703-c0185c8b3aaa', 'parent_id': None, 'argsrepr': "('<email@example.com>', {})", 'kwargsrepr': '{}', 'origin': 'gen187209@ubuntu'}, 'properties': {'correlation_id': '6e506f75-628e-4aa1-9703-c0185c8b3aaa', 'reply_to': '403f7314-384a-30a3-a518-65911b7cba5c', 'delivery_mode': 2, 'delivery_info': {'exchange': '', 'routing_key': 'celery'}, 'priority': 0, 'body_encoding': 'base64', 'delivery_tag': 'dad6b5d3-c667-473e-a62c-0881a7349684'}} -
Rewriting windowing raw sql into django ORM
I have raw query, which I need to rewrite into django ORM. Lets say we have model like this: class exampleModel(models.Model): value1 = models.BigIntegerField(primary_key=True) value2 = models.CharField(max_length=255, blank=True, null=True) value3 = models.CharField(max_length=255, blank=True, null=True) value4 = models.CharField(max_length=255, blank=True, null=True) I want to compare filter of this model with number of occurences of primary key named value1 in other tables, is there any way to do it in django orm? Here is raw query I have as an example, I need to rewrite it into ORM. Thank you raw_query=f"SELECT value1,value2,value3,value4 (SELECT COUNT(*) FROM exampleTable2 l WHERE o.value1 = l.value1) AS count_occurences_table2, (SELECT COUNT(*) FROM exampleTable3 l WHERE o.value1 = l.value1 ) AS count_occurences_table3, FROM exampleModel o WHERE name LIKE '%example%' OR address LIKE '%example%'" Essentially what it does is that it writes back parameters from first table and checks for primary key occurence in other tables and sends back count of these occurences in other tables of each line in exampleTable.. -
Django: How to display Multiple Models in a single view through function approach?
what I want to execute that all my three models will be displayed through one view by a function approach. The fields I want to display in All fields of Cylinder Entry ,issue date(if exists) ,userName,Return date(if exists) (of that particular cylinderId) Eg: cylinderId | date | type | status |availability| issuedate | userName | returndate | 1 11/11 co2 fill available 12/11(if exists) xyz 13/11(if exists) Sorry for this messy table. but unable to write the logic please help me out here is my models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) super().save(*args,**kwargs) def __str__(self): return str(self.userName) class ReturnCylinder(models.Model): fill=[ ('Fill','fill'), ('Empty','empty'), ('refill','Refill') ] ava=[ ('yes','YES'), ('no','NO') ] cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE,unique=True) user_return=models.ForeignKey('IssueCylinder',on_delete=models.CASCADE) returnDate=models.DateTimeField(default=timezone.now) status=models.CharField(max_length=10,choices=fill) availability=models.CharField(max_length=20,choices=ava) def save(self,*args,**kwargs): if not self.pk: if self.availability=='YES' or self.availability=='yes': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Available') else: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Unavailable') if self.status=='refill' or self.status=='Refill': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Refill') super().save(*args,**kwargs) def __str__(self): return self.cylinder -
Why is it called signals.py and not receivers.py in Django?
I am aware that Django itself has not defined any guideline about where should the signal receivers live inside an app. But, in the online community, I have seen a general practice (Based on stackoverflow answers and various tutorials) to define a signals.py inside the app direcotry. What confuses me is that why should it be called signals.py and not receivers.py as we are defining receivers/listners there not signals. Please help me understand. -
Passing Django logged-in user information to Dash app
Is possible to pass the currently logged in user full name/group etc. into a Dash app created in Django? Assume you have a simple Dash table integrated into Django: import dash from dash.dependencies import Input, Output, State import dash_table import dash_core_components as dcc import dash_html_components as html import pandas as pd from django_plotly_dash import DjangoDash df = pd.read_csv('...') app = dash.Dash(__name__) app.layout = dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), ) if __name__ == '__main__': app.run_server(debug=True) [...] and assume you for instance want to pass the logged in name into the data table. How can this be done? For example, "name = request.user.get_full_name" or some type of similar statement does not work (of my knowledge). Thanks! -
Hello guys so when i clikc on django title i get django post and when i click on javascript title i get django post ether
when i clikc on django title i get django post and when i click on javascript title i get django post ether am not using any frame_work and this my blog page i really try every solution i know but Unfortunately nothing happend blog.html {% for blog in blogs %} <div class="col-xl-12 col-md-6 col-xs-12 blog"> <div class="right-text-content"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> <h2 class="sub-heading">{{blog.title|title}}</h2> </button> <!-- Modal --> <div class="modal fade align-self-end mr-3 " id="myModal" tabindex="1" role="dialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">{{blog.title|title}}</h5> <h6 class="float-right">{{blog.created_at}}</h6> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{blog.content|linebreaks}} </div> <div class="modal-footer"> <h5>Created by {{blog.name}}</h5> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <p> <br> <a rel="nofollow noopener" href="{{blog.name_url}}" target="_parent">{{blog.name}}</a> <br> {{blog.content|linebreaks}} </p> {{blog.created_at}} </div> </div> {% endfor %} views.py from django.shortcuts import render from .models import DigitalTeam, Blog def index(request): pers = DigitalTeam.objects.all() return render(request, 'index.html', {'pers':pers}) def blog(request): pers = DigitalTeam.objects.all() blogs = Blog.objects.all() return render(request, 'blog.html', {'pers':pers, 'blogs':blogs}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('blog', views.blog, name='blog'), ] So guys what am i missing -
In Django after loading {{form.media}} javascripts in the page stop working
I am trying to use the django-map-widgets in my project. However, after I load the map using {{location.media}} {{location.as_p}} , even though the map loads fine, the other javascript codes in the page stop working. For example the "logout link" which uses a javascript script: The Django form: class LocationDetails(forms.ModelForm): class Meta: model = Provider fields = ['location'] widgets = { 'lage': GoogleStaticOverlayMapWidget(zoom=12, thumbnail_size='50x50', size='640x640'), } The rendered HTML code <!DOCTYPE html> <html lang="en-US" dir="ltr"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Document Title ============================================= --> <title> Ihr Dashboard </title> <!-- Favicons ============================================= --> <link rel="apple-touch-icon" sizes="57x57" href="/static/assets/images/favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/assets/images/favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/assets/images/favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/assets/images/favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/assets/images/favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/assets/images/favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/assets/images/favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/assets/images/favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/assets/images/favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/assets/images/favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/assets/images/favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/assets/images/favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/assets/images/favicons/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/assets/images/favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!-- Stylesheets ============================================= --> <!-- Default stylesheets--> <link href="/static/assets/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Template specific stylesheets--> <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Volkhov:400i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet"> <link href="/static/assets/lib/animate.css/animate.css" rel="stylesheet"> <link href="/static/assets/lib/components-font-awesome/css/font-awesome.min.css" rel="stylesheet"> <link href="/static/assets/lib/et-line-font/et-line-font.css" rel="stylesheet"> <link href="/static/assets/lib/flexslider/flexslider.css" … -
Categorise using foreign key in django
i want to display the names of product having a particular foreign key at a time my models.py: from django.db import models class Company(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='comapny') name = models.CharField(max_length=200) def __str__(self): return self.name i want it to display company names as list heading followed by list of all products of that particular company but dont know how to filter it like that and display on html my views.py: class Hydraulic(ListView): template_name = 'hydraulics.HTML' context_object_name = 'hydraulic' model = models.Product can someone tell me how i can filter it for name of foreignkey and inject it in HTML THANKS -
What are differences between mixins and utils in programming?
As I have seen these two concepts in different programming languages like python, dart. Sometimes I mixed up these two as one thing. are these two are similar or different? -
how can I get related users, of a given team? DRF
How can I get the users that are to a team, Ex: where Team master = 1 for example this is my models : from django.db import models from users.models import CustomUser # Create your models here. class Team(models.Model): master = models.ForeignKey(CustomUser, on_delete=models.CASCADE) name = models.CharField(null=False, blank=False, max_length=255) comment = models.CharField(null=True, blank=True, max_length=255) class TeamUser(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) My serializer : from rest_framework import serializers from apps.teams.models import Team, TeamUser class TeamUserSerializer(serializers.ModelSerializer): class Meta: model = TeamUser fields = '__all__' class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = '__all__' I want to get all the users that are related to team master 1 -
reconnecting-websocket.min.js:1 WebSocket connection to 'wss' failed: Error during WebSocket handshake: Unexpected response code: 200
I tried deploy my Django channels with WebSocket on Nginx, I tried a lot of ways but all failed try to change on my Nginx and tried to change the WebSocket URL but there is no any way work with me My nginx location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://127.0.0.1:8001; } my websocket url var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname var socket = new ReconnectingWebSocket(endpoint) my django channel layer in settings CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, }, } -
How to integrate google drive API with Django web application?
I want to store the files uploaded by users using a form to get stored in my google drive. Initially, I tried the following code (that prints names and ids of first 10 files) which only works as python script and I don't know how to change/use in the views of my Django application. (I might be also be doing something wrong in the setup part). from __future__ import print_function import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials … -
How to respond to method not allowed in Django class-based views
I have a Django app where the views are written using Django's generic views (pre-fixed, cannot change to APIView from Django rest framework). Each API either responds to POST, PUT, or a GET request. Now I want to respond to a custom message for other request types (DELETE, GET... etc) for every API. Currently, Django sends its default 405 Error without any response body. How can I change that? Here's a default class class ClassName(View): def post(self, request) -> JsonResponse: ...... some other application logic ...... return JsonResponse({ "status": True, "message": "", }, status=200) Now, this class only replies successfully to POST requests, any other methods are not allowed. How do I respond with the following message for other request types? return JsonResponse({ "status": false, "msg": "method not allowed", }, status=405) -
Nginx failing to serve django static or media files on digital ocean
I'm having issues serving static files and media files when I deploy my dockerised django app to digital ocean. I've read many similar questions on here, but none of the answers have worked for me so far. Roughly following this guide, https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#nginx, I'm now in a state where I can spin up my docker container locally using the following commands and have nginx serve static/media files perfectly: sudo docker-compose -f docker-compose-prod.yml down -v sudo docker-compose -f docker-compose-prod.yml up -d --build sudo docker-compose -f docker-compose-prod.yml exec web python manage.py collectstatic --no-input --clear I'm now attempting to get the same working on a digital ocean droplet. On the remote server I run exactly the same commands as above start up the services. Everything then works as expected apart from the ability to access any static or media file. Whenever I for example visit {my digital ocean ip}/static/admin/css/nav_sidebar.css, I'm met with a 404 error. Whenever I see chrome attempting to fetch my custom css, the requests just show as "cancelled" (and then if I visit the URL path of the cancelled request I see the same 404). My code can be seen here: https://github.com/PaulGilmartin/personal_website Parts perhaps relevant to this discussion: nginx.conf upstream personal_website … -
how i get the name of user who logged in my website now django
def show(request): if request.method == 'POST': if request.POST.get('location') and request.POST.get('member') and request.POST.get('arrival') and request.POST.get('leaving'): dest = Destination() dest.location = request.POST.get('location') dest.member = request.POST.get('member') dest.arrival = request.POST.get('arrival') dest.leaving = request.POST.get('leaving') dest.author = user.name(User.objects.all()) dest.save() messages.success(request, 'we will send you best option..!') return render(request,'travell/home.html') else: return render(request,'travell/home.html') what should i do in author please help i am new in this -
Why do I have a 'KeyError' error when using when using Django's coverage tool
Im developing a django API. Now im doing some tests on the endpoints and when i execute 'python manage.py test' everything goes well. But when i use the flag '--with-coverage' or 'coverage run --source='.' manage.py test app && coverage report' i get the error 'KeyError: 'BREAK_LOOP'. Someone can help me? Code from django.test import TestCase import requests class Teste(TestCase): url = "localhost://endpoint/" def test(self): token = self.token headers={ 'content-type' : 'application/json', 'Authorization' : token } response = requests.get(self.url, headers=headers) self.assertEqual(response.status_code, 403) Error nosetests --with-coverage --verbosity=1 Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/django_nose/runner.py", line 308, in run_tests result = self.run_suite(nose_argv) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/django_nose/runner.py", line 244, in run_suite nose.core.TestProgram(argv=nose_argv, exit=False, File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/nose/core.py", line 118, in __init__ unittest.TestProgram.__init__( File "/usr/lib/python3.8/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/nose/core.py", line 145, in parseArgs self.config.configure(argv, doc=self.usage()) File "/home/user/.virtualenvs/env/lib/python3.8/site-packages/nose/config.py", line 346, in configure self.plugins.configure(options, self) File … -
Django act as browser
Im lately working on a POC of mine. My goal is to forward the request from an user to another server and act as a kind browser in a browser. def test(request): r = requests.get('https://www.google.com') return HttpResponse(r) with this code i recieve a normal response (without css, but not that important rn), but i cant really use the site (makes sense, because im not really using their backend.) Is there a simple way to kinda act as an browser in django so that i could for example edit the recieved code? -
pyInstaller and Django : Couldn't import Django
I am working on an django application and have kind of finish coding it. This app is designed to be used by someone else and as she isn't so familiar with command line or so, i would like to create an executable (with pyInstaller) that start the localhost server and open the page on a browser (I don't nee to deploy it online or so, the localhost is sufficient). To do so, I've created a python script that calls the command python3 manage.py runserver and then open the localhost page in a browser. I then called the command pyinstaller myApp.py (with myApp.py the python script containing the 2 commands above) and then also the command pyinstaller TestMACB2.spec (I'm not sure I need this command but anyway I now have an executable that tries to run those two commands). The opening of the web page works well but I dont know why for the command to start the server, i have this error: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I do have django installed and when I start the server with the command in … -
Django/Python "django.core.exceptions.ImproperlyConfigured: Cannot import 'contact'. Check that '...apps.contact.apps.ContactConfig.name' is correct"
Hopefully you all can give me a hand with this... my work flow: |.vscode: |capstone_project_website: | -_pycache_: | -apps: | -_pycache_ | -accounts: | -contact: # app that is throwing errors | -_pycache_: | -migrations: | -_init_.py | -admin.py | -apps.py | -forms.py | -models.py | -test.py | -urls.py | -views.py | -public: | -_init_.py | -templates: # all my .html | -_init_.py | -asgi.py | -settings.py | -urls.py | -views.py | -wsgi.py |requirements: |scripts: |static: |.gitignore |.python-version |db-sqlite3 |docker-compose.yml |Dockerfile |Makefile #command I am running |manage.py |setup.cfg my Installed apps in capstone_project_website/settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "capstone_project_website.apps.accounts", "capstone_project_website.apps.contact", ] my capstone_project_website/apps/contact/apps.py: from django.apps import AppConfig class ContactConfig(AppConfig): name = "contact" the command I am running is in my Makefile: compose-start: docker-compose up --remove-orphans $(options) When I run make compose-start I get this message from my Terminal: make compose-start docker-compose up --remove-orphans Docker Compose is now in the Docker CLI, try `docker compose up` Starting django-website_postgres_1 ... done Starting django-website_db_migrate_1 ... done Starting django-website_website_1 ... done Attaching to django-website_postgres_1, django-website_db_migrate_1, django-website_website_1 db_migrate_1 | Traceback (most recent call last): db_migrate_1 | File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 244, in create db_migrate_1 | app_module = import_module(app_name) db_migrate_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", … -
Dynamic Forms with Logical Operators
I am currently stuck with a task where I need to create a form using HTML and JavaScript. I know it is very simple but the trick comes as second part. Think of form that is dynamic and over it uses logical operators such as "And" & "OR" operators to club the options selected by the user. I am really confused with this task. I can create dynamic dropdown selection form with JS with no problem but I have no idea how can I create a form that can club those selections with Logical operators also I have no idea how to handle DELETE for the form fields in between. I am fetching the dropdown meta-data from an API made over Django. I need to get the form data in post request so that I can create a string of SQL query. I know there will be many suggestion of how I can do it directly with Django but the fact is I need to create the SQL query string and not to run it on the database. Example of SQL Query String: SELECT first_name, last_name, salary FROM employees WHERE salary = 7000 OR salary = 8000 ORDER BY salary; … -
Pulling data associated with user account in Django
I'm creating a model in Django with the following syntax. The model has a foreign key of registered users. However, I want to serialize this model that will return a Json file only associated with the logged in user. Can you give your recommendations? Or is there an alternative way to extract the information from the model using different approach? class Education(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) school = models.CharField(max_length=50) year = models.CharField(max_length=10) -
Keyerror 'include' on migrating models to sql server
I have a django application and have backend as Microsoft sql server. For that, i have installed "pip install django-mssql-backend". I have extended User model and added one additional field of confirm_password and same i am migrating, but i am getting below error Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\core\management\commands\migrate.py", line 246, in handle fake_initial=fake_initial, File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\db\migrations\operations\models.py", line 531, in database_forwards getattr(new_model._meta, self.option_name, set()), File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\sql_server\pyodbc\schema.py", line 156, in alter_unique_together self.execute(sql) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\sql_server\pyodbc\schema.py", line 861, in execute sql = str(sql) File "C:\Users\RJhaveri\Documents\Ronak\SourceCode\Development\django\retailAudit\lib\site-packages\django\db\backends\ddl_references.py", line 201, in __str__ … -
domain name problem with django app dployed with heroku
i'm trying to add adsense to my django web app but i can't activate it because of "no content website" error. i'm using heroku to publish my webapp and i've seen that my website work with this way "mywebsite.herokuapp.com" but doesn't work with "www.mywebapp.herokuapp.com" and it's probably because of that i had this error. when i'm trying to acces to "www.mywebapp.com" my browser show me a page with that error : inaccessible website , DNS_PROBE_POSSIBLE in my settings.py file, the allowed_host line contains "mywebapp.com", "www.mywebapp.com" did somebody can say to me how to fix that in heroku web app's settings eventually or directly in my project files. thank you for helping me ! -
django rest framework: TypeError: unhashable type: 'list'
I can't find the bug please help I also tried this with custom models didn't worked. As you can see I'm tring to do PUT, DELETE and GET opration. Error Message Exception Type: TypeError at /api/user/sagar/Exception Value: unhashable type: 'list' views.py class ProfileApiView(generics.RetrieveUpdateDestroyAPIView): serializer_class = serializer.RegisterUserSerializer permission_classes = [IsAuthenticated, ] lookup_field = ['username'] def get_queryset(self): return User.objects.filter(username=self.request.user) serializer.py class RegisterUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True, validators=[ UniqueValidator(queryset=User.objects.all())]) username = serializers.CharField(required=True, validators=[ UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) class Meta: model = User fields = ['email', 'username', 'password'] def create(self, validated_data): user = User.objects.create( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user