Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i work with SQLite and than switch to MySQL? Django
I would like to start a project that would evantually require MySQL. However it is much easier for me not to use MySQL for now and instead to use SQLite. Is it possible to write the code using SQLite and at the end just switch to MySQL? How difficult is this? -
List model field Django?
I just recently started working on a planner app using Django. I made a new User class that extends Django's User class. This is the code: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): projects = [] The projects list is for all the projects the User has. Below is the model for Project and the view this is used in: class Project(models.Model): title = models.CharField(max_length=60) def dashboard_view(request, *args, **kwargs): if request.user.is_authenticated: context = { 'projects' : request.user.projects } return render(request, 'dash.html', context) else: return redirect('login') This works temporarily, but when I end the server, it turns back into an empty list. Is there any equivalent for this in the form of a model field type? Thanks guys! -
crispy forms tailwind with tabs
I want to have a form with 3 tabs using cripsyformws and tailwind. for now it does not work: my html: {% extends "base.html" %} {% load tailwind_filters %} {% block content %} <div class="max-w-lg mx-auto"> <div class="py-5 border-t border-gray-200"> <h1 class="text-4xl text-gray-800">Create a new company</h1> </div> <form method="post" class="mt-5"> {% csrf_token %} {{ form|crispy }} <button type='submit' class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md"> Submit </button> </form> </div> {% endblock content %} my form: class CompanyModelForm(forms.ModelForm): class Meta: model = Company fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( TabHolder( Tab('company_name' , 'fiscal_end_of_year' , ), Tab('Addrfirm_address', 'Addrfirm_code', 'Addrfirm_country', 'Addrfirm_city', 'Addrfirm_state' ), Tab('AddrShipping_address', 'AddrShipping_code', 'AddrShipping_country', 'AddrShipping_city', 'AddrShipping_state' ), Tab('AddrInvoice_address', 'AddrInvoice_code', 'AddrInvoice_country', 'AddrInvoice_city', 'AddrInvoice_state' ) ) ) self.helper.layout.append(Submit('submit', 'Submit')) My goal is to have 3 tabs for the same form tab1 general info, tab2 shipping address, tab3 invoicing address. Do tailwind permit this with crispy or how should I do this if not -
django standalone script: cannot import name 'Celery' from 'celery'
I am trying to run a standalone Django scipt import os, sys, django proj_path = "/path/to/django-project" import ipdb; ipdb.set_trace() # This is so Django knows where to find stuff. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "boiler.settings") sys.path.append(proj_path) django.setup() When i run It says ImportError: cannot import name 'Celery' from 'celery' (/path/to/django-poject/boiler/celery.py) My folder structure: django-poject -- boiler -- __init__.py -- settings.py -- celery.py -- manage.py __init__.py from .celery import app as celery_app __all__ = ['celery_app'] celery.py import os from celery import Celery import django import sys os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boiler.settings') #This defines the celery app instance redis = 'redis://:pass@localhost:6379/0' app = Celery(dirname, broker=redis, backend=redis ) I am able to run celery using activate virtualenv cd to django-poject celery -A boiler worker --loglevel=debug without any problems But in standalone its creating problems -
Need help translating raw sql query to ORM Django
Django Models that used in projects: class LeadStatus(models.Model): status_id = models.PositiveIntegerField(verbose_name='ID статуса', unique=True) name = models.CharField(max_length=100, verbose_name='Имя', null=True, default='Неизвестный') class Lead(models.Model): lead_id = models.PositiveIntegerField(verbose_name="ID сделки", null=True, unique=True) created_date_time = models.DateTimeField(verbose_name="Время и дата создания сделки", null=True) price = models.IntegerField(verbose_name='Бюджет сделки') current_status = models.ForeignKey(LeadStatus, on_delete=models.SET_NULL, verbose_name='Текущий статус', null=True) class LeadsNote(models.Model): note_id = models.CharField(verbose_name="ID примечания", null=True, unique=True, max_length=64) lead = models.ForeignKey(Lead, on_delete=models.CASCADE) old_status = models.ForeignKey(LeadStatus, related_name='old_status', null=True, blank=True, on_delete=models.CASCADE) new_status = models.ForeignKey(LeadStatus, null=True, related_name='new_status', blank=True, on_delete=models.CASCADE) crossing_status_date_time = models.DateTimeField(verbose_name="Время и дата пересечения статуса", null=True) I am trying to execute the following SQL query using Django ORM tools. He does what i need SELECT leads.id, notes.crossing_status_date_time, old_status.name as old_status, new_status.name as new_status, (CASE WHEN leads.id in ( select leads.id from core_leads where old_status.status_id not in (13829322, 14286379) and new_status.status_id in (13829322, 14286379)) THEN true ELSE false END) as _is_profit FROM core_leadsnote AS notes LEFT JOIN core_lead AS leads ON notes.lead_id=leads.id LEFT JOIN core_leadstatus AS old_status ON notes.old_status_id=old_status.id LEFT JOIN core_leadstatus AS new_status ON notes.new_status_id=new_status.id Using Django subqueries I came up with the following ORM query. But it doesn't work as well as raw sql from django.db.models import OuterRef, Q, Subquery, Case, When, BooleanField from .models import LeadsNote, Lead, CompanyConfig, AmoCompany company = AmoCompany.objects.first() status_config … -
Uvicorn automatically shuts down
Trying to launch uvicorn on a shared hosting server (Linux Debian): uvicorn etebase_server.asgi:application --port 8000 --host 0.0.0.0 --lifespan on uvicorn starts, can handle a couple of HTTP GETs, but then shuts down after 30 secs or so. Here is the error msg: INFO: Started server process [125907] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: Shutting down INFO: Waiting for application shutdown. ERROR: Exception in 'lifespan' protocol Traceback (most recent call last): File "/XXX/etebase/.venv/lib/python3.7/site-packages/uvicorn/lifespan/on.py", line 55, in main await app(scope, self.receive, self.send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in call return await self.app(scope, receive, send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/fastapi/applications.py", line 199, in call await super().call(scope, receive, send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/applications.py", line 111, in call await self.middleware_stack(scope, receive, send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/middleware/errors.py", line 146, in call await self.app(scope, receive, send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/middleware/trustedhost.py", line 34, in call await self.app(scope, receive, send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/middleware/cors.py", line 70, in call await self.app(scope, receive, send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/exceptions.py", line 58, in call await self.app(scope, receive, send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/routing.py", line 555, in call await self.lifespan(scope, receive, send) File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/routing.py", line 526, in lifespan async for item in self.lifespan_context(app): File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/routing.py", line 469, in default_lifespan await self.shutdown() File "/XXX/etebase/.venv/lib/python3.7/site-packages/starlette/routing.py", line 512, in shutdown await … -
Django rest framework avoid rollback on status!=200 responses
I have an APIview used to add users into an application. That apiview will return a 200 when the user is created and a 400 if the user already exists on the application. In any of the cases the apiview should write into a 'events' table the action performed: Events.objects.create(action='user-registration', result='ok/ko', otherinfo='whatever') Seems DRF is designed to do a rollback to any database action whenever a view returns a status code different to 200 in a response. I tried to use a context manager, but not sure if I am doing something wrong, since I don't get the expected result: @transaction.atomic def SaveEvent(**kwargs): with transaction.atomic(): try: Events.object.create(**kwargs) except Exception as e: raise return True class register_user(APIview): def post(self,request): SaveEvent(action='register-user',result='fail',otherinfo='forced fail') return JsonResponse(status=400, data={'status': 'ko','data':'forced fail'}) How can I ensure the Event is persisted into the db even when the response is a status_code=400? -
Why can't I use my docker-compose in windows?
so I was watching a tutorial about microservices in python and we were using docker-compose.yml so In the tutorial, he used docker-compose up in the terminal to run it but for some reasons, it's not working with me like in the tutorial, it was giving different outputs, at first it gave me that docker-compose is not a command then I googled a bit and found a solution saying that I have to install docker-compose and I installed it. then I tried docker-compose f- docker-compose.yml up and I am getting this error (venv) C:\Users\hp\PycharmProjects\MyWorkProjects\admin>docker-compose -f docker-compose.yml up Traceback (most recent call last): File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\docker\api\client.py", line 214, in _retrieve_server_version return self.version(api_version=False)["ApiVersion"] File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\docker\api\daemon.py", line 181, in version return self._result(self._get(url), json=True) File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\docker\utils\decorators.py", line 46, in inner return f(self, *args, **kwargs) File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\docker\api\client.py", line 237, in _get return self.get(url, **self._set_request_timeout(kwargs)) File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\requests\sessions.py", line 555, in get return self.request('GET', url, **kwargs) File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\requests\sessions.py", line 542, in request resp = self.send(prep, **send_kwargs) File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\requests\sessions.py", line 655, in send r = adapter.send(request, **kwargs) File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\requests\adapters.py", line 439, in send resp = conn.urlopen( File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "c:\users\hp\pycharmprojects\myworkprojects\venv\lib\site-packages\urllib3\connectionpool.py", line 394, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1255, in request … -
Generate timezone aware datetimes using django annotate and 'generate_series'
I want to generate weekly intervals from a datetime that account for daylight savings times. Example situation: The first_datetime is 2300 3 Jan UTC and localtime. Daylights savings time shift the local time forward a hour on 12 Jan. Target output: 2300 3 Jan UTC, 2300 10 Jan UTC, 2200 17 Jan UTC, ... The code that I am using currently only moves forward in week intervals, without considering timezone. # Models class Celebration(Models.model): first_datetime = models.Date ... # Managers.py ... Celebration.objects.annotate( start=Func( ExpressionWrapper( F("first_datetime"), output_field=DateTimeField() ), # Find first datetime. end, Value("1 week"), function="generate_series", ), ) Related answer that uses postgres directly: https://dba.stackexchange.com/questions/175963/how-do-i-generate-a-date-series-in-postgresql -
Online Software license Certificate App. (Django)
Objective: A mechanism for creating license certificates with short expiry (7 days) on authenticated API call. Renewed certificate will allow Python web app running on-premises Linux OS to operate seven more days. This will force end-user to provide internet access so that the server can collect compiled data from nodes. A crypto algo will create private key from node’s UUID (dmidecode). Server will have private keys for all registered nodes to sign license certificates with seven days expiry. Python web app will verify certificate expiry using system’s UUID at each startup. A simple way to do this would to use JWT for certificates creation and UUID as secrete key but I want know if there are any open-source lib specialized for this case or is there any other better way to implement this. Note: Linux Node is shipped to the end-user preconfigured with an encrypted drive so users does not have access to python codebase. System Digram -
Collecting django static files for deployment
I developed a django application to handle requests from angular application. Now, should I collect static files for django application while deploying it? python manage.py collectstatic Will my django respond to the requests without staticfiles? Because, I found in many documentations that collectstatic is being performed in the steps to deploy django application. -
Deployement on a Django Api
I'm actually developping a Django Rest API with the djangoRestFramework, I configured followed many tutorials and finally configured it. For the next step, I tried to deploy the API on an Apache web server. Here is my wsgi.py : """ WSGI config for take_care_api project. It exposes the WSGI callable as a module-level variable named application. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os import sys os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'take_care_api.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() My 000-default.conf : LoadModule wsgi_module modules/mod_wsgi_python3.so <VirtualHost *:80> ServerAdmin renoidur@localhost # DocumentRoot /etc/take_care_api/ DocumentRoot /var/www/html Alias /static /api/site/static ErrorLog /api/site/logs/error.log CustomLog /api/site/logs/access.log combined <Directory /api/take_care_api/take_care_api/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess take_care_api python-path=/api/take_care_api/ WSGIProcessGroup take_care_api WSGIScriptAlias / /api/take_care_api/take_care_api/wsgi.py </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet When I tried to access to my django project trought the browser, I received this error: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at renoidur@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.38 … -
Deploy Django Code with Docker to AWS EC2 instance without ECS
Here is my setup. My Django code is hosted on Github I have docker setup in my EC2 Instance My deployment process is manual. I have to run git pull, docker build and docker run on every single code change. I am using a dockerservice account to perform this step. How do I automate step 3 with AWS code deploy or something similar. Every example I am seeing on the internet involves ECS, Fargate which I am not ready to use yet -
Can't get jquery script to work in django admin StackedInline model field
(Sorry this is slightly convoluted) I have 2 django models (recipe and ingredient -- code below). class Recipe(models.Model): title = models.CharField(max_length=200) servings = models.IntegerField() tags = TaggableManager() def __str__(self): return self.title class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, default=None, on_delete=models.CASCADE) name = models.TextField(max_length=50) numerical = models.BooleanField(default=True) quantity=models.IntegerField(default=0) measurement = models.CharField(max_length=20) def __str__(self): return self.name I registered this models so that I can edit ingredients inline from the recipe view within the admin page. (see image) from django.contrib import admin from .models import Recipe, Ingredient from django_summernote.admin import SummernoteModelAdmin class IngredientAdmin(admin.StackedInline): model = Ingredient extra = 0 #exclude = ('urls',) class RecipeAdmin(SummernoteModelAdmin): list_display = ('title', 'servings', 'tags') list_filter = ("tags",) search_fields = ['title', 'tags'] inlines = [IngredientAdmin] summernote_fields = '__all__' class Meta: model = Recipe class IngredientAdmin(admin.ModelAdmin): pass admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient, IngredientAdmin) Now I want to make the ingredient's field quantity disappear if the numerical checkbox is set to False. I was able to do this within the Admin-ingredients's view following this post and copying the Admin change_form.html into <appname>/templates/admin/ingredient/change_form.html and adding the following javascript to the {% block admin_change_form_document_ready %} section. <script> django.jQuery(document).ready(function(){ if (django.jQuery('#id_numerical').is(':checked')) { hide_quantity=false; } else { var elementQuantity = document.getElementsByClassName("form-row field-quantity"); var i; for (i = 0; i … -
passing multiple parameters via Django's {% url %} template tags
I have a code: .html code: <a href="{% url 'someurl' %}?query1=param1&?query2=param2"> views.py code: query1 = request.GET.get('query1','') or None query2 = request.GET.get('query2','') or None I can't get the query2 value. Thank you so much in advance! -
send_mail() got multiple values for argument 'fail_silently' Django contact form only passing message not name or subject
So I'm trying to make a contact form with django, but it works but only with the message, I'm trying to have an area for the senders name and their email as well. here's my working code in my views.py from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings def index(request): if request.method == 'POST': message = request.POST('message') send_mail('Contact Form', message, settings.EMAIL_HOST_USER, ['myemail@gmail.com'], fail_silently=False) return render(request, 'app/index.html') and the html <h3>Contact Form</h3> <form method="post" action="{% url 'index' %}"> {% csrf_token %} <input type="text" name="name" placeholder="Your Full Name." /> <textarea name="message" placeholder="Message..."></textarea> <input type="submit" /> </form> and if I try to set name = request.POST.get('name') underneath the message = request.POST.get('message') and then name after message in the send_mail function I get the error send_mail() got multiple values for argument 'fail_silently' I've checked out the documentation and I've seen several different things but nothing worked the way I needed. -
Django test is not working with primary key
test.py from django.test import TestCase, Client, SimpleTestCase from django.urls import reverse, resolve from .models import BlogappModel from django.contrib.auth import get_user_model from .views import Blogapphome, Blogpostview class TestUrls(SimpleTestCase): def test_list_view_url(self): url = reverse('blogapp') self.assertEqual( resolve(url).func.view_class, Blogapphome) def test_detail_view_url(self): url = reverse('blogpost', args=[1,]) self.assertEqual( resolve(url).func.view_class, Blogpostview) class BlogTest(TestCase): def test_post_detail_view(self): response = self.client.get(reverse('blogpost', args=[1])) self.assertEqual(response.status_code , 200) print('All tests are successful') When I'm running this code it's saying 404 != 200 but as you can see in my urls.py urlpatterns = [ path('', views.Blogapphome.as_view(), name='blogapp'), path('post/<int:pk>/', views.Blogpostview.as_view(), name='blogpost') ] second path is referring to that url but why it's not working in test.py -
Django - Foreign Key - ProtectedError Handling
When facing Cannot delete some instances of model xxx because they are referenced through protected foreign keys yyy what are the best practices? Can I somehow track this specific error and intercept it into simple pop-up window or redirect to custom template? -
How I can make notification system in Django by signals
How I can make a notification system in Django by signals, in which any user add like to the video send a notification to the author who added like to his video, I tried everything and no thing worked with me my model class Video(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) video = models.FileField(upload_to='post-videos', validators=[validate_file_extension]) title = models.CharField(max_length=100) slug = models.SlugField(max_length=250, unique_for_date='publish') is_public = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(Account, blank=True, related_name='likes', default=None) the signals file @receiver(post_save, sender=Video.likes) def update_likes(sender, instance, created, **kwargs): if created == False: instance.video.likes.save() print('like updated!') post_save.connect(update_likes, sender=Video) the notification model that I tried to base on my notification but I filed then I try by signals class Notification(models.Model): NOTIFICATION_TYPE = ((1, 'like')) video = models.ForeignKey("videos.Video", on_delete=models.CASCADE, related_name="noti_video", blank=True, null=True) sender = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=NOTIFICATION_TYPE) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) -
Django CKEditor with Cloudinary
I am creating a blog where I have used Django Ckeditor as Rich Text Editor. Also, I have deployed my app on Heroku and used Cloudinary for media files storage. In the development, it is working fine. The images are uploaded by ckeditor to the media root. But after I deployed, ckeditor isn't uploading the images to cloudinary. My urls.py : from contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.decorators import login_required from django.views.decorators.cache import never_cache from django.conf.urls import url from ckeditor_uploader import views urlpatterns = [ path('admin/', admin.site.urls), # path('ckeditor/', include('ckeditor_uploader.urls')), url(r"^ckeditor/upload/", login_required(views.upload), name="ckeditor_upload"), url( r"^ckeditor/browse/", never_cache(login_required(views.browse)), name="ckeditor_browse", ), path('accounts/',include('authentication.urls')), path('',include('core.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'authentication.views.error_404' handler500 = 'authentication.views.error_500' Media Settings in settings.py # Cloudinary if not DEBUG: CLOUDINARY_STORAGE = { 'CLOUD_NAME': config("CLOUD_NAME"), 'API_KEY': config("API_KEY"), 'API_SECRET': config("API_SECRET") } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' # Media Files MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' # CKEditor Configurations CKEDITOR_UPLOAD_PATH = "blog/uploads/" -
Automatically filling in user into form in Django
I am attempting to automatically assign a user to a questionnaire that they fill out. Here is part of my views.py file: @login_required def questionnaireAnswerView(request): form = QuestionnaireForm(request.POST or None) if form.is_valid(): form.save() return redirect("/accounts/profile/") context = { 'form': form } return render(request, "questionnaire/createNewQuestionnaire.html", context) This is my createNewQuestionnaire.html file: <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>Create</title> </head> <body> <form action="." method="POST">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit Questionnaire" /> </form> </body> </html> Here is my form.py class QuestionnaireForm(forms.ModelForm): class Meta: model = Questionnaire fields = [ 'name', 'organisationType', 'organisationIncome', 'programArea', 'appliedForFunding', 'successfullyFundedBefore', 'sourcesOfIncome', 'planToGenerateIncome', 'skillsToReachTargets', 'processesToRecruit', 'processesToUpskill', 'confidentSpeakingAboutProject', 'knowGoodCharity', 'collectPastSuccessFunding', 'collectPastFailedFunding', 'areasOfAdditionalHelp' ] And finally, this is part of my model.py. I have not shown the types of choices here. class Questionnaire(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, unique=True) name = models.CharField(max_length=254, blank=False, null=False) organisationType = models.CharField(max_length=2, choices=typeOfCharity, blank=False, null=False) organisationIncome = models.CharField(max_length=1, choices=incomeLevels, blank=False, null=False) ... I think I need to make changes to my veiws.py file. In particular, I believe I need to somehow access the form that is returned from the request.POST and then set the currently logged in user as the user required. I have tried passing in the user through to the form … -
Send group message outside consumer
I got a little problem with my django server. After implementing AsyncWebsocketConsumer I noticed that if I send (outside consumer.py) a message to a group only the latest browser client receives the message. If I send a websocket message from the browser, all other clients receive the message. The "channels" topic is kinda new to me so I'm not quite sure I understood the workflow completly. It looks like if I send a group message from consumer.py I need a 'type' which leads to a function which sends the data. But if I send a group message from outside it leads directly to the "send" function and doesn't spread the message to the group. django==3.1.7 channels==3.0.3 channels-redis==3.2.0 consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer class SensorWS(AsyncWebsocketConsumer): async def connect(self): await self.channel_layer.group_add("temp", self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard("temp", self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) data = text_data_json['data'] await self.channel_layer.group_send( "temp", { 'type': 'data_message', 'data': data } ) async def data_message(self, message, type="data_message"): await self.send(text_data=json.dumps({ 'data': message['data'] })) views.py import channels.layers from asgiref.sync import async_to_sync ... ... data = {'mydata': 'testdata'} channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("temp", {"type": 'data_message', 'data': data}) routing.py from django.urls import re_path from . import … -
how to switch between authenticated user and anonymous user in Djnango
I have this kind of view in my web application. and i have two main kids of users which are the suppliers and the admin, i am also trying to make the application usable by normal user but some functions will be restricted, i have made all the functions for the suppliers and admin and was working on the anonymous users. I have a line of code in my view dependent on the request.user, i still want the anonymous users to have access to that page but there is a button in form of an icon which has a login_required decorator, so they will have to login. views.py def products(request): title = "All Products" all_products = Product.objects.annotate( favourited_by_user=Count(Case( When( is_favourite=request.user, then=1 ), # default=0, output_field=BooleanField(), )), ).order_by('-id') context = {"all_products":all_products, "title":title} return render(request, 'core/products.html', context) For the is_favourite, what kind of logic can i make for the anonymous users. -
change boolean field to True after Payment?
i use stripe Api Payment method and i have a boolean filed in my database called ordered set to False i just want it to be True after payment here is my views.py: class OrderSummary(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): order = Order.objects.get(user=self.request.user) #this is to bring the order delivered = order.ordered YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], metadata={ "order_id":order.id, "order":order, "delivered":delivered }, mode='payment', success_url=YOUR_DOMAIN + "/", cancel_url=YOUR_DOMAIN + "/", ) return JsonResponse({'id': checkout_session.id}) and here is after payment webhook views: @csrf_exempt def stripe_webhook(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': #this is to bring the order session = event['data']['object'] customer_email = session["customer_details"]["email"] orders =session["metadata"]["delivered"] orders=True orders.save() print(session) # Passed signature verification return HttpResponse(status=200) but i got this error AttributeError: 'bool' object has no attribute 'save' -
Dajngo model foreign field with conditional
Let's say i have a movie related database and two fields:movie and person. person model can consist of directors, actors and writers and has fields id, name, profession. I know that we can create ForeignKey inside of movie model, pointing to person model, and my question is can fields like actor, director and writer be created or specified inside of movie model, having pointer to personmodel or NULL if that id'd person in not this field relates to?