Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does my template takes forever to load when I change to the remote postgresql database?
This problem is pretty much only prevalent when I use a remote database, but select_related and prematch_related are used in query sets to fetch data, so foreign keys aren't doing it. It's faster when it's using a local sqlite database. Is there any way that i can optimize my template to load faster as there is a lot of data to be displayed there. As there are many separate pages performing the same action the backend just calls a queryset and the data is assigned to a dictionary. The template uses this to be completely dynamic. <!DOCTYPE html> {% load static %} {% load fontawesome %} {% load backend_extras %} {% load bootstrap4 %} <html> {% include "includes/header.html" %} <body style="margin: 0px; border: 0px; padding: 0px; background-color: White;"> {% include "includes/admin-nav.html" with active=name %} {% if name != 'index' %} <div id="modal-bar"> <input type="text" id="modal-search" onkeyup="searchFunc()" placeholder="Search.."> <div class="modal-btns"> <a class="modal-btn" data-modal="modal-window-add"><img src="{% static 'Cobras/imgs/add_button.png' %}"></a> </div> <div id="modal-window-add" class="modal-window modal"> <!-- Modal content --> <form action="" method="post" class="modal-content"> <div class="close">&times;</div> {% csrf_token %} {% bootstrap_form form_add %} <input type="hidden" name="method" value="add"> {% buttons %} <button type="submit" class="btn btn-primary">Submit</button> {% endbuttons %} </form> </div> </div> {% for info in data … -
How To Save An Image From URL Using Django-Allauth?
The user is signing up via the Django-AllAuth and his profile image URL is being extracted. I want then to save this image to ImageField. How do I do that? Here is my code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(default=None, max_length=255) email = models.CharField(default=None, max_length=500) picture = models.ImageField(default='default.jpg', upload_to='profile_pics', max_length=255) def __str__(self): return self.user.username @receiver(user_signed_up) def populate_profile(sociallogin, user, **kwargs): profile = Profile(user=user) if sociallogin.account.provider == 'google': user_data = user.socialaccount_set.filter(provider='google')[0].extra_data picture_url = user_data['picture'] email = user_data['email'] full_name = user_data['name'] profile.picture = picture_url profile.email = email profile.full_name = full_name profile.save() -
djnago unittest: clien.get error 401 even if I send token
I try to create a unittest for method logout, I have this for this purpose: response = client.get('/api/v1/logout') self.assertEquals(response.status_code, 200) but in my logout controller I have this: permission_classes = (IsAuthenticated,) thus I changed my above code to this: response = self.client.post('/api/v1/login', data={'username': 'testuser', 'password': '12345678'}) client = APIClient() client.credentials(HTTP_AUTHORIZATION='Bearer ' + response.json()['access_token']) response = client.get('/api/v1/logout') self.assertEquals(response.status_code, 200) but when I run my test I get 401 as result self.assertEquals(response.status_code, 200) AssertionError: 401 != 200 I am not sure how can I pass token to my request -
send value from anchor tag to views
i have blog field in my project. i want to send the post id in to the views.py tell me what i'm doing wrong in blog.html <a href="{% url 'post-detail' post.id %}" class="btn btn-primary">Read more</a> in urls: path('post_detail/<int:pk>/', PostDetailView.as_view(), name='post- detail') in views: class PostDetailView(DetailView): model = Post def get_queryset(self): queryset = super().get_queryset() search = self.request.GET.get('pk') if search: queryset = Post.objects.filter(page_id=search) print(queryset) else: return queryset.none() -
No module named import_export although it is installed
I'm trying to use django-import-export in my django site. I installed it in my virtual environment using "pip install django-import-export" and I know it's there because I ran pip freeze but it still gives an error when I do eb create django-env: "ModuleNotFoundError: No module named 'import_export'". It is included in INSTALLED_APPS in settings.py and I ran python manage.py collectstatic before I got the eror. 2019-05-26 06:21:41 ERROR [Instance: i-08f7c48c9afd84a8f] Command failed on instance. Return code: 1 Output: (TRUNCATED)...ile "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'import_export'. container_command 01_migrate in .ebextensions/db-migrate.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2019-05-26 06:21:41 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2019-05-26 06:22:44 ERROR Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. I am a beginner and this is my first question on StackOverflow. I appreciate any help. -
Autofield column is not showing in admin database
i have created a model Post class Post(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) image = models.ImageField(upload_to='blog_image', default='default.jpg') smallContent = models.TextField() content = models.TextField() data_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title but id field is not showing in admin panel. i did makemigrations and migrate and both are done successfully. -
Do we have a memory in Django application?
What if I want to store a short data set in the memory of my application? Do we have a memory in Django application or maybe it is better to ask if Django is alive? I know that I can save queries in Redis but I want to know if there is a better and faster way to save data in one view and retrieve those from another view using memory? Is it right or wrong at all? Thanks -
In Django, the button url is called unexpectedly, so I can not find the page
In Django, the button url is called unexpectedly, so I can not find the page i tried click below button but it's not work <button type="button" class="btn btn-outline-info btn-sm float-right" name="button" onclick="location.href='{{fn_id}}/finisher/new'">포스팅</button> url result is Maybe the button does not work because the page that calls url is a detail page and below buuton is work <button type="button" class="btn btn-outline-info btn-sm float-right" name="button" onclick="location.href='http://127.0.0.1:8000/bestlec/{{fn_id}}/finisher/new'">포스팅</button> but That causes problem Because it requests a local address do you know how to slove it?? thanks for let me know~! -
django url doesn't work fine for me when using class based view
i am new to Django, and now i am using Django2.2. The scenario is when user click profile option on menu, and it will take user to their user profile Following is my userprofile model class UserProfile(auth.models.AbstractUser): image = models.ImageField(upload_to=get_image_path, # default="image/default.png", max_length=100, blank=True, null=True, default='account_users/default/profile_image/default.png') class Meta: verbose_name = "account_user" verbose_name_plural = verbose_name def __str__(self): return self.username ```python --------------------------seperate line--------------------------- <ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenu1"> <li><a href="{% url 'account:user_profile_detail' username=userprofile.username %}" class="btn btn-simple">Profile</a></li> </ul> --------------------------seperate line--------------------------- Following is url urlpatterns = [ path("profile/<str:username>/", views.UserDetail.as_view(), name="user_profile_detail"), ] --------------------------seperate line--------------------------- Following is my class based view ```python class UserDetail(DetailView): model = models.UserProfile template_name = "userprofile_detail.html" def get_queryset(self): queryset = super().get_queryset() return queryset.filter( userprofile__username__iexact=self.kwargs.get("username") ) it shows me this following error : AttributeError at /account/profile/sm10547/ Generic detail view UserDetail must be called with either an object pk or a slug in the URLconf. Request Method: GET Request URL: http://0.0.0.0:8000/account/profile/sm10547/ Django Version: 2.2.1 Exception Type: AttributeError Exception Value: Generic detail view UserDetail must be called with either an object pk or a slug in the URLconf. Exception Location: /usr/local/lib/python3.7/site-packages/django/views/generic/detail.py in get_object, line 47 Python Executable: /usr/local/bin/python Python Version: 3.7.2 -
how to fix keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['post/(?P<slug>[^/]+)/$']
I have this error in views.py return super().form_valid(form) in runserver Reverse for 'postdetail' with keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['post/(?P[^/]+)/$'] models.py class Post(models.Model): title = models.CharField(max_length=60) slug = models.SlugField(max_length=60, unique=True) first_image = models.ImageField(null=True, upload_to='post_image') content = RichTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def save(self, *args, **kwargs): super().save(*args,**kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('postdetail', kwargs={'pk': self.pk}) def post_slug(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(post_slug, sender=Post) views.py ......... class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'first_image', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False urls.py ...... urlpatterns = [ ...... path('post/<slug>/', PostDetailView.as_view(), name='postdetail'), ...... ] -
Django ModelForm return empty value with error if user pass empty value
I have some issue with Django ModelForm. if the user passed an empty value to the required field Django ModelForm return empty value with an error. should return the same value as database. Thanks class ProfileForm(ModelForm): first_name = forms.CharField(strip=False, required=True, widget=forms.TextInput) class Meta: model = User fields = ['first_name','middle_name','last_name'] -
Django DateTimeField with auto_now_add asks for default
I have this field in my model created_at = models.DateTimeField( auto_now_add = True ) When I try to make migrations I get an error: You are trying to add the field 'created_at' with 'auto_now_add=True' to user wi thout a default; the database needs something to populate existing rows. 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py I tried to set the default value but it says default and auto_now_add are mutually exclusive. Of course I could just use default without auto_now_add but I want to know why this error pops up. Did I miss something? -
How to configure the project and virtualenv paths in crontab to schedule jobs in Django?
I am using a library called django_cron to schedule tasks with Django. I've already done all the required setup, including, but not limited to adding this chunk of code to the crons.py file: class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 # every 2 minutes. schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'core.my_cron_job' # a unique code def do(self): pass; However, I am having a lot of trouble to configure the contrab command in the contrab editor. I am currently using this command (because I am using a virtual environment): * * * * * source /Users/myame/Desktop/dev/Websites/django_env/bin/activate && python /Users/myname/Desktop/dev/Websites/project/manage.py runcrons I am getting this error: crontab: installing new crontab "/tmp/crontab.kdldvixya8":4: bad minute crontab: errors in crontab file, can't install How can I solve this? What's wrong with it? Thank you in advance. -
Save list of records and fields into django model
I receive this list from my website admin: [['present', '2'], ['present', '3'], ['present', '4'], ['study', '1'], The first option is actually the field name that needs to be edit in Rollcall model and the second option is the user ID. Now I want to save this list to the Rollcall model: #models.py class Rollcall(models.Model): student = models.ForeignKey(User) present = models.BooleanField(default=False) study = models.BooleanField(default=False) So I first check and find the various fields that a particular user has in the list, and then I will save all those fields for one user in my model. How can I do this? -
Unable to connect two call back functions together in dash app
Hello I am working on a dash app for the first time and I am unable to fix an issue that I am facing. I have a front-end that takes the user input, does some calculation, stores the result in a hidden div and then updates the graph. The app loads fine however it runs into an error as soon as I hit the submit button. Below is the code I have written. It looks like both the callback functions triggers at the same time. app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[ html.Div([ html.Div([ html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()), className="nine columns") ], className="three columns"), html.Div([ html.Div([ html.Div([ html.P("Select Month Range:"), ], className="two columns" ), html.Div([ dcc.RangeSlider( id='month_slider', # updatemode='drag', # count=1, min=1, max=maxmarks, step=1, value=[maxmarks - 1, maxmarks], marks=tags, pushable=1 ), ], className="six columns", style={}) ], className="twelve columns", style={ 'backgroundColor': '#EFEAEA', 'padding-top': '1.5em', 'padding-bottom': '1em' }), html.Div([ html.Div([ dcc.Dropdown( id='demographics', options=[ {'label': 'All 18-49', 'value': '18-49'}, {'label': 'Female 25-54', 'value': '25-54F'}, {'label': 'All 25-54', 'value': '25-54'}, ], placeholder="Select Demographics", ) ], className="two columns", style={}), html.Div([ dcc.Dropdown( id='ID', options=[ {'label': '200', 'value': 200, 'type': 'number'}, {'label': '250', 'value': 250, 'type': 'number'}, {'label': '300', 'value': 300, 'type': 'number'}, {'label': '350', 'value': 350, 'type': 'number'}, {'label': '400', 'value': 400, … -
Cors origin Policy blocked When ssl is enabled
I m trying to deploy Angular - Django project on an Azure VM it was working fine without HTTPS but I had to add FCM to the angular project which requires HTTPS since both angular and Django is running same server different ports like angular on *:80 and Django on *:8000 I had set up SSL for both separately I manage to docker it and get it up and running. But then I noticed a very strange bug on Django to enable cors headers I had to add few more options to Django Like SSL_SECURE_REDIRECT, CORS_ORIGIN_ALLOW_ALL, CORS_ORIGIN_WHITELIST. etc. And this is what happens now when I set SSL_SECURE_REDIRECT = True it works on Mozilla and safari NOT In chrome if I change that to False it works only in Chrome Mozilla and safari gives a cross-origin policy error. proxy_pass on nginx - no luck removing SSL_SECURE_REDIRECT - no luck Adding headers - no luck Added Trusted origins - no luck Re-installed CORSHEADERS plugin for Django On Local Its still working Its production so I can't force to users to use any browser Added different setting for production and local deployment - waste of time In postman It works cannot access … -
Django-vote implementation for comment up/down voting system
I am new to Django, and I am trying to implement up/downvotes in a comments app I am building, using django-vote: https://github.com/shanbay/django-vote for the implementation. However, either I am not understanding the django-vote documentation correctly or my implementation is faulty. I've looked through the source code for django-vote on its github but to no avail. I've tried tracing back the faults by having the code print to console at each step, and it seems like the django-vote app isnt actually logging the votes. If that is the case I may just try to build another one from scratch, but am not sure. HTML for the vote buttons: <i class=" vote upvote increment fas fa-chevron-circle-up" data-userid ="{{ request.user.id }}" data-commentid="{{ comment.id }}" data-action='UP' ></i> <i class="vote downvote increment fas fa-chevron-circle-down" data-userid ="{{ request.user.id }}" data-commentid="{{ comment.id }}" data-action='DOWN'></i> JS: $(".increment").click(function(event){ var v = $(this); var action = v.data('action'); var commentID = v.data('commentid'); var userID = v.data('userid'); console.log("vote submitted"); console.log(commentID); console.log(action); console.log(userID); $.ajax({ url: "/comments/vote/", data: { 'csrfmiddlewaretoken' : '{{ csrf_token }}', commentID: commentID, action: action, userID : userID, }, type: 'POST', success: function (data) { console.log(data); console.log("vote success")}, error: function() { console.log('vote failure') } }); }); Django view function: @login_required @require_POST … -
Getting a JsonDecodeError on Jupyter Notebook
I'm setting up a Jupyter Notebook that apply a Machine learning model from the Ibm watson studio API to some datas that are coming from my Postgresql database. While reshaping the data to be readable by the API, a JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) appeared and I can't solve it. This is the full traceback: --------------------------------------------------------------------------- JSONDecodeError Traceback (most recent call last) <ipython-input-114-9d8e7cf98a41> in <module>() 1 import json 2 ----> 3 classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', reshaped).get_result() 4 5 print(json.dumps(classes, indent=2)) /opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/natural_language_classifier_v1.py in classify_collection(self, classifier_id, collection, **kwargs) 152 if collection is None: 153 raise ValueError('collection must be provided') --> 154 collection = [self._convert_model(x, ClassifyInput) for x in collection] 155 156 headers = {} /opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/natural_language_classifier_v1.py in <listcomp>(.0) 152 if collection is None: 153 raise ValueError('collection must be provided') --> 154 collection = [self._convert_model(x, ClassifyInput) for x in collection] 155 156 headers = {} /opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/watson_service.py in _convert_model(val, classname) 461 if classname is not None and not hasattr(val, "_from_dict"): 462 if isinstance(val, str): --> 463 val = json_import.loads(val) 464 val = classname._from_dict(dict(val)) 465 if hasattr(val, "_to_dict"): /opt/conda/envs/DSX-Python35/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 317 parse_int is None and parse_float is None and … -
Django cannot find any valid urlpatterns
I'm trying to include a second urls.py in my main Django urls.py, and it's throwing this error whenever I try to do it: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/user/app/lib/python3.5/site-packages/django/urls/resolvers.py", line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/user/app/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/user/app/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/user/app/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/user/app/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/user/app/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/user/app/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/user/app/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/user/app/lib/python3.5/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/user/app/lib/python3.5/site-packages/django/urls/resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'app.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Here's the main urls.py: from django.urls import … -
Django CreateView With ManyToManyField
I am trying to use a Django CreateView and ultimately update a ManyToMany Field if the user selects a certain value. I can get the form to validate, but ultimately it isn't updating the manytomanyfield in the database. Not sure what I'm doing wrong. I have referenced this similar SO issue, Django ManyToMany CreateView Fields In Both Tables but it was of no help to me. Thanks in advance for any thoughts. My code: class AuthorView(LoginRequiredMixin,CreateView): model = NewAuthor form_class = NewAuthorForm template_name = 'create_author.html' def form_valid(self, form): instance = form.save() if instance.status == 'Submitted': if instance.choice == "Custom": instance.access.add(instance.created_by) instance = form.save() This passes form validation, but doesn't save the created_by value in the manytomany field. I have tried to incorporate form.save(commit=False) and a subsequent form.save(), but that doesn't seem to help either. I am ultimately trying to add the created_by user to the manytomany field, but no luck so far. -
Internal Django Server Error when submitting a new object in a patch request from React form
I am using a multiselect form from react-widgets to allow users to select multiple courses and trying to add the selected courses as a patch request to Django. My multiselect is creating an array called userCourses which seems to correctly be an array of course objects that the user selected. Would it make sense to have CustomUser.courses just be an array of the course IDs since that would be easier to send as a patch? Constructor for React Form constructor() { super() this.state = { user: {}, ... courses: [], userCourses: [], } ... } Multi select form <Multiselect className="signin-input" data = {this.state.courses} textField = "name" userCourses = {this.state.userCourses} onChange = {userCourses => this.setState({userCourses})} /> handleUpdate(){ ... const updatedUser = { ... courses: this.state.userCourses } axios .patch("http://127.0.0.1:8000/api/users/" + myID,updatedUser) .then(res=>{console.log(res);}) } Django Serializers class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('id', 'name', 'description') class UserSerializer(serializers.ModelSerializer): ... courses = CourseSerializer(many=True,required=False) class Meta: model = CustomUser fields = (... 'courses'...) Django Models class CustomUser(AbstractUser): ... courses = models.ManyToManyField(Course, related_name='user_courses',blank=True) I am getting the following error: PATCH http://127.0.0.1:8000/api/users/2 500 (Internal Server Error) Here is the console printing user.courses (before updated courses): courses: Array(1) 0: {id: 1, name: "CS290", description: "Software"} length: … -
Specifying upload_to parameter in the model does not seem to do anything
My model looks like this: class MainSample(models.Model): audio = models.FileField(upload_to='audio') In the following view, I am creating this model's instance and saving it: from .models import MainSample def index(request): MainSample.objects.all().delete() main_sample = MainSample() main_sample.audio = 'audio/main_sample.mp4' # why do I need to prepend this with 'audio'? main_sample.save() context = { 'main_sample': main_sample, } return render(request, 'mediaapp/index.html', context) And next creating an audio element in the template: <!DOCTYPE HTML> <html> <body> <audio controls src="{{main_sample.audio.url}}"</div> </body> </html> The audio file is pre-downloaded and sits in MEDIA_ROOT/audio/. The code works, but I don't understand the purpose of upload_to parameter in the model definition, even after reading about it in the Django docs. It is supposed to append audio path to my MEDIA_ROOT, yet in the view I still need to prepend the value of main_sample.audio with audio/, otherwise the template will not load the audio file. Could someone explain in plain words what does the upload_to does in this context, and if I can possibly get rid of writing audio/ again in my view? -
Preventing dangerous user input from django tinymce
Say we want to use tinymce to allow users to enter HTML formatted input. The django-tinymce package is a handy solution. But to render this later as output, we have to use {{ userinput | safe }} to display it. But do we know for a fact the original user's input is ... safe? What in particular are the kinds of malicious HTML tags we need to be wary of and sanitize? What would be a sound strategy to not strip out the legitimate tags tinymce utilizes while protecting future website users who will be presented with 'safe' user input? -
HTTP Long Polling Django Channels 2.x
I am new to Django channels trying to implement HTTP Long Polling. I tried the documented example here but it doesn't seem to work. class LongPollConsumer(AsyncHttpConsumer): async def handle(self, body): self.room_name = self.scope['url_route']['kwargs']['uuid'] self.room_group_name = 'upvote_' # await self.send_response(200, b"Hello", headers=[ # (b"Content-Type", b"application/json"), # ]) await self.send_headers(headers=[ (b"Content-Type", b"application/json"), ]) print('consumer room_name', self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) # Headers are only sent after the first body event. # Set "more_body" to tell the interface server to not # finish the response yet: await self.send_body(b"i", more_body=True) async def upvote_message(self, event): # Send JSON and finish the response: # async_to_sync(self.channel_layer.group_discard)( # self.room_group_name, # self.channel_name # ) print('inside....upvote_message') await self.send_body(json.dumps(event).encode("utf-8")) and from my views.py I call: room_group_name = 'upvote_' channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( room_group_name, { "type": "upvote.message", "message": { 'actionType': 'WS_NEW_EVENT_RECEIVED', 'data': {} } } ) It prints consumer room_name upvote_ as soon as request is sent and the request is still open which it should be, but, the response is absolutely nothing. I am using Postman to test the long polling endpoint. My questions are: Is the type in views.py correct? I tried upvote_message as well which it doesn't seem to work either. How do I close the connection from server … -
Django giving stack overflow error when applying migrations
I have about 150 tables for this very specific use case. I've made a models folder with "apps" in each of them containing the models. Making the migrations is no problem. Applying them, I get this error: Operations to perform: Apply all migrations: admin, auth, contenttypes, public, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying public.0001_initial... OK Applying public.0002_auto_20190525_1519... OK Applying public.0003_auto_20190525_1519... OK Fatal Python error: Cannot recover from stack overflow. Current thread 0x00000f70 (most recent call first): File "c:\users\yoom\appdata\local\programs\python\python37-32\Lib\contextlib.py", line 130 in __exit__ File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\db\migrations\state.py", line 318 in render_multiple File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\db\migrations\state.py", line 191 in _reload File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\db\migrations\state.py", line 158 in reload_model File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\db\migrations\operations\models.py", line 739 in state_forwards File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\db\migrations\migration.py", line 114 in apply File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\db\migrations\executor.py", line 245 in apply_migration File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\db\migrations\executor.py", line 147 in _migrate_all_forwards File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\db\migrations\executor.py", line 117 in migrate File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\core\management\commands\migrate.py", line 234 in handle File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\core\management\base.py", line 83 in wrapped File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\core\management\base.py", line 364 in execute File "C:\Users\yoom\Code\test\testvenv\lib\site-packages\django\core\management\base.py", line 323 in run_from_argv …