Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF token missing or incorrect error when using accessing from client network
CSRF token missing or incorrect error when using accessing from the client network My python Django web app is deployed in the Nginx server on CentOS 7. It has some ajax POST calls. I have included header : {"X-CSRFToken": '{{ csrf_token }}'}, in every ajax post request. It was working fine when we use the application from any open network/WiFi. But when using in client network, it's failing for ajax POST calls(Intial login is fine). Django logs display the message "WARNING 2021-02-03 14:44:56,895 log 14776 140049620125504 Forbidden (CSRF token missing or incorrect.): /employee". FYI, it's not SSL enabled and it's directly accessed with server IP, which is public. -
How to display row data from a table
I want to display the row data from a table to be displayed as a mail while we click on the row. But my doubt is how can I fetch only that row item(data) from the database and display. Can anyone suggest a possible way for this? -
How to update form with get approval from another specific user in Django?
I want to create a basic approval system in my Django project. In this system there are several ranks, but for this question I only use Lead and Manager. I created forms and this forms are representing limits. Only Lead can fill these forms. But what I want is when a Lead update the form it shouldn't display without Manager's approval. How can I do that? approvals/models.py class DoaTable(models.Model): LIMITS = ( ('Low Risk', 'Low Risk'), (...), ('Strict Credit Check', 'Strict Credit Check'), ('No Credit Check', 'No Credit Check'), ) RANKS = ( ('Analyst', 'Analyst'), ('Senior Analyst', 'Senior Analyst'), ('Lead', 'Lead'), ('Manager', 'Manager'), ('...Officer'), ) rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) limit = models.FloatField() comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) user/models.py class UserProfile(AbstractUser): ... password = models.CharField(max_length=250) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200) ... class Rank(models.Model): rank_name = models.CharField(max_length=200) company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) Ranks in this model is same as Doa table ranks. We assume that user ranks are Lead and Manager for this scenerio. approvals/forms.py class DoaTableForm(forms.ModelForm): class Meta: model = DoaTable fields = ('rank', 'risk', 'limit',) class UpdateDoaTableForm(forms.ModelForm): class Meta: model = DoaTable fields = ('limit',) aprovals/views.py def update_limit(request, id): limiting = get_object_or_404(DoaTable, id=id) form … -
Exporting issues to excel using openpyxl(django) (cant seems to work with fetchall())
def export_as_xls(self, request, queryset): opts = self.model._meta file_name = unidecode(opts.verbose_name) sql_query = '''SELECT COUNT(id) AS No_Of_Report, vendor, country_code, SUM(new_code)*100/SUM(sent) AS 'failure_rate', SUM(case when new_code =0 then 1 ELSE 0 end)*100/sum(sent) AS 'success_rate' FROM sms_statistics WHERE FROM_UNIXTIME(date) >= curdate() - interval 30 day GROUP BY vendor, country_code ORDER BY vendor DESC;''' This is mysql query i used to call for the data in mysql schema field_names = ('No of report', 'Vendor', 'Country Code', 'Failure Rate', 'Success Rate') wb = Workbook() ws = wb.active ws.append(ExportExcelAction.generate_header(self, self.model, field_names)) with connection.cursor() as cursor: cursor.execute(sql_query) objects = list(cursor.fetchall()) for row in cursor.fetchall(): objects = list(row) ws.append(objects) print(ws.append(row)) ws = style_output_file(ws) I think the issue is right here for not being able to export to excel. Im not be using the right method to export the file from action.py response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename={file_name}.xlsx' wb.save(response) return response export_as_xls.short_description = "Reports of Past 30 days" export_as_xls.acts_on_all = True Blockquote I believe this part is fine as i tried exporting an empty file and its working as expexted -
Compare two dates in Django Template
In my template i have the two variable from the view: {{data.purchase_date}} and {{data.approval_granted}}. i would like to check if there are more than two days between the two dates and alert the user. I tried the following: {% if data.trade_date|timeuntil:data.approval_granted > 2 %} Purchase was executed after clearance had expired, investigate possible breach. {% endif %} But it shows nothing. Can you please help me? i am coming from Ruby where this is super easy to do actually. -
Python get two value difference and their remaining percentage
In python i have a two variable like : toatalCount = 4 completedCount = 2 what i actually want is i want 50 as a result what i am getting through this . formula = 100/(toatalCount - completedCount) but when i am having values like: toatalCount = 1 completedCount = 0 or toatalCount = 0 completedCount = 1 it is not working in that case i want only remaining percentage of variables.Please help me related this i am stuck here -
ERR_CONNECTION_REFUSED via localhost access( React -> Django )
I made dev environment underbelow. Container is Docker container. +-----------------------------------------------------+ | ◎http://192.168.1.1:8040/ | | | +---------------------------------------------------------------------------+ | | | [ubuntu] | | | | (192.168.1.1) | | | +-----------------------------------------------+ | | | | | ✖ http://172.17.0.1:8040/ | | | | | | | | | +-------------------------------------------------------------------------+ | || | | | | [container]| | || | | | | (172.17.0.1)| | || +--+--+--+ | | | | || | React | | | | | +--------> nodejs +-----------------------------------------+ | | | | | || | | ✖ http://localhost:8040/ | | | | | | || +--------+ ✖ http://127.0.0.1:8040/ | | | | | | || v v v | | | || +--------+ ++--+--+---+ | | | || | | | | | | +---------+ | +------> nodejs +--------------------------------------->+ Django | | | | | | | || | | ◎ http://localhost:8040/ | | | | | +-+ | || +--------+ ◎ http://127.0.0.1:8040/ ++--+------+ | | | | | || ^ ^ | | | +---+ || +--------+ | | | | | Browser | || | | | | | | | (winPC) +----------> Flask +-----------------------------------------+ | | | | | || | | ◎ http://localhost:8040/ | | | … -
raise exception as http response
I'm using django and vue to write a Programmer. Could I raise an exception as a http response, so I can raise the exception anywhere, and do not need to catch it in the django view function, and then reassemble it into a new http response. Pseudocode try: a = ['0'] b = a[2] except IndexError as e: raise ExceptionAsHttpResponse(status=404, reason='haha') # Not implemented, hope to get your help. after the raise ExceptionAsHttpResponse, the frontend can just accquire the status and reason -
env issue running local version of Django site
I am trying to run a Django project locally on my computer but I keep running into some issues trying to get it started. I installed all dependencies in my anaconda local environment. I'm not sure if maybe my system is not reading read the .env file and how to fix that? I'm juat not sure what's going on here. Any help would be greatly appreciated! Here is the error in my terminal when I try running the server. (FSS_Link) ➜ company_name git:(data-dashboard) python manage.py createsuperuser Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/abelrenteria/Documents/CWC_Website_Code/cwc/config/settings/local.py", line 1, in <module> from .base import * # noqa File "/Users/abelrenteria/Documents/CWC_Website_Code/cwc/config/settings/base.py", line 9, in <module> ROOT_DIR = environ.Path(__file__) - 3 AttributeError: 'module' object has no attribute 'Path' Any ideas on how to fix? Thanks! -
Firebase auth for social sign in in django rest framework
We are developing react native app with django rest framework as backend.We want social sign in using firebase auth. But in that case how will I authenticate tokens in django rest framework? For normal email sign in we are using jwt authentication. Now I am not getting how will I use JWT authentication for users who signed up through our app and firebase authentication for users who signed in using social sign in like google,FB and apple in django rest framework? -
i want to make menu dropdown react js django in section (salary)
I'm trying to menu dropdow reactjs django in the section formgroup (salary): and this is the source code from [github] https://github.com/diogosouza/django-react-logrocket import React from "react"; import Select from 'react-select'; import { Button, Form, FormGroup, Input, Label } from "reactstrap"; import axios from "axios"; import { API_URL } from "../constants"; class NewStudentForm extends React.Component { state = { pk: 0, name: "", address: "", role: "", department: "", salary: "" }; componentDidMount() { if (this.props.student) { const { pk, name, address, role, department, salary } = this.props.student; this.setState({ pk, name, address, role, department, salary }); } } onChange = e => { this.setState({ [e.target.name]: e.target.value }); }; createStudent = e => { e.preventDefault(); axios.post(API_URL, this.state).then(() => { this.props.resetState(); this.props.toggle(); }); }; editStudent = e => { e.preventDefault(); axios.put(API_URL + this.state.pk, this.state).then(() => { this.props.resetState(); this.props.toggle(); }); }; defaultIfEmpty = value => { return value === "" ? "" : value; }; all forms in the code: render() { return ( <Form onSubmit={this.props.student ? this.editStudent : this.createStudent}> <FormGroup> <Label for="name">Name:</Label> <Input type="text" name="name" onChange={this.onChange} value={this.defaultIfEmpty(this.state.name)} /> </FormGroup> <FormGroup> <Label for="address">Address:</Label> <Input type="address" name="address" onChange={this.onChange} value={this.defaultIfEmpty(this.state.address)} /> </FormGroup> <FormGroup> <Label for="role">Role:</Label> <Input type="text" name="role" onChange={this.onChange} value={this.defaultIfEmpty(this.state.role)} /> </FormGroup> <FormGroup> <Label for="department">Department:</Label> <Input type="text" … -
KeyError handling while consuming API
I am consuming the Yelp API and using this detail view to display details of individual restaurants such as the name, rating and price of a restaurant. The detail dictionary is solid for the most part and lets me collect variables to use as context in template. However some restaurants do not provide their 'price' to the API, therefore when accessing this view I get a KeyError because there is no price in some cases. How can I create this dictionary with a None value for price to avoid this error? Or is exception handling with try & except the best solution? def detail(request, api_id): API_KEY = 'unique_key' url = 'https://api.yelp.com/v3/businesses/'+ api_id headers = {'Authorization': 'Bearer {}'.format(API_KEY)} req = requests.get(url, headers=headers) parsed = json.loads(req.text) detail = { 'id': parsed['id'], 'name': parsed['name'], 'rating':parsed['rating'], 'price': parsed['price'], } context = {'detail': detail} return render(request, 'API/detail.html', context) -
Django - add link with custom admin page href
In my Django project, I have created a custom admin page for an app via the get_urls() method. I'd like to add a link to the app's main model index view that will take users to this custom page - however, I'm having some trouble creating this link element correctly and I don't seem to be able to piece together the right way to do it - I'm just left with a Reverse for 'export' not found. 'export' is not a valid view function or pattern name. error. I've set up the admin for the app like so: # my_project/observations/admin.py from django.template.response import TemplateResponse from django.urls import path class ObservationAdmin(SimpleHistoryAdmin, SoftDeletionModelAdmin): change_list_template = 'export_link.html' def get_urls(self): urls = super().get_urls() custom_urls = [ path('export/', self.admin_site.admin_view(self.export_view), name='export') ] return custom_urls + urls def export_view(self, request): context = dict( self.admin_site.each_context(request), ) return TemplateResponse(request, 'export.html', context) and the two templates that are referenced: # my_project/observations/templates/export.html {% extends "admin/base_site.html" %} {% block content %} <div> Some custom content </div> {% endblock %} # my_project/observations/templates/export_link.html {% extends 'admin/change_list.html' %} {% block object-tools-items %} <li> <a href="{% url 'export' %}" class="btn btn-high btn-success">Export</a> </li> {{ block.super }} {% endblock %} Navigating directly to http://localhost:8000/admin/observations/observation/export/ works perfectly, I … -
Django Test: type object has no attribute 'objects'
In my web application, I have locations and respective opening hours. The OpeningHours model looks as follows: class OpeningHours(models.Model): location = models.ForeignKey( Location, related_name='hours', on_delete=models.CASCADE) weekday = models.PositiveSmallIntegerField(choices=WEEKDAYS, unique=True) from_hour = models.PositiveSmallIntegerField(choices=HOUR_OF_DAY_12) to_hour = models.PositiveSmallIntegerField(choices=HOUR_OF_DAY_12) class Meta: ordering = ('weekday', 'from_hour') unique_together = ('weekday', 'from_hour', 'to_hour') def get_weekday_display(self): return WEEKDAYS[self.weekday][1] def get_hours_display(self): return '{} - {}'.format(HOUR_OF_DAY_12[self.from_hour][1], HOUR_OF_DAY_12[self.to_hour][1]) def get_start_hour_display(self): return HOUR_OF_DAY_12[self.from_hour][1] def get_end_hour_display(self): return HOUR_OF_DAY_12[self.to_hour][1] def __str__(self): return '{}: {} - {}'.format(self.get_weekday_display(), HOUR_OF_DAY_12[self.from_hour][1], HOUR_OF_DAY_12[self.to_hour][1]) I'm trying to test a model similar to how I have successfully tested other models in my application: class OpeningHours(TestCase): def create_opening_hours(self, weekday=1, from_hour=12, to_hour=15): self.location = create_location(self) return OpeningHours.objects.create(location=self.location, weekday=weekday, from_hour=from_hour, to_hour=to_hour) def test_opening_hours(self): oh = self.create_opening_hours() self.assertTrue(isinstance(oh, OpeningHours)) self.assertTrue(0 <= oh.from_hour <= 23) self.assertTrue(0 <= oh.to_hour <= 23) self.assertTrue(1 <= oh.weekday <= 7) , but when running the test I get this error message: Traceback (most recent call last): File "<app_path>/tests.py", line 137, in test_opening_hours oh = self.create_opening_hours() File "<app_path>/tests.py", line 134, in create_opening_hours return OpeningHours.objects.create(location=self.location, weekday=weekday, from_hour=from_hour, to_hour=to_hour) AttributeError: type object 'OpeningHours' has no attribute 'objects' I assume this could have to do with the ordering or unique_together metadata, but not sure how to solve this... any pointers in the right direction very … -
Docker Wordpress/Apache behind Docker Nginx - Port Number Issue
I am having problems getting the wordpress docker image working with the nginx docker image. The python/django container works perfectly fine with nginx, but the wordpress/apache one is having problems. I can get to the django site, with https. I cannot get into the wordpress one with https. In fact, when I go to my site site.com/wp, I get back site.com:8080/wp, so for some reason it is coming back through port 8080, and not 443 or 80. I've tried setting the wordpress site as the root location / (in the default.conf file) and it still has the same problem (then I get site.com:8080). The wordpress functionality is normal, I can edit the site as usual. default.conf file for nginx disable_symlinks off; ssl_certificate xxx ssl_certificate_key xxx server { listen 80; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name site.com; location / { proxy_pass http://django:8000; #django container } location /static { alias /path/to/static; } location /wp { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_pass http://wordpress:80; #the wordpress container } } docker yml version: '3.7' services: django: restart: always build: context: . dockerfile: docker-django #django gunicorn server, python image ports: - "8000:8000" wordpress: restart: always build: context: . … -
Django UserCreationForm not Submitting
I have django site that is am currently trying to create a user creation form for. I have following all the steps but something is not happening. When I click the button in my register form it does not submit anything. I also do not see a POST message in the terminal. When I go to the admin portal I also do not see what I have submitted. Views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from .models import StudentCourses from .forms import StudentCoursesForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout def registerPage(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserCreationForm() context = {'form': form} return render(request, 'Courses/register.html', context) HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> </head> <body> <h3>Register</h3> <form method="post"> {% csrf_token %} {{ form.as_p }} </form> <button type="submit">Register</button> </body> </html> -
Django cannot show login error on the page
I am making a login page and testing it. I try to enter the wrong password and hope it can show the error message. But it seems not, it just refreshes the page, how can I show the message error? Here is my code: login.html: <!DOCTYPE html> <html> <body> <h1>Login</h1> <form method="POST" action=""> {% csrf_token%} {% for field in form %} {{ field.label }} {{ field }} {{ field.help_text }} {{ field.errors }} <br></br> {% endfor %} <input type="submit" name="LoginUser"> <a class="button" href="{% url 'home' %}"> Cancel </a> </form> {% for message in messages %} <p id='message'>{{ message }}</p> {% endfor %} <h3>Don't have an account? <a href="{% url 'register' %}">Register</a> </h3> </body> </html> view.py: class register(FormView): template_name = "showList/register.html"; form_class = CreateUserForm; def form_valid(self, form): form.save(); messages.success(self.request, "User had been created."); return redirect('login'); class LoginPage(FormView): template_name = "showList/login.html"; form_class = AuthenticationForm; def form_valid(self, form): username = form.cleaned_data['username']; password = form.cleaned_data['password']; user = authenticate(username = username, password = password); print(user) if user is not None: login(self.request, user); return redirect('home'); Thank you -
Why does my CMD prompt do nothing when I use the "python manage.py runserver" command after activating the virtual environment for my Django project
Not using a virtual environment,on my command prompt, "python manage.py command" works but when I activate the virtual environment and use "python manage.py command" it just goes to the next line without doing anything -
Django - How to turn a Page object to Json
I have this social network project for learning purposes, and I'm trying to add a pagination feature to it. I manage to successfully render all the posts in a page with JavaScript after I turn them into a JSON. The problem is that I get this error: Object of type Page is not JSON serializable when I try to paginate the posts like this: all_posts = Post.objects.all().order_by("-timestamp").all() serialized_posts = [post.serialize() for post in all_posts] paginator = Paginator(serialized_posts, 10) #every page displays up to 10 post page_obj = paginator.get_page(pagenumber) return JsonResponse(page_obj, safe=False) Here is the Post model: class Post(models.Model): autor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default="", related_name="user_post") content = models.TextField(max_length=240) likers = models.ManyToManyField(User, related_name="posts_liked") timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { "id": self.id, "autor": self.autor.username, "content": self.content, "likers": [user.username for user in self.likers.all()], "timestamp": self.timestamp.strftime("%b. %d, %Y, %H:%M %p"), "autor_profile_pic": self.autor.profile_picture } Any ideas on how to work this out? -
django: Unable to get sorl-thumbnail working
I am making a django site where users can upload images and I want to use sorl-thumbnail for thumbnail generation and caching. I am using a container based workflow using podman on a fedora silverblue host. I have setup a memcached cache engine (using the memcached docker image), and can set and get values to and from the cache in django-shell with no issues. I have run the migrate command with sorl-thumbnail added to my installed-apps. I have run the ./manage.py createcachetable command and no errors. I am using pylibmc with: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', } } I have created a model which has the sorl.thumbnail ImageField, although I hope to use a standard imagefield eventually, which I believe is possible. I have checked my postgres database and the thumbnail_kvstore table is created but never populated with any data. I have the following model, view, and template: model... class Image(models.Model): image_file = ImageField(upload_to=user_directory_path) #thumbnail = models.ImageField(upload_to=str(user_directory_path) + '_thumb', null=True) userprofile = models.ForeignKey(ForumProfile, on_delete=models.CASCADE, related_name="images") view...(the get function is added during debugging this issue)... class ForumProfileUploadView(LoginRequiredMixin, FormView): form_class = ImageForm template_name = 'list.html' success_url = reverse_lazy('my-view') def get(self, request, *args, **kwargs): form = self.form_class() message = … -
Getting a KeyVault secret using a GitHub secret
I'm working on an Azure sample and want to use GitHub actions to deploy this Django solution. https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=powershell%2Cclone#1-set-up-your-initial-environment This YAML works: name: Build and deploy Django app to Azure App Service on: push: branches: - master env: WEBAPP_NAME: ${{ secrets.WebApp_Name }} # Set the WebApp name from GITHUB secrets SERVICE_PRINCIPAL: ${{ secrets.AZURE_SERVICE_PRINCIPAL }} KV_NAME: "xxdjangoDemo-KV" KV_SECRET: 'SECRET-KEY' . . . - name: Log in to Azure CLI uses: azure/login@v1 with: creds: ${{ env.SERVICE_PRINCIPAL }} - name: Get Key Vault values uses: Azure/get-keyvault-secrets@v1.0 with: keyvault: ${{ env.KV_NAME }} # Set the name of the KEY VAULT in Azure portal from GITHUB secrets secrets: ${{ env.KV_SECRET }} # comma separated list of secret keys to fetch from key vault id: myGetSecretAction # ID for secrets that you will reference This doesn't: name: Build and deploy Django app to Azure App Service on: push: branches: - master env: WEBAPP_NAME: ${{ secrets.WebApp_Name }} # Set the WebApp name from GITHUB secrets SERVICE_PRINCIPAL: ${{ secrets.AZURE_SERVICE_PRINCIPAL }} KV_NAME: ${{ secrets.KEY_VAULT_NAME }} KV_SECRET: ${{ secrets.KEY_VAULT_SECRET_NAME }} . . . . - name: Log in to Azure CLI uses: azure/login@v1 with: creds: ${{ env.SERVICE_PRINCIPAL }} - name: Get Key Vault values uses: Azure/get-keyvault-secrets@v1.0 with: keyvault: ${{ env.KV_NAME }} … -
Django Rest Framework does not filter after resetting queryset
My url will be something like: ... /? Search = modal. I want to replace the "modal" with empty "" to clean the filter and return all records. Views.py class AnexoExamesViewSet(viewsets.ModelViewSet): search_fields = ['descr'] filter_backends = (filters.SearchFilter,) queryset = AnexoExames.objects.all() serializer_class = AnexoExamesSerializer def get_queryset(self): queryset = AnexoExames.objects.all() search_descr = self.request.query_params.get('search',None) print(search_descr) if search_descr=='modal': queryset = AnexoExames.objects.filter(descr='') return queryset This way it is returning zero results -
django ModelForm extra field
i will like to have extra field in modelForm. From this extra field i will like to pass the value to field in model when save. this is example what i want to get will like to generate name in random name field, and save to database as name models.py from django.db import models class Test2App(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name forms.py from django import forms from .models import test2App class TestForm(forms.ModelForm): class Meta: model = Test2App fields = ['name'] Views.py def add_name(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() return redirect('test_name') else: form = TestForm() return render(request, 'test/add.html', {'form': form}) html <form method="post"> {% csrf_token %} <label for="name">Random Name</label> <button>Generate</button> <input id="name" name="name_test"> {{ form}} <input type="submit" value="Submit"> </form> -
Django Admin Stack Inline Itself (Same Model) Indefinitely
Given the following models class File(models.Model): id = models.AutoField(primary_key=True) class Loop(models.Model): id = models.AutoField(primary_key=True) file = models.ForeignKey(File, on_delete=models.CASCADE, null=True, blank=True) loop = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True) class Segment(models.Model): id = models.AutoField(primary_key=True) file = models.ForeignKey(File, on_delete=models.CASCADE, null=True, blank=True) loop = models.ForeignKey(Loop, on_delete=models.CASCADE, null=True, blank=True) I want to build a nested admin where the user can: User adds a File After adding a File, the user can either directly add a Segment or a Loop If the user directly adds Segment, well it ends there. However, if the user happens to add a Loop, he/she should have an option to again add either the Loop or Segment Something like this: File Segment Loop Segment Loop Loop Segment Segment ..... ..... I have tried the following but it apparently doesn't work. class SegmentInline(nested_admin.NestedModelAdmin): model = Segment class LoopInline(nested_admin.NestedModelAdmin): model = Loop inlines = [SegmentInline, LoopInline] class FileAdmin(nested_admin.NestedModelAdmin): model = File inlines = [SegmentInline, LoopInline] It fails with the following error: NameError: name 'LoopInline' is not defined How do I achieve this in Django Admin? Any workarounds to this? -
Does Django Channels support a synchronous long-polling consumer?
I'm using Channels v2. I want to integrate long-polling into my project. The only consumer I see in the documentation for http long polling is the AsyncHttpConsumer. The code I need to run in my handle function is not asynchronous. It connects to another device on the network using a library that is not asynchronous. From what I understand, this will cause the event loop to block, which is bad. Can I run my handler synchronously, in a thread somehow? There's a SyncConsumer, but that seems to have something to do with Web Sockets. It doesn't seem applicable to Long Polling.