Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter_horizontal pre-selected items
I want see in django admin filter_horizontal not all my tags, but only tags of one selected group. Example: My tags: Group Fruits: Apples, Plums, Appricots.. Group Flowers: Roses, Tulips, Asters.. I want to be able select anywhere in admin one plants group (for example "Fruits") and see in filter_horizontal tags "Apples, Plums, Appricots.." , but not "Roses.." My models: class PlantsGroups(TitleRequiredModel): is_active = models.BooleanField(default=True) ... def __str__(self): return self.title class PlantsTags(TitleRequiredModel): is_active = models.BooleanField(default=True) ... plants_group = models.ForeignKey(PlantsGroups, on_delete=models.CASCADE) def __str__(self): return self.title class PlantsTags(TitleRequiredModel): is_active = models.BooleanField(default=True) ... plants_tags = models.ManyToManyField('PlantsTags', blank=True, related_name="blabla", verbose_name='blablabla') def __str__(self): return self.title Thanks! I am novice to django, please help me :) -
Highlight entire row in Django admin list
I've been stuck on this issue for days. I have a change_list with applicants, now I want to highlight the rows of objects that have been changed recently. To do this I made a custom property: @property def has_recently_been_modified(self): return datetime.now() - self.updated_at < timedelta(days=5) Which I use in the admin.py to create a field that houses a class I need: def recently_modified(self, obj): if obj.has_recently_been_modified: return mark_safe("<span class='row_yellow'></span>") recently_modified.allow_tags = True list_display = ('custom_status','viewed', 'updated_at', 'first_name', 'last_name', 'vacancy', 'created_at', 'recently_modified') And with JS I use that class to color the row: window.onload = function () { const x = document.getElementsByClassName("row_yellow"); let i; for (i = 0; i < x.length; i++) { let ligne = x[i].parentNode; while (ligne.tagName !== "TR") { ligne = ligne.parentNode; } ligne.style.backgroundColor = "yellow"; } } Although it does color the entire row, the extra empty column at the end of the row is a real thorn in my eye. Removing it from the list_display doesn't obviously work. So my question is, is there a clever way to "hide" it? Or even a completely different method to color the row? I have tried using django-liststyle, but that seems like a broken package. I immediatly get a … -
How to test an OTP-secured Django form?
I'm building a Django application using the django_otp OTP extension, and I'm running into some issues with automated testing of forms. Specifically, despite everything I've tried, attempts to call a form decorated with otp_required results in getting shown the 'you need to enable OTP on this account' redirect page. I've made several attempts at implementing things suggested by google searches, such as this one and several others. Right now, during the TestCase __init__ I create a user with the following code: # Set up a user: self.testuser = User.objects.create(username='testuser') self.testuser.set_password('12345') self.testuser.is_superuser = True self.testuser.is_verified = True self.otp_device = self.testuser.staticdevice_set.create(name='Testdevice') self.otp_device.confirmed = True self.otp_device.save() self.testuser.save() And when using a Client object to make a request: def setup_client(self): client = Client() client.force_login(self.testuser) client.session.save() return client The failing test case is: def test_connection_create_form_no_circuit(self): testdata = baseData() client = testdata.setup_client() client_group = ClientGroup.objects.get(name='testgroup') context_id = Context.objects.get(name='testcontext').id bandwidth_id = BandwidthProfile.objects.get(name='testprofile').id conntype_id = ConnectionType.objects.get(name='testconntype').id postdata = { 'id_enabled': True, 'id_circuitless': True, 'id_debug_info': False, 'id_connectionref': 'Test 1234', 'id_customer': '321', 'id_install_address': '123 Stockton Bvd.', 'id_carrierref': 'nil', 'id_c_context': context_id, 'id_c_bandwidthprofile': bandwidth_id, 'id_c_connectiontype': conntype_id, 'id_ppp_username': 'test_conn_123', 'id_ppp_password': 'pass_54321', 'id_ipv4_address': '1.2.3.4' } response = client.post('/radius/clientgroup/%d/connection/' % client_group.id, postdata) self.assertEqual(response.status_code, 200) Rather than a 200 I'm getting a 403 and the 'You … -
What should a django view that processes the post request from esp32 look like
I have a challenge sending data from esp32 to my django server. I am using HttpClient and my site is hosted on ngrok. I have a sensor conneted to an Arduino Uno and the Arduino send sensor values to esp32 using serrial communication. I need to display these values on my django website. I had thought of using the Ethernet shield instead of esp32 but still facing te same problem, In the Ethernet shield configuratio, i need a port but my ngrok url does not have one or maybe it has but i dont know how to use it. views.py def post_entry(request): if request.method == 'POST': post_data = request.body return HttpResponse('Hey there im working') The esp32 code: #include <WiFi.h> #include <HTTPClient.h> const char* ssid = ""; const char* password = ""; void setup(){ Serial.begin(115200); delay(1000); WiFi.mode(WIFI_STA); //Optional WiFi.begin(ssid, password); Serial.println("\nConnecting"); while(WiFi.status() != WL_CONNECTED){ Serial.print("."); delay(100); } Serial.println("\nConnected to the WiFi network"); Serial.print("Local ESP32 IP: "); Serial.println(WiFi.localIP()); } void loop(){ if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status HTTPClient http; http.begin("my-url-created-from-ngrok/post-entry/"); //Specify destination for HTTP request http.addHeader("Content-Type", "application/json"); //Specify content-type header int httpResponseCode = http.POST("POSTING from ESP32"); //Send the actual POST request if(httpResponseCode>0){ String response = http.getString(); //Get the response to the request … -
best way of authentication for django rest framework [closed]
I have searched so much about different ways of authentication(JWT,Session,..) but I can't draw a conclusion which one is the best and I'm confused. I would be glad if someone has any experience. Thanks. -
Returning data to Django form for editing
I am using multiple forms which opens in modals from the same page at my Django app. I got it to work with custom functions, but now I'm a bit struggling on how to add editing functionality since I am very new to Django. Since this way working with forms is very new to me I got lost where should I provide instance that form would show already entered data for that instance. This is form variable in views.py edit_employment_form = _get_form(request, EditEmploymentForm, "edit_employment_form_pre") This is function I use to differiante between forms. (Or at least i think that this does it) def _get_form(request, formcls, prefix): data = request.POST if prefix in request.POST else None return formcls(data, prefix=prefix) This is my full view in views.py to better understand structure. Below request.method condition is variable employment_id which I am going to use to filter instance. I get that id from button in html which itself is form and returns me item id from for loop. @login_required def person_profile(request, person_id): current_user = request.user user = Person.objects.get(user=current_user) people = Person.objects.all() jobs = Job.objects.all() person = Person.objects.get(pk=person_id) employments = Employments.objects.filter(person_id=person_id).order_by("-start_date") workflows = Workflows.objects.filter(person_id=person_id).order_by("-workflow_date") sources = Sources.objects.filter(person_id=person_id).order_by("-source_date") tags = Tags.objects.filter(person_id=person_id) comments = Comments.objects.filter(person_id=person_id) person_calls = … -
How to send json data from events sent from server in Django?
I'm looking for an answer to my question, how do I send "JSON data"? For example, if I wanted to submit a discussion, it would be sent as a string, not "JSON" This is what I'm sending but I really want to send the discussion but I count the number of discussions and send it and if the number the user has is different from this number it updates the data and I see it's a bad way views.py def stream(request): def event_stream(): discussion = Discussion.objects.all() count = discussion.count() while True: time.sleep(3) yield 'data: %i\n\n' % count return StreamingHttpResponse(event_stream(), content_type='text/event-stream') template if(typeof(EventSource) !== "undefined") { var source = new EventSource("stream/"); source.onmessage = function(event) { console.log(event.data); }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } -
Error that says -: template does not exist
So , this is my first ever try with django and im currently learning about urls and views, ive been encountering the error that says "template not found " i apologize beforehand if the question is noob-ish. (here is the code for urls.py file) `""" URL configuration for views_urls project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home) ] ` (below is the code for the view.py file that i created , which exists in the same folder as the url.py file) `from django.shortcuts import render def home(request): return render(request, 'main.html')` (below is the main.html file the exists in a folder called templates) `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" … -
'Order' object has no attribute 'orderitem_set'
1 I'm trying to get the orderitem per order. The error AttributeError at /cart/ 'Order' object has no attribute 'orderitem_set' models.py class Order(models.Model): customer= models.ForeignKey(Users,on_delete=models.SET_NULL,null=True, blank=False) date_oder= models.DateTimeField(auto_now_add=True) status= models.BooleanField(default=False) transaction_id= models.CharField(max_length=100, null=True) delivery_date= models.DateTimeField(auto_now_add=True) delivered= models.DateTimeField(auto_now=True) def str(self) : return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class Order_detail(models.Model): product= models.ForeignKey(Products,on_delete=models.SET_NULL,null=True, blank=False) order= models.ForeignKey(Order,on_delete=models.SET_NULL,null=True, blank=False, related_name='order_items') quantity=models.IntegerField(default=0,null=True, blank=True) date_added=models.DateTimeField(auto_now_add=True) def get_total(self): total= self.product.pro_price * self.quantity return total View.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer ,status = False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0,'get_cart_items':0} context = {'items':items , 'order': order} return render(request,'app/cart.html',context) please, I cannot solve this problem -
How to solve permission error while testing drf view?
I am getting permission error AttributeError: 'WSGIRequest' object has no attribute 'authenticators' while testing my drf view. I am using djangorestframework-api-key for rest framework permission. views.py class SliderViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet): queryset = Slider.objects.all() serializer_class = SliderSerializer lookup_field = "id" test_view.py class TestSliderViewSet: @pytest.fixture def api_rf(self) -> APIRequestFactory: return APIRequestFactory() def test_get_queryset(self, slider: Slider, api_rf: APIRequestFactory): view = SliderViewSet() request = api_rf.get("/fake-url/") view.request = request assert slider in view.get_queryset() def test_get_object(self, slider: Slider, api_rf: APIRequestFactory): from rest_framework_api_key.models import APIKey api_key, key = APIKey.objects.create_key(name="my-remote-service") view = SliderViewSet() request = api_rf.get("/fake-url/") request.META['X_API_KEY'] = f'Api-Key {key}' view.request = request view.kwargs = {"id": slider.pk} assert slider == view.get_object() if I remove rest_framework_api_key.permissions.HasAPIKey from DEFAULT_PERMISSION_CLASSES test is done successfully. -
Sum of object fields in django
I have a "Bet" model, there is a total_amount field. I want that when creating a model object, 'total_amount' is the sum of the fields "rubles", "euros", "dollars". But when i create new object then 'total_amount' is 0 class Bet(models.Model): bet_id = models.AutoField(primary_key=True) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='bet_event') user = models.ForeignKey(User, on_delete=models.CASCADE) euros = models.IntegerField(default=0) rubles = models.IntegerField(default=0) dollars = models.IntegerField(default=0) total_amount = models.IntegerField(default=0) max_amount = models.IntegerField(default=0) def save(self, *args, **kwargs): balance = {'euros', 'rubles', 'dollars'} self.total_amount = sum([value for key, value in self.__dict__.items() if key in balance]) super(Bet, self).save(*args, **kwargs) -
Django hitcount gives error AttributeError at /admin/hitcount/hit/ 'NoneType' object has no attribute '_base_manager'
AttributeError at /admin/hitcount/hit/ 'NoneType' object has no attribute '_base_manager' 'NoneType' object has no attribute '_base_manager' 43 {% if site_url %} 44 <a href="{{ site_url }}">{% translate 'View site' %}</a> / 45 {% endif %} 46 {% if user.is_active and user.is_staff %} 47 {% url 'django-admindocs-docroot' as docsroot %} 48 {% if docsroot %} 49 <a href="{{ docsroot }}">{% translate 'Documentation' %}</a> / 50 {% endif %} 51 {% endif %} 52 {% if user.has_usable_password %} 53 <a href="{% url 'admin:password_change' %}">{% translate 'Change password' %}</a> / 54 {% endif %} 55 <a href="{% url 'admin:logout' %}">{% translate 'Log out' %}</a> 56 {% endblock %} 57 </div> 58 {% endif %} 59 {% endblock %} 60 {% block nav-global %}{% endblock %} 61 </div> 62 <!-- END Header --> 63 {% block breadcrumbs %} -
Indexing SearchVector makes query slower in django ORM - PostgreSQL
I have a model with 2 string fields, the model stores around 8m of records. from django.contrib.gis.db import models from postgres_copy import CopyManager class Patent(models.Model): office = models.CharField(max_length=100) office_patent_id = models.CharField(max_length=100) type = models.CharField(null=True, blank=True, max_length=100) application_filed_date = models.DateField(null=True) granted_date = models.DateField() title = models.TextField() abstract = models.TextField(null=True, blank=True) claims_count = models.IntegerField() figures_count = models.IntegerField(null=True) sheets_count = models.IntegerField(null=True) withdrawn = models.BooleanField() objects = CopyManager() Running the following query without indexing anything runs in 425s ~ 7m from django.contrib.postgres.search import SearchVector, SearchQuery cpu_gpu_count = Patent.objects.annotate( search=SearchVector('title', 'abstract') ).filter(search=SearchQuery("CPU | GPU")).count() Indexing the SearchVector like this, in a new migration file and running the same query, gives me the same result but in 453s, which is even worse than the un-indexed timings. What's going on? from django.db.migrations import Migration, AddIndex, RunPython from django.contrib.postgres.indexes import GistIndex, GinIndex from django.contrib.postgres.search import SearchVector class Migration(Migration): dependencies = [ ("main", "0001_initial"), ] operations = [ AddIndex("Patent", GinIndex(SearchVector("title", "abstract", config="english"), name="main_patent_title_abstract_idx")) ] I have also tried adding a SearchVectorField and using a GIN index on that. Initially populate it, and then add a trigger to update it as the docs suggest but this made my database unresponsive. Even the count(*) query never finished within an hour, the … -
Multiple migrations are created everytime in django
I have a model in my app : class PutAwayProductsPosition(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE) put_position = models.CharField(max_length=50, default=0) is_put = models.BooleanField(default=False) class PutAway(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) grn = models.ForeignKey("grn.GRN", on_delete=models.CASCADE) employee_assigned = models.ForeignKey(Employee, on_delete=models.CASCADE) putaway_id = models.IntegerField(default=0) products_position = models.ManyToManyField(PutAwayProductsPosition) completely_executed = models.BooleanField(default=False) partially_executed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) scheduled_datetime = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) evertime i run makemigrations a file is created like the following in migrations class Migration(migrations.Migration): dependencies = [ ('grn', '0068_auto_20230411_0703'), ('putpick', '0033_auto_20230410_0810'), ] operations = [ migrations.AlterField( model_name='putaway', name='grn', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='grn.GRN'), ), ] even when there is no change in the model, i migrate them and then after that if i run makemigrations again this file is created in the folder, I am unable to understand the reason for this -
How can I restrict a user from accessing certain pages?
There are pages "password_reset/" and "password_reset/done/". After filling out the form on the "password_reset/" page, there is a redirect to the "password_reset/done/" page. But if someone tries to access the page through the url, he will succeed. How to fix it. path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'), I tried to solve it this way, but something didn't work out. class CustomPasswordResetDoneView(PasswordResetDoneView): def get(self, request, *args, **kwargs): referer = request.META.get('HTTP_REFERER') if referer != reverse('password_reset'): return HttpResponse(status=404) return render(request, 'registration/password_reset_done.html') -
"Select a valid choice. That choice is not one of the available choices" error on OneToOneField
models.py class Major(models.Model): major = models.CharField(max_length=50, unique=True) description = models.TextField() image = models.ImageField(default='default_pics/default_major.jpg', upload_to='major_pics') class Teacher(models.Model): image = models.ImageField(default='default_pics/default_teacher.jpg', upload_to='teacher_pics') interest = models.TextField(blank=True,null=True) major = models.ForeignKey(Major, on_delete=models.SET_NULL, null=True) user = models.OneToOneField(MyUser, on_delete=models.CASCADE) forms.py class TeacherProfileCreationForm(forms.ModelForm): class Meta: model = Teacher fields = ['major', 'image'] help_texts = { 'image': 'If you do not set any image, one will be set automatically for this teacher upon creation.' } views.py @login_required def teacher_create_view(request): if request.method == 'POST': u_form = TeacherUserCreationForm(request.POST) t_form = TeacherProfileCreationForm(request.POST, request.FILES) if u_form.is_valid and t_form.is_valid(): u_form.save() t_form.save(commit=False) email = u_form.cleaned_data.get('email') user = MyUser.objects.get(email=email) t_form.instance.user = user t_form.save() teacher = Teacher.objects.get(user__email=email) messages.success(request, f'A teacher has been added!') return redirect('teacher-detail', teacher.id) else: u_form = TeacherUserCreationForm() t_form = TeacherProfileCreationForm() context = {'u_form': u_form, 't_form': t_form, 'list_url':list_url,'list_title':list_title, 'detail_title': detail_title} return render(request, 'users/teacher_create_update_form.html', context) tests.py class TestTeacher(TestCase): def setUp(self): self.client = Client() self.major = Major.objects.create( major='Test Major', description='Foo bar', ) self.teacher_user = User.objects.create( email="test_teacher@gmail.com", full_name="Test Teacher 1", is_teacher=True ) self.teacher = Teacher.objects.create( major=self.major, user=self.teacher_user ) self.teacher_create = reverse('teacher-create') def test_teacher_create(self): response = self.client.post(self.teacher_create, { 'email': 'test_teacher2@gmail.com', 'full_name': "Test Teacher 2", 'password1': '@DylanBergmanN1!', 'password2': '@DylanBergmanN1!', 'major': self.major # The error is most probably right here }) print(response.context['t_form'].errors) Error message in terminal <ul class="errorlist"><li>major<ul class="errorlist"><li>Select a valid … -
How to run vuejs project with django app together?
I am developing the front-end side in VueJs and backend-side in Django. I am using REST API for the connection between front-end and backend. After building the VueJS project, I received the dist folder. Is it right way to run this dist folder inside django project? Is it good way to continue? path('', TemplateView.as_view(template_name='index.html'), name='index') The index.html is generated by after building VueJs project. -
Downloaded zip file getting corrupts in DRF this my code
@action(detail=False, methods=['post']) def download_zip_attachment(self,request,**kwargs): data = request.data project_id=request.data.get('project_id',None) buffer = BytesIO() zf = zipfile.ZipFile(buffer, "w", zipfile.ZIP_STORED) project = Project.objects.get(id=project_id) project_doc=project.project_chunks.all() for chunk_index, chunk in enumerate(project_doc): for index, attachment in enumerate(chunk.attachments.all()): file_name = str(attachment.attachment).split('/')[-1] current_file = attachment.attachment.path if os.path.isfile(current_file): zf.write(current_file, file_name) zf.close() buffer.seek(0) response = FileResponse(buffer, as_attachment=True, filename='project.zip') response['Content-Type'] = 'application/x-zip-compressed' response['Content-Disposition'] = 'attachment; filename="project.zip"' return response @action(detail=False, methods=['post']) def download_zip_attachment(self,request,**kwargs): data = request.data project_id=request.data.get('project_id',None) buffer = BytesIO() zf = zipfile.ZipFile(buffer, "w", zipfile.ZIP_STORED) project = Project.objects.get(id=project_id) project_doc=project.project_chunks.all() for chunk_index, chunk in enumerate(project_doc): for index, attachment in enumerate(chunk.attachments.all()): file_name = str(attachment.attachment).split('/')[-1] current_file = attachment.attachment.path if os.path.isfile(current_file): zf.write(current_file, file_name) zf.close() buffer.seek(0) response = FileResponse(buffer, as_attachment=True, filename='project.zip') response['Content-Type'] = 'application/x-zip-compressed' response['Content-Disposition'] = 'attachment; filename="project.zip"' return response -
Dynamically create tab with label device IP and pull the information from device to show up in display
I am trying to build an app which will do the authentication for the ARISTA or any other Device IP address/username and password using eAPI json api. and once authenticated it will populate the device data into the new created dynamic tab. I have created the app @ https://github.com/rakeshbitsindri/connect what it is supposed to do is to do the Ajax call from the home.html to views.py for login once pressed the + button in the webpage, after successful authentication from DUT it will pull out the device info and add it in a dynamically created tab attached to the + button, this will be primary tab bar, I will need the secondary tab bar as well, where i can show various information from device categorically and also apply config /modify some of the config of device. The place where i am stuck is after pressing the + button the add_device page opens up, after putting device info the tab is not created, the device login info is correct but not sure how-to make it working seems like the ajax call is either not working in my case, or ajax call is not returning the views.py function output. or may be … -
request.session[] doesn't work on mobile phone (chrome) but works on desktop. Why?
I've made a store and it is super strange, it works on desktops and iPads without any bugs but when I check it on my mobile phone it has a strange bug. The bug is: There are a store page and the cart page. I add the first item to request.session[] on the "store page", I go to "cart page" and I see that the item is there, right from the request.session[]. Then I go back to the "store page" and add another item. I go back to the "cart page" again and I don't see the second item in the cart! I can click the "cart" link again and again. And there will not be the 2nd item. I can go to another page and then go back to the "cart" page again, and there will not be the 2nd item, but if I just refresh the page - the item will appear. Why? Why do I need to refresh the page, even going back and forward doesn't work, but only refreshing works... After refreshing it shows all items from the request.session[]. I really can't understand how it can be. Do you have a clue? I wanted to connect … -
Git pull, não puxa
meu nome é Gentil Nascimento. Tô concluindo um curso de Django, e finalizando o projeto do curso. Criei o arquivo 'requirements.txt' no visual studio code, subi pro git hub, ta tudo certo lá. To enviando o projeto pra plataforma; Google App Engine, e Dentro do Computer clonei o projeto e fiz git pull. Quando tento instalar o 'requirements.txt' dá erro. (venv) gentiln65@server-principal:~/Django3$ git pull Already up to date. (venv) gentiln65@server-principal:~/Django3$ ls blog 'folha de comandos.txt' requirements.txt templates_geral db.sqlite3 manage.py strata website (venv) gentiln65@server-principal:~/Django3$ pip install -r blog/requirements.txt Could not open requirements file: [Errno 2] No such file or directory: 'blog/requirements.txt' (venv) gentiln65@server-principal:~/Django3$ -
Getting django-eventstream and Pushpin working
I'm trying to get django-eventstream and Pushpin working within a kubernetes cluster. I can successfully subscribe to the stream, but I never receive data sent via send_event. And I do not receive any errors messages to tell me where things are going wrong. The stream I'm trying to get working is a logging stream to my app, so it is routinely getting updates. My setup: Using django-eventstream, I have the following in my Django container: settings.py - MIDDLEWARE = [ ... 'django_grip.GripMiddleware' ] INSTALLED_APPS = [ 'django_eventstream', ... ] GRIP_URL = 'http://pushpin:5561' urls.py - path('event/logmessage/', include(django_eventstream.urls), {'channels': ['logmessage']}), logutility.py - import logging from datetime import datetime from django_eventstream import send_event from django.core.serializers import serialize def logMessage(level, source, message): from .models import LogMessage logger = logging.getLogger(__name__) if level in ['DEBUG', 'INFO', 'WARNING', 'ERROR']: level = logging.getLevelName(level) logger.debug('Log message received: {0} {1} {2}'.format(logging.getLevelName(level), source, message)) logger.log(level, (source + ' - ' + message)) lm = LogMessage.objects.create(msg_time=datetime.now(), level=logging.getLevelName(level), source=source, msg_text=message) lmjson = serialize('json', [lm]) send_event('logmessage', 'message', lmjson) My web app talks to a frontend container that runs httpd (I know, we're about to switch over to nginx) httpd.conf - ProxyPass /event/ http://pushpin:7999/event/ ProxyPassReverse /event/ http://pushpin:7999/event/ And my React client does the following: componentDidMount() … -
I am unable to connect my expo react native application with django websocket
useEffect(() => { const ws = new WebSocket('ws://127.0.0.1:8000/ws/awsc/'); ws.onopen = (event) => { console.log(event.data) console.log('ws opened') }; ws.onmessage = function (event) { console.log(event.data) }; ws.onclose = function (event) { console.log("closed, code is:", event.code) }; return () => ws.close(); }, []); The following code is unable to establish connection with django web-socket. My django app is running on localhost and my react native app is running on expo app emulator The following code is unable to establish connection with django web-socket. My django app is running on localhost and my react native app is running on expo app emulator I simply want to establish connection of my django websocket with my expo react native app -
Django on Dreamhost failed to install
Did anyone tried to install Django on Dreamhost , i tried different tutorials but failed I tried to install it via ssh but failed. I tried to follow the steps one by one but without any luck -
502 Bad Gateway on my Django app hosted on Elastic beanstalk using Application Load balancer
I am having this issue on my Django web app 502 Bad Gateway ngix/1.20.0 This error occurs whenever I am trying to view any of the task_submitted models or if I want to add another one. Some times it won't display this error, it will work perfectly and some time it will display this error. The app is hosted on elastic beanstalk. I have checked my Django app terminal for any error log but I can't find any logs there. Please help me out 🙏 Thanks in advance If you need any other information about this just let me know I will provide. My model which I am having issue with when viewing or creating new objectsThe error Where can I get the error log and fix the issue.