Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django OR search with dictionary-based filter
I am working into someone else's code, and would like to modify the search behaviour – so that the query input is used as an “or” query across two fields. Currently I have this: forms.py class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] #filters['title__icontains'] = self.cleaned_data['q'] return filters views.py class FilteredListView(FormMixin, ListView): def get_form_kwargs(self): return { 'initial': self.get_initial(), 'prefix': self.get_prefix(), 'data': self.request.GET or None } def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() form = self.get_form(self.get_form_class()) if form.is_valid(): self.object_list = self.object_list.filter(**form.filter_by()) context = self.get_context_data(form=form) return self.render_to_response(context) What I would like to be able to do is take the “q” input and do something like this: self.object_list.filter(Q(title__icontains = request.GET['q']) | Q(description__icontains = request.GET['q'])) So that results are returned where “q” is present in the “title” or the “description”, or both. But I cannot work out a way to do that with the filter_by returning the dictionary as it currently is. Is it possible to do this? … -
Paypal IPN sent in the wrong order
We handle 10-20 payments daily using Paypals IPN system. The past hour or so Paypal has been sending the IPNs in the wrong order. Our payments are subscriptions. So generally they send. Subscr_signup & shortly after that susbcr_payment. But today they've been sending the subscr_payment before the subscr_signup every time. Which messed up our flow since the payment tries to link itself with a subscriber which it can't so it throws an error. This has forced us to manually add all the information which is a headache. Any ideas on how I should solve this? -
Django add many-to-many field to serializer
I have these tables: Transformed to django models: class A(models.Model): id = models.IntegerField(primary_key=True) fieldA = models.TextField() many_to_many = models.ManyToManyField('B', through="A_B") class Meta: managed = False db_table = 'A' class B(models.Model): id = models.IntegerField(primary_key=True) fieldB = models.TextField() class Meta: managed = False db_table = 'B' class A_B(models.Model): fk_A = models.ForeignKey(A, db_column='fk_A') fk_B = models.ForeignKey(B, db_column='fk_B') fieldC = models.TextField() class Meta: managed = False db_table = 'A_B' unique_together = (('fk_A', 'fk_B'),) Some sample data in these tables: Table A | TableB | Table A_B ______________________________________________________________ id fieldA | id fieldB | fk_A fk_B fieldC | | 1 "textA" | 1 "textB1" | 1 1 "textC1" | 2 "textB2" | 1 2 "textC2" And I need a serializer that for one row of A, for example the row id=1 from table A, it returns something like this: { "id":1, "fieldA":"textA", "many_to_many":[ { "B":{ "id":1, "fieldB":"textB1" }, "fieldC":"textC1" }, { "B":{ "id":1, "fieldB":"textB1" }, "fieldC":"textC1" } ] } The serializer that I used: class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = ('id','fieldB') class ASerializer(serializers.ModelSerializer): many_to_many = BSerializer(read_only=True,many=True) class Meta: model = A fields = ('id','fieldA','many_to_many') But can't figure out how to add fieldC to the ASerializer -
How can i get answer section like stack overflow in Django?
I want to add answer section like stack overflow and how model be handled ? -
problem in loading media files into templates
My django project is searching for images in /profile/<pk>/[app_name]/profile_pics/images.jpg instead of [app_name]/profile_pics/images.jpeg similar to this question image isn't uploaded to media root using Django Where's the problem? -
I am facing error of python migrate in Django
Hey I have am following Crazy Programmer i.e Rafe Qazi and now I am stuck at here. Cannot Run the code python manage.py migrate Please help me :) For image please click here :- https://i.imgur.com/oqoKLSG.png Please Help :) -
AJAX POST to DJANGO and get result back to frontend
i am trying to program a tool that use javascript "JQUERY" $get. to grab data from several API's in async way. The data is pushed to a query and send to DJANGO via AJAX. That works but.. The data should be edit in the backend via Python and should then be sent back to the front end. Problem: The data is shown in my answer of the inspector tool (FIREFOX) but not in my HTML. My HTML: <form method="POST" action="/my_page/" id="test_form"> {% csrf_token %} <input type="text" id="name" name="name" placeholder="Type Keywords ..."> <input type="submit" value="GO!"></input> </form> <tbody> {% for task in tasks %} <tr> <td> {{ task }} </td> </tr> {% endfor %} </tbody> js: $(document).on('submit','#test_form', function(e){ e.preventDefault(); var daten = []; var input = $('#name').val(); var apis = [ API1, API2, API3,...... and so on to API 50 ]; var api; for (api of apis){ $.get(api, function(data){ for (bla of data.suggestions){ daten.push(bla.value) }; }); }; const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 2000, daten); }); Promise.all([promise3]).then((values) => { $.ajax({ type: 'POST', url: '/my_page/', data: {'daten[]': values}, success:function(data){ console.log(data); } }); return false; }); }); views.py: @csrf_exempt def my_page(request): if request.is_ajax(): tasks = request.POST.getlist('daten[]') print(tasks) #That works fine return … -
Adding ManyToMany relation Using Django
following are my details. models.py class Employee(models.Model): EmployeeId = models.AutoField(primary_key=True, db_column='EmployeeId') EmployeeCode = models.CharField(max_length=50, unique=True, null=False, blank=False) EmployeeName = models.CharField(max_length=50) EmployeeStatus = models.SmallIntegerField(default=1, null=True, blank=True) CreatedDate = models.DateField(null=True, default=None, blank=True) CreatedUser = models.ForeignKey(Login, on_delete=models.PROTECT, db_column='CreatedUser', related_name='CreatedUser', null=True, default=None, blank=True) Device = models.ManyToManyField(Device, through='EmployeeDevice') class Meta: db_table = "Employee" serializer.py class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' views.py @api_view(['PUT']) @permission_classes([IsAuthenticated]) def employee_update(request): try: login = Login.objects.get(UserId=1) emp_serializer = EmployeeSerializer(data=request.data) if emp_serializer.is_valid(): emp_serializer.save() device = Device.objects.all() for devicedata in device: emp_serializer.Device.add(devicedata) else: logging.getLogger("error_logger").exception(emp_serializer.errors) return Response(emp_serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({'Exception': repr(ex)}, status=status.HTTP_400_BAD_REQUEST) this is my code but its not working properly device details is not saving showing error "Exception": "AttributeError("'EmployeeSerializer' object has no attribute 'Device'",)" and also i want to save the CreatedDate and CreatedUser with the existing data. and also how can i get the primary key value after inserting ? How can i do this ? -
Search and show data at the same time Django
Please don't downvote for any opacity in question, instead please comment the specified part. What I want: As we generally see on e-commerce site like say amazon. we search some keywords, then it loads the data but "one by one". for example, I searched a t-shirt. it first display a tshirt while other are in loading process, and then other gets loaded one by one then more are loading in the next line. It is like dynamic search along with dynamic user display. I want to achieve this in my django website. What I got to know after a lot search. -- elasticsearch is very good for searching data --* but what if I want to display my complete data of a model, but lets say 50 items on a page then 50 on next page so on. all items and their images are being loaded dynamically one by one. How can I achieve this "one by one display thing". Please suggest me some keywords to google it. Or guide me through the process. "or" is it an automatic process?? like once we can get all 50 items data and its images link in one Ajax request then, attaching DOM … -
Why am I getting this ImportError? cannot import name 'setting' from 'social_django.utils
ImportError: Could not import 'rest_framework_social_oauth2.authentication.SocialAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'setting' from 'social_django.utils' (/Users/Scott/Desktop/myvirtualenv/crazy/lib/python3.7/site-packages/social_django/utils.py). Here are my settings.py followed by my urls.py files. If anymore information is needed to diagnose this issue please let me know. Settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pzqls7qo%-fr!vm-$t%mkip%fa+9k$fnh728$x-0zl9lj0qp5t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Crazyapp', 'oauth2_provider', 'social.apps.django_app.default', 'social_django', 'rest_framework_social_oauth2', ] 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', ] ROOT_URLCONF = 'Crazy.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'Crazy.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization … -
API KEY still visible in the https query after using dotenv method for Django
I'm trying to hide the api key in https query... I end up with the method hiding it with .env file. I did all steps, but the key is still visible. In the query I see the actual numbers, not just variable being processed. What I didn't do or what I did wrong? I set up the dotenv program and did this in the code In .env file: PROJECT_KEY="1234567890" In settings: PROJECT_KEY_API_KEY = os.environ.get('PROJECT_KEY') In view: from django.conf import settings api_key = PROJECT_KEY_API_KEY In the actual query line in https address it tells me: ...&api_key=1234567890 I would like this key will be processed to external host, but not visible in the address. Thank you! -
cannot host django project in local network
I wanted to acess the web page that i did in django in all devices(mobile and desktop) connected in my network, i tried: simpply python manage.py runserver and acess the http://127.0.0.1:8000/ given by the console. The chrome of my mobile gives me "connection refused" put the ip in ALLOWED_HOST and python manage.py runserver my_ip:8000 my_ip is the number of my ip that the https://www.whatismyip.com/ gives me. python manage.py runserver 0:8000, it gives me [Errno 11001] getaddrinfo failed what can i do? -
Diffrence between 'Blog' And 'Blog.apps.BlogConfig' in installed_apps
What is the difference between Blog and 'Blog.apps.BlogConfig' in INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', **'Blog'**, ] And INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', **'Blog.apps.BlogConfig'**, ] Which is the best practice? -
Get exception traceback in middleware while DEBUG = False
My task is to return regular Djangos 500 error page with traceback if current user is admin. I have a middleware specified before others: def catch(get_response): # One-time configuration and initialization. def middleware(request): # Code to be executed for each request before # the view (and later middleware) are called. response = get_response(request) # Code to be executed for each request/response after # the view is called. # PRODUCES SAME RESULT print(response.content) print(response.getvalue()) print(response._container) return response return middleware Calling response.content, response.getvalue() and response._container in case of DEBUG = False produces same result: '\n<!doctype html>\n<html lang="en">\n<head>\n <title>Server Error (500)</title>\n</head>\n<body>\n <h1>Server Error (500)</h1><p></p>\n</body>\n</html>\n' I want to get classic fully described page somehow, how can it be possible? -
How to resolve Django MEDIA_ROOT pathing inconsistencies to get thumbnails to show?
I'm trying to get thumbnail images from an ImageField to show up in a Django 3.0.4 site. When I create an instance of a model called Resource in the shell, I can grab a file object from the MEDIA_ROOT/default_thumbnails directory and use it for the ImageField in the instance. The resource.thumbnail returns an ImageFieldFile. When I look at the detail view of that object in the django admin, it lists the correct path to the thumbnail file I'd expect: /home/rob/development/eh/eduhwy/media/default_thumbnails/xyz.jpg When I visit the detail view for that resource in the site, it also lists the above filepath. But it does not show the image. And when I click the link, I get an error that the following path does not exist: /home/rob/development/eh/eduhwy/media/home/rob/development/eh/eduhwy/media/default_thumbnails/xyz.jpg The duplicated "/home/rob/development/eh/eduhwy/media" makes me suspect there is an extra slash or misconfigured path somewhere but I cannot find it. The kicker is that if I create a resource through the admin using the exact same image file, everything works fine. Relevant settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_URLCONF = 'eduhwy.urls' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR + '/eduhwy', 'static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR + '/eduhwy', 'media') models.py: class … -
In production (deployed to pythonanywhere.com) - How do I resolve this error while adding user to group in django admin?
Everything work in my local environment but gives error in production. Here's my custom permission in a decorator.py from django.http import HttpResponse from django.shortcuts import redirect def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = [] if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view the page') return wrapper_func return decorator Then in my view.py: @login_required @allowed_users(allowed_roles=['supervisor']) def journal_entry(request): JournalFormset = modelformset_factory(JournalEntry, fields='__all__', extra=1) if request.method == 'POST': form = JournalFormset(request.POST, queryset=JournalEntry.objects.none()) instance = form.save() form = JournalFormset(queryset=JournalEntry.objects.none()) return render(request, 'journal_entry.html', {'form':form}) When I try to add the a user to 'supervisor' group as in: adding user to 'supervisor' group I get the following error: ProgrammingError at /admin/auth/user/2/change/ syntax error at or near "ON" LINE 1: ...ser_groups" ("user_id", "group_id") VALUES (2, 1) ON CONFLIC... ^ Request Method: POST Request URL: https://mogononso.pythonanywhere.com/admin/auth/user/2/change/ Django Version: 3.0.4 Exception Type: ProgrammingError Exception Value: syntax error at or near "ON" LINE 1: ...ser_groups" ("user_id", "group_id") VALUES (2, 1) ON CONFLIC... ^ Exception Location: /home/mogononso/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 86 Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/home/mogononso/.virtualenvs/myenv/lib/python3.7/site-packages/git/ext/gitdb', '/var/www', '.', '', '/var/www', '/home/mogononso/.virtualenvs/myenv/lib/python37.zip', '/home/mogononso/.virtualenvs/myenv/lib/python3.7', '/home/mogononso/.virtualenvs/myenv/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/mogononso/.virtualenvs/myenv/lib/python3.7/site-packages', '/home/mogononso/churchapp/churchapp2', '/home/mogononso/.virtualenvs/myenv/lib/python3.7/site-packages/gitdb/ext/smmap'] Server time: Tue, 7 … -
Store JSON in database with python
I've been having trouble storing JSON to database with non ASCII characters. Here's what I have so far. I'm using python requests library. getJSON = requests.get('https://jsonapi.com/jsonfile') storeDB = requests.post( 'http://databaseAPI/Database/item', data='{"payload": %s}' % (getJSON.text), headers={'Content-Type': 'application/json'} ) But it's failing with this error because my JSON contains non ASCII character. How can I fix that? Error - Traceback (most recent call last): File "addKonvo.py", line 134, in <module> headers={'Content-Type': 'application/json'} File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 119, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 530, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 643, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.7/site-packages/requests/adapters.py", line 449, in send timeout=timeout File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 672, in urlopen chunked=chunked, File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 387, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1252, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1297, in _send_request body = _encode(body, 'body') File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 170, in _encode (name.title(), data[err.start:err.end], name)) from None UnicodeEncodeError: 'latin-1' codec can't encode character '\u20ac' in position 505: Body ('€') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.``` -
Having issue with rendering table rows with list of dictionaries using django-tables2
I'm having issue with rendering the table rows by passing list of dictionaries using django-tables2. views.py ======== list_of_dict = [{"File Path": 'path1', "Age": 500, "No of files": 90}, {"File Path": 'path2', "Age": 400, "No of files": 25}] nt = Small_table(list_of_dict) RequestConfig(request).configure(nt) return render(request, "collectionsec.html", {"small": nt}) tables.py ========= import django_tables2 as tables class Small_table (tables.Table): name = tables.Column() age = tables.Column() nof = tables.Column() class meta: attrs = {'class': 'paleblue'} attrs = {'class': 'table table-responsive', 'width': '100%'} collectionsec.html ================== {% load django_tables2 %} {% render_table small %} This is what the output looks like: Name Age Nof — — — — — — Can somebody please help me with this? Thanks in advance :) -
Ignoring a folder inside static files using gitignore in a Django project
I have a folder inside the static directory of an app in a Django project. Lets call this special_folder. It contains some static files that I do not want to commit to Git. The project directory looks something like this: myproject | +-- manage.py | +-- .gitignore | +-- myapp | +-- static | +-- special_folder Now, if I want to ignore this folder for Git, do I need to add something like the following line to the .gitignore file: myapp/static/special_folder/ Is this the right approach? Or should I just add special_folder/? Thanks for any help. -
How can I get setUpTestData to tear down / rollback primary keys (postgreSQL)?
I am using postgreSQL 12. I have two TestCase classes: class TestA(TestCase): @classmethod def setUpTestData(cls): for _ in range(5): MyModel.objects.create() def test_1(self): print('Start test 1') objects = MyModel.objects.all() for i in objects: print(i.pk) self.assertEqual(True, True) class TestB(TestCase): @classmethod def setUpTestData(cls): for _ in range(5): MyModel.objects.create() def test_2(self): print('Start test 2') objects = MyModel.objects.all() for i in objects: print(i.pk) self.assertEqual(True, True) This results in printing: Start test 1 1 2 3 4 5 Start test 2 6 7 8 9 10 When these tests are run it is clear that although the tearDownClass is removing the objects, the autoincrement on primary key is not being reset. Indeed, if I try to set MyModel.objects.create(pk=1) on test_2 then I get a duplicate key value error. This causes problems if you use something like factory_boy to create your fixtures, as it will throw similar duplicate key errors. Why are primary keys not removed and how to I fix this situation? -
Can I change datetime-local format for django-filters?
I'm using django-filters for a datetime filter. When I try to use datetime-local my form sends the date time query like this: 2020-07-07T18:39 But my django-filter accept the format just like this: 2020-07-07 18:39 Can I change the format of datetime-local input field somehow? -
Managing crossed-apps models in Django
first question here in Stackoverflow... So, I need a solution for making it possible to edit a Django app through another Django app. For example, i have an App called homepage which has a model named homepage, and another app called post which has a model named Post. I'd like to create or edit some posts through another tab inside the HomePage admin (I'm using django-nested-inline App). I've already thought in using an Inline model but for me it makes no sense having a "homepage foreign key" inside Posts... Sorry if I mispelled something and if my question is out of the terms of SO... Thanks! -
Django AllAuth OAuth2Provider, how to get jwt token to front-end
I have created my own ProviderAccount, OAuth2Provider, and OAuth2Adapter. I am using an internal SSO system. I have set this all up, get redirected to my SSO page via accounts/MY_PROVIDER/login/?process=login, redirected back to my callback URL, then directed back to my homepage. However, I am wondering how can I get a JWT token for the signed in user? My front-end and django backend are seperate.. I am NOT using django views(seperate react frontend), it's just a django restframework. When I get redirected back to the home page, this comes in the cookies messages="{REDACTED CODE}$[[\"__json_message\"\0540\05425\054\"Successfully signed in as MY_USER.\"]\054[\"__json_message\"\0540\05425\054\"Successfully signed in as MY_USER.\"]\054[\"__json_message\"\0540\05425\054\"Successfully signed in as MY_USER.\"]\054[\"__json_message\"\0540\05425\054\"Successfully signed in as MY_USER.\"]\054[\"__json_message\"\0540\05425\054\"Successfully signed in as MY_USER.\"]\054[\"__json_message\"\0540\05425\054\"Successfully signed in as MY_USER.\"]\054[\"__json_message\"\0540\05425\054\"Successfully signed in as MY_USER.\"]]"; csrftoken={REDACTED CODE}; sessionid={REDACTED CODE} I don't believe any of those are auth tokens, and just regular old session tokens and what not... so I am wondering how can i get a JWT token returned or how can I get that? -
How to communicate between two django instances?
So I am having two connections, one is a websockets connection with the frontend for notifications and another is a http connection which the user will directly use to perform some special actions. So there will be a websocket connection from one tab and a separate http connection in another tab. I have to relay events happening in the django http instance to the websockets connection so it can notify the frontend. Now as I understand Django, it creates separate application instances for every request. I want a way to quickly communicate that http instance and the websockets instance. I'm using Django (version 2.2) along with django-channels for the websocket functionality. I know that there is a CHANNEL_LAYER feature in channels to communicate over something like Redis. I'm avoiding the use of Redis because this would be the only use-case for it and it won't be feasible. Is there another way to achieve this without the use of Redis? -
Updated with Fixtures: Django REST test error: *** django.db.utils.ProgrammingError: relation “” does not exist
Hi I am testing my rest endpoint. When I run my test, python manage.py test apps.pulse.tests.PulseTestCase.test_clinical_pubmed I get an error that the test model does not exist in the test db. *** django.db.utils.ProgrammingError: relation "pulse_targets" does not exist For my endpoint I need to create a test model instance, which should get populated in setUp(self), but that error gets throwed. Here is my test class, from django.test import TestCase from apps.pulse.models import Twitter from apps.pulse.models import Targets import json class PulseTestCase(TestCase): def setUp(self): Targets.objects.create(gene_id='wee1') target = Targets.objects.get(gene_id='wee1') Twitter.objects.create(target=target, tweet_id=21212121212112212, user_id=313133131313133, tweet='wee1 in cancer', user='DeplorableBob') def test_twitter(self): response = self.client.post('/api/pulse/twitter', {'geneID': 'adrb2'}, format='json') self.assertEqual(response.status_code, 200) def test_clinical_pubmed(self): response = self.client.post('/api/pulse/clinicalpubmed', {'geneID': 'adrb2'}, format='json') self.assertEqual(response.status_code, 200) Here is my models.py class Targets(models.Model): gene_id = models.CharField(max_length=50, blank=True, null=True) uniprot = models.CharField(max_length=50, blank=True, null=True) ensemble_id = models.CharField(max_length=50, blank=True, null=True) Here is views.py @api_view(['POST']) def get_clinical_pubmed(request): try: response = middleware.get_clinical_pubmed(request.data['geneID']) except: response = 'Something went wrong' return JsonResponse({'data': response}) Here is my fixture 0001_initial.py class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ConferenceWatchList', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=200, null=True)), ('society', models.CharField(blank=True, max_length=200, null=True)), ('url', models.CharField(blank=True, max_length=200, null=True)), ('start_date', models.DateField(blank=True, null=True)), ('end_date', models.DateField(blank=True, null=True)), ('abstract_release_date', models.DateField(blank=True, null=True)), …