Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Internal Server Error occurs during using flask
Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application I got that error using flask how can I solve this error Thank you in advance. -
Uncaught SyntaxError: Unexpected identifier at my fetch headers
I try to runserver and it runs but my chrome console identifies error at headers and it does npt execute the add to cart. I have refreshed my page several times. P have even turned off my server and ran my server multiple times but same issues remain. My Cart.js File var updateBtns = document.getElementsByClassName('update-cart') for (var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:',productId, 'action:',action) console.log('USER:',user) if (user === 'AnonymousUser') { console.log('user is not logged in') }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('user is logged in, sending data') var url = '/update_item/' fetch(url, { method:'POST' headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, } body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) }) } This is my views.py which does not execute on my console My views.py from django.shortcuts import render from django.http import JsonResponse import json from .models import * # Create your views here. def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/Store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context = {'items':items, 'order':order} return … -
Virtual Env name not written in terminal when activated
I am using atom text editor and when I am activating my virtual environment the name is not written in the start so while programming I am not aware that the environment is activated or not. The environments in my library are as following. when I activate using command activate MyDjangoEnv but the name of the environment is not shown in brackets like it is usually there. I am always confused that the environment is activated or not while installing the libraries. Following picture explains my issue. -
Writing custom ORM in Django
I was interviewed for a position as a backend developer. What the interviewer said was they don't use Django in particular, "we write our own custom ORMs". What did he mean by that? I kept thinking about what he said. What did he mean by that? What I have understood till now is ORM does most of our work so that we don't need to write SQL queries by ourselves. ORM converts all our Python/Django code into SQL queries which makes it so much easier. My next question might be related to this as well. The interviewer asked whether I can use another architecture while building the app from Django/Django Rest. I asked if he meant another framework. But he said no and said not another framework but another architecture. What did he mean by this? -
Items of a Model are not counting seperatly
I am building a BlogApp and I am stuck on a Problem. models.py class Album(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) file = models.ImageField(upload_to='posts',null=True,blank=True) video = models.FileField(upload_to='videos',null=True,blank=True) views.py def new_story(request): file = Album.objects.filter(user=request.user) context = {'file':file} return render(request, 'mains/new_story.html', context) What i am trying to do :- There are two fields in the Albummodel AND I am trying to count file and video separately. when i count in the template using {{ file.count }} then it count all the files and videos BUT when i try to count separately {{ file.video.count }} then it is not showing. I have no idea, how can i count separately. Any help would be Appreciated. Thank You in Advance. -
Method Not Allowed (POST): Django Todo app
I am working on a Django todo list app that allows you to add and remove tasks and categorize them. There's also a user authentication function to login and signup. I am stuck with a bug when I try to add or remove a task saying "Method Not Allowed (POST) 405 0. I think it's something with the urls, but I kept working on it and still can't resolve it. Here's a link to what I am talking about. The task form is in todoApp/pages/templates/home.html: https://github.com/AdhamKhalifa/COM214-Final-Project/tree/main/todoApp/pages/templates -
Django Rest Framework parse error in PUT API
I'm using DRF (Django Rest Framework) to develop API's I am getting below error. rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0) Everything I have created as per the documentation Below is my code def blog_detail(request, pk): try: single_blog = Blog.objects.get(pk=pk) except Blog.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": if pk: serializer = BlogSerializer(single_blog) return JsonResponse(serializer.data, safe=False) if request.method == "PUT": data = JSONParser().parse(request) serializer = BlogSerializer(single_blog, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) In the above code, GET is working properly PUT is having some errors. I'm using Postman to hit API Data: { "blog_title": "My blog using API", "blog_description": "Update: This is a test blog. UPDATED.", "blog_user_id": 10, "user_name": "admin" } -
How I can pass a model class attribute as a context from a class based view
I want to pass the Post model's title as a context to the template from my class-based view called PostDetailView. This title context would be the title of my template. How I can do this? All the necessary codes are given below plz help. models.py: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.author}\'s Post' views.py: from django.shortcuts import render from .models import Post from django.contrib.auth.decorators import login_required from django.views.generic import ListView, DetailView from django.utils.decorators import method_decorator @method_decorator(login_required, name='dispatch') class PostListView(ListView): model = Post context_object_name = 'posts' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Home' return context class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = '?' return context -
django filter across multiple model fields using predefined choices
I am trying to filter through a model with the choices defined before the filter. store_choices = ( ('harveynichols', 'Harvey Nichols'), ('houseoffraser', 'House of Fraser'), ('selfridges', 'Selfridges'), ('lookfantastic', 'LOOKFANTASTIC'), ('superdrug', 'Superdrug'), ('boots', 'Boots'), ('allbeauty', 'allbeauty'), ('asos', 'asos'), ) class ProductFilter(django_filters.FilterSet): store = django_filters.MultipleChoiceFilter(choices=store_choices) brand = django_filters.MultipleChoiceFilter(choices=brand_choices) price = django_filters.RangeFilter() class Meta: model = Product fields = ['store', 'brand', 'price'] def store_checks(self, queryset, name, store_choices): return Product.objects.filter( Q(store__icontains=store_choices) | Q(storehn__icontains=store_choices) | Q(storehof__icontains=store_choices) | Q( storesf__icontains=store_choices) | Q(storelf__icontains=store_choices) | Q(storesd__icontains=store_choices) | Q(storeboots__icontains=store_choices) | Q(storeab__icontains=store_choices) | Q(storea__icontains=store_choices) ) This does not work and returns no products, I am not sure what variable to use instead of store_choices with the Q(XXX__icontains = ). Any help would be appreciated -
Why is Django trying to insert infinite decimal places into my decimal field?
I had this model: class ErrorReproduction(models.Model): amount = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=65535) class Meta: managed = False db_table = 'error_reproduction' In my view, I was running ErrorReproduction.objects.create(amount=1.0), which gave me the error [<class 'decimal.InvalidOperation'>]. I then read this post, which said that max_digits should be greater than the decimal_places, so I changed the model to this: class ErrorReproduction(models.Model): amount = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=32000) class Meta: managed = False db_table = 'error_reproduction' Now, the same operation in the view gives me: value overflows numeric format LINE 1: ...SERT INTO "error_reproduction" ("amount") VALUES ('1.0000000... ^ Why is the value 1.0 overflowing the decimal field? Is it because of the infinite .00000? How am I supposed to insert values into decimal fields? I have also tried: ErrorReproduction.objects.create(amount=1) ErrorReproduction.objects.create(amount=Decimal(1.0)) ErrorReproduction.objects.create(amount=Decimal(1)) ErrorReproduction.objects.create(amount=float(1.0)) ErrorReproduction.objects.create(amount=float(1)) ErrorReproduction.objects.create(amount=math.trunc(1.0)) ErrorReproduction.objects.create(amount=math.trunc(1)) ErrorReproduction.objects.create(amount=round(1.0, 3)) ErrorReproduction.objects.create(amount=round(1, 3)) -
DJANGO: Save two forms within one class-based view
I have difficulties saving 2 forms within one view the only first one is saving but I cant figure out how to save the second one. Here is my code and issue : models.py class Office(models.Model): name = models.CharField(max_length=100,null=True) Address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name='officeAddress',blank=True,null=True) def __str__(self): return self.name class Address(models.Model): address_line = models.CharField(max_length=60, blank=True) address_line2 = models.CharField(max_length=60, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='District') province=ChainedForeignKey(Province,chained_field="country",chained_model_field= "country",show_all=False,auto_choose=True,sort=True) district=ChainedForeignKey(District,chained_field="province", chained_model_field="province",show_all=False,auto_choose=True,sort=True) class Meta: verbose_name = "Address" verbose_name_plural = "Addresses" forms.py class OfficeModelForm(BSModalModelForm): class Meta: model = Office fields = ['name'] class AddressForm(forms.ModelForm): class Meta: model = Address fields = ['address_line','address_line2','country','province','district'] views.py class OfficeCreateView(BSModalCreateView): form_class = OfficeModelForm second_form_class = AddressForm template_name = 'settings/create_office.html' success_message = 'Success: Office was created.' success_url = reverse_lazy('company:office-list') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['address'] = self.second_form_class return context create_office.html {% load static i18n %} {% load widget_tweaks %} <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ address.media.js }} <div class="modal-body"> <div class="form-group">{% render_field form.name %}</div> <div class="form-group">{% render_field address.address_line %}</div> <div class="form-group">{% render_field address.address_line2 %}</div> <div class="form-group">{% render_field address.country %}</div> <div class="form-group">{% render_field address.province %}</div> <div class="form-group">{% render_field address.district %}</div> <button class="btn btn-primary ms-auto" type="submit">{% trans "Create new office" %}</button> </div> </form> I think I need first to save the … -
How to display both selection (request)and result (return) on the same page
I want to show both request and its result on same page without corresponding to web-server or DB or with asynchronous(?) at each time. For example, a page display author list on the left side, and when an author is clicked, the list of the author’s book title are displayed on right side of same page. The simple method is, I think, that requested author on a page is sent to server (DB), getting the book list on there, building new html file, returning it and display the result on other page. I think it might be better off using jQuery or Javascript, but I’m not sure because of not good in Javascript Please tell me that is it possible and giving something of example code or references. The environment is Python 3.7 Django 2.2 Thank you -
Only allow a field to be edited and NOT written to in Django Rest Framework
so I am trying to create a todo app using the Django rest Framework, and have my models.py as... class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=150) date_created = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) What I want is that when a user inputs their task, I want the completed attribute to be hidden to the user and automatically set that to false. But then allow the user to change to true or false later on. With my current serializer.py.. class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('id', 'task', 'date_created', 'completed') extra_kwargs = { "date_created":{"read_only":True}, # 'completed':{"read_only":True} } And my views.py... class ListView(viewsets.ModelViewSet): serializer_class = serializers.TaskSerializer permission_classes = (IsAuthenticated, permissions.ViewOwnTask) def get_queryset(self): return Task.objects.filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) In my serializer.py, the commented code 'completed':{"read_only":True} allows the user to edit the field and write on that field when uploading, as shown in this image However when I uncomment the 'completed':{"read_only":True} field, the option of writing the completed field disappears however I am not allowed to edit that field. Is there anything such as {"edit_only":True}, allowing the user to edit the field only. If you get my point. Any help would be greatly appreciated. Thanks! -
When to use which, Class-based views, Function-based view or generic veiws
So this is more like a discussion and guideline. When I should use which one(Function/Class/Generic). What are the advantages/disadvantages of one over and another, in which scenario one is the most suitable. Is it possible to handle multiple request with same request method GET/POST/... with a single class based view,i.e handle 2 get request in one class. -
Extremely slow Oauth authentication django-allauth
when I am trying to do sign up: Keeping email verification = "mandatory", via Github it is taking approximate 3-10 minutes for the callback url to load. via email / password sign up, it is taking 3-10 minutes for the url "after" the sign up button to load. Keeping email verification = "none", via Github it is taking approximate 3-10 minutes for the callback url to load. via email / password sign up is happening smoothly. Following are the code files: settings.py: Django settings for config project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-xc-592)no)((2&6grj56rfw$um58(cd(+0zvs2f=ar0wq6&@0=' # 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', 'django.contrib.sites', # new 'userlogin', 'allauth', # new 'allauth.account', # new 'allauth.socialaccount', # … -
Django coverage doesn't cover APITestCase tests
I have a relatively large Django + DRF project with over 400 tests, but I fail to get coverage metrics of over 40%. Here are the results after running tests. From my understanding, there could be a few sources of issues here: (1) The directory structure of our application is weird We've tinkered a bit with our directory structure, here is what it looks like today: core_app - apis - businessapi - models - migrations - serializers - views - tests - business_tests.py - admin.py - urls.py - apps.py - __init__.py - userapi - transactionapi - ... - settings - production.py - celery_apps - ... - ... and here is what our business_tess.py file looks like: class TestBusiness(APITestCase): def setUp(self): self.businessA = BusinessFactory(...) self.businessB = BusinessFactory(...) self.primary_adminA = ProfileFactory(...) self.primary_adminB = ProfileFactory(...) # Create 10 spenders self.spendersA = ProfileFactory.create_batch(...) self.spendersB = ProfileFactory.create_batch(...) # Create 5 admins self.adminsA = ProfileFactory.create_batch(...) self.adminsB = ProfileFactory.create_batch(...) # Authorize self.primary_admin_client = APIClient() self.primary_admin_client.credentials(Accept="application/json") self.primary_admin_client.force_authenticate(self.primary_adminA) ... def test_business_permissions(self): expected_response = {...} sorted_expected = OrderedDict(sorted(expected_response.items())) # Try to access as primaryadmin _, client = authenticate_user(self.primary_adminA.id) response = client.get("url_to_test") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), sorted_expected) (2) Coverage doesn't pick up tests that are accessed through API calls I personally don't … -
manage.py and docker-compose in different directories?
I am no expert with docker and what I want to do I think should not be hard, I simply way to be able to run manage.py commands having my docker-compose in different directory and NOT specifying the location of manage.py when im rnning the command. So right now I have a directory that has a the docker-compose.yml and a folder called backend where the manage.py file is. I just want to be able to run docker-compose run --rm web python3 manage.py instead of docker-compose run --rm web python3 backend/manage.py How can I do it? -
Why is my log file not outputting my debug messages? (Django)
When I have my server locally output a log it works, but when I upload to the live environment I only see major errors and the selection of tables in my DB. Logging code in my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'debug.log'), }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } My views.py: def home(request): log = logging.getLogger('django') log.debug('test') return render(request, 'qit/index.html') debug.log output: (0.001) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1; args=(1,) (0.001) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2021-05-16T00:07:46.570887+00:00'::timestamptz AND "django_session"."session_key" = 'mn3oumf41ryqi9h7v9n3g33isk0hoxsk'); args=(datetime.datetime(2021, 5, 16, 0, 7, 46, 570887, tzinfo=<UTC>), 'mn3oumf41ryqi9h7v9n3g33isk0hoxsk') (0.001) SELECT "qit_queue"."id", "qit_queue"."owner_id", "qit_queue"."queue_string", "qit_queue"."name_string", "qit_queue"."anon_string", "qit_queue"."thumbnail_string", "qit_queue"."invite_code", "qit_queue"."password" FROM "qit_queue" WHERE "qit_queue"."invite_code" = 'esMou'; args=('esMou',) (0.001) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2021-05-16T00:07:57.077838+00:00'::timestamptz AND "django_session"."session_key" = 'mn3oumf41ryqi9h7v9n3g33isk0hoxsk'); args=(datetime.datetime(2021, 5, 16, 0, 7, 57, 77838, tzinfo=<UTC>), 'mn3oumf41ryqi9h7v9n3g33isk0hoxsk') (0.001) SELECT "qit_queue"."id", "qit_queue"."owner_id", "qit_queue"."queue_string", "qit_queue"."name_string", "qit_queue"."anon_string", "qit_queue"."thumbnail_string", "qit_queue"."invite_code", "qit_queue"."password" FROM "qit_queue" WHERE "qit_queue"."invite_code" = 'esMou'; args=('esMou',) Unfortunately the test does not show up on my debug.log file. If anyone has any … -
Automatically adding html in Django
I am making use of the {% extends 'core/base.html %} tag to include a header. I write this on the beginning line of each page I create so that it loads a navigation bar and other static files. Is there a way to not write the extends functionality on each page I create and instead it is injected automatically each time I create a page? -
sort dict of list based on max of values in list
I several models (ModelB, ModelC, ....) that have last_updated fields in all of them. They also share id values between them. So if I retrieve id=11, it will have last_updated values for each of the Models. I am trying to sort the id (and associated dict/list) according to the most recent last_updated value in each id. How I am getting the initial id ids = ModelA.objects.values_list('id', flat=True).filter(u=val1) ids returns <QuerySet [11, 12, 13, 14]> How I'm getting last_updated for each of the models updates = {} for i in ids: updates[i] = [] for my_models in (ModelB, ModelC): updates[i].append(my_models.objects.values_list('last_updated', flat=True).get(id=i)) Example output of updates { 11:[ datetime.datetime(2021, 5, 13, 17, 13, 15, 849356, tzinfo=<UTC>), datetime.datetime(2021, 5, 13, 19, 12, 24, 978689, tzinfo=<UTC>)], 12:[ datetime.datetime(2021, 5, 14, 0, 0, 4, 906100, tzinfo=<UTC>), datetime.datetime(2021, 5, 15, 0, 16, 20, 995024, tzinfo=<UTC>)], 13:[ datetime.datetime(2021, 5, 13, 3, 31, 14, 738902, tzinfo=<UTC>), datetime.datetime(2021, 5, 13, 2, 58, 0, 375691, tzinfo=<UTC>)], 14:[ datetime.datetime(2021, 5, 15, 19, 40, 24, 732034, tzinfo=<UTC>), datetime.datetime(2021, 5, 14, 0, 52, 27, 199480, tzinfo=<UTC>)] } How I'm selecting the max and sorting the ids based on the max datetime value. sort_ = {} for k in updates: sort_[k] = max(updates[k]) new_order … -
Django login not working even for django-admin
I know this question has been asked many times before but I am facing quit a unique satiation. My djagno project was working completely fine and I was able to login. But then I start working on django SSO so I had to install some cas packages and ran migrations. But then after some time I uninstall those packages and reset the project as it was before but when I tried to login I wasn't able to login, not even able to login to django admin section. I don't think there is a need of code snippet as I have some thing which was working before and not working now but to give you some idea about my login view. here is the code user = authenticate(request=request, username=request.POST['email'].lower().strip(), password=request.POST['password']) if user is None: return render_error('Sign in failed! Please try again.') else: login(request, user) # Redirect to 'next' url if it exists, otherwise index if 'next' in request.GET: return HttpResponseRedirect(request.GET['next']) -
Related object doesn't exist during _fixture_teardown using factory_boy in tests
I've setup a django test suite, using factory_boy to handle models. In tests where a related object is involved through a ForeignKey, I'm seeing an error suggesting that the related object doesn't exist during _fixture_teardown. And I can't understand why, given this is part of teardown. The error is; Traceback (most recent call last): File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/test/testcases.py", line 284, in _setup_and_call self._post_teardown() File "/Users/mwalker/Sites/consoles/project/tests/mixins.py", line 10, in _post_teardown super()._post_teardown() File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/test/testcases.py", line 1006, in _post_teardown self._fixture_teardown() File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/test/testcases.py", line 1248, in _fixture_teardown connections[db_name].check_constraints() File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 285, in check_constraints cursor.execute('SET CONSTRAINTS ALL IMMEDIATE') File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/mwalker/Sites/consoles/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) django.db.utils.IntegrityError: insert or update on table "charity_listing" violates foreign key constraint "charity_listing_client_id_c3b74de6_fk_clients_client_id" DETAIL: Key (client_id)=(1) is not present in table "clients_client". So far, I'm only seeing this error from the Client table, but my tests are still very limited in scope. The failing test from the above error is; class ApplicationTest(TestCase): @classmethod def setUpTestData(cls): client = ClientFactory.create(name='Stackoverflow', enabled=True) listing … -
Initial dynamic data for django database
I want populate my database with initial data (dummy data). I have DateTimeFields in many models and for the DateTimeFields it would be good to have a variable in my fixtures files (json, yaml, xml). E.g.: now() + 7h, now() + 6d + 8h + 30m -
Heroku Database
Good day, I have a Django app that I hosted on Heroku with the codes from GitHub, it deployed fine and I have a domain, for instance myapp.herokuapp.com. But when I make some changes to the website itself, everything seems alright, then I make changes in the code and push it to GitHub. It deploys again perfectly, but all the former changes I made on the website get discarded, it now looks like a fresh deployed app. Auto-deploy from GitHub is enabled in my Heroku settings. how can I retain changes I make on the Heroku website after updating my code?? -
Django Channels Redis: Exception inside application: Lock is not acquired
Fully loaded multi-tenant Django application with 1000's of WebSockets using Daphne/Channels, running fine for a few months and suddenly tenants all calling it the support line the application running slow or outright hanging. Narrowed it down to WebSockets as HTTP REST API hits came through fast and error free. None of the application logs or OS logs indicate some issue, so only thing to go on is the exception noted below. It happened over and over again here and there throughout 2 days. Don't expect any deep debugging help, just some off-the-cuff advice on possibilities. Thanks. AWS Linux 1 Python 3..6.4 Elasticache Redis 5.0 channels==2.4.0 channels-redis==2.4.2 daphne==2.5.0 Django==2.2.13 Split configuration HTTP served by uwsgi, daphne serves asgi, Nginx May 10 08:08:16 prod-b-web1: [pid 15053] [version 119.5.10.5086] [tenant_id -] [domain_name -] [pathname /opt/releases/r119.5.10.5086/env/lib/python3.6/site-packages/daphne/server.py] [lineno 288] [priority ERROR] [funcname application_checker] [request_path -] [request_method -] [request_data -] [request_user -] [request_stack -] Exception inside application: Lock is not acquired. Traceback (most recent call last): File "/opt/releases/r119.5.10.5086/env/lib/python3.6/site-packages/channels_redis/core.py", line 435, in receive real_channel File "/opt/releases/r119.5.10.5086/env/lib/python3.6/site-packages/channels_redis/core.py", line 484, in receive_single await self.receive_clean_locks.acquire(channel_key) File "/opt/releases/r119.5.10.5086/env/lib/python3.6/site-packages/channels_redis/core.py", line 152, in acquire return await self.locks[channel].acquire() File "/opt/python3.6/lib/python3.6/asyncio/locks.py", line 176, in acquire yield from fut concurrent.futures._base.CancelledError During handling of the above exception, …