Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rarely get SynchronousOnlyOperation error in different GET requests which have database query in Django 3.2.6
Error occurs only in development server environment, cant reproduce it in local. Dev server is a docker composed environment with Django 3.2.6, python 3.7, gunicorn (for wsgi), daphne (for asgi), postgres 12, redis, celery & celery-beat inside. Error happens in GET requests which are not supposed to have any async context. For example, log of one of these errors: gunicorn_1 | [2022-12-07 13:40:21 +0000] [24] [DEBUG] GET /api/v2/sync/groups gunicorn_1 | Internal Server Error: /api/v2/sync/groups gunicorn_1 | Traceback (most recent call last): gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner gunicorn_1 | response = get_response(request) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response gunicorn_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view gunicorn_1 | return view_func(*args, **kwargs) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view gunicorn_1 | return self.dispatch(request, *args, **kwargs) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch gunicorn_1 | response = self.handle_exception(exc) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception gunicorn_1 | self.raise_uncaught_exception(exc) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception gunicorn_1 | raise exc gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 497, in dispatch gunicorn_1 | self.initial(request, *args, **kwargs) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 414, in initial gunicorn_1 | self.perform_authentication(request) gunicorn_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", … -
Not sending messages to db
When I try to send messages to a temporary email address, it arrives there but does not go into the django database. view.py def about(req): form = MessangeForm() if req.method == "POST": form = MessangeForm(req.POST) if form.is_valid(): subject = form.cleaned_data.get('title') body = form.cleaned_data.get('body') try: send_mail(subject, body,settings.EMAIL_HOST_USER, ["nakkosikni@gufum.com"], fail_silently=False) form.save() except Exception as err: print(str(err)) return redirect('index') return render(req, "about.html", {"form": form}) models.py ``` class Messange(models.Model): title = models.CharField(verbose_name='Subject', max_length=250, null=True, blank=True ) body = models.TextField(verbose_name='Body') def __str__(self): return f'(self.body)' forms.py class MessangeForm(ModelForm): class Meta: model = Messange fields = ["title", "body"] widgets = { "body": forms.Textarea(attrs={'class': 'form-control'}), } When I click on submit button I get this error. [07/Dec/2022 21:20:12] "GET /about HTTP/1.1" 200 2332 ОШИБКА: неверный синтаксис для типа time: "rtjyfukugil" LINE 1: ..._messange" ("title", "body") VALUES ('hjdfhjehf', 'rtjyfukug... I don't understand what needs to be changed there. -
How to render thousands of a model objects in fraction of seconds in django?
Suppose, I have a model "Student" in my django application. Now, i already have 10k student registered in my portal and i want to render all the objects at a time in a template. But the issue is, this rendering process takes a lot of time to list all the students. So, how we can make an overcome ? Consider the worst case scenario, The database have millions of students. -
Django :Retrive files from django model with signed urls from different buckets
Hope evryone doing good I want to upload some files in different buckets , and the bucket names are also stored in adjescent django field in same table. How can i retrieve that bucket name and use for upload in storage option in FileField ,The below is my table looks like class TestFileField(models.Model): id = models.AutoField(primary_key=True,blank=True,null=True) name = models.CharField(max_length=30,null=True,blank=True) **bucketname** = models.CharField(max_length=30,null=True,blank=True) sourcefile = models.FileField(upload_to=get_upload_path, blank=True,storage = GoogleCloudStorage(bucket_name = **bucketname <-- i want a value which stored in the above bucketname field** )) Or Im also trying like this, @deconstructible class CustomBucketSelection(GoogleCloudStorage): def __init__(self,*args,**kwargs): kwargs['bucket_name'] = 'mubuckey' or settings.bucket super(CustomBucketSelection,self).__init__(*args,**kwargs) def url(self, name): bucketname = current_instance.bucketname ----------------------------- i want current instance here to fecth th bucket name or credentials which stores in same database like this once i got bucket name i will generate signed url and returns that url ----------------------------------- return urll class TestFileField(models.Model): id = models.AutoField(primary_key=True,blank=True,null=True) name = models.CharField(max_length=30,null=True,blank=True) bucket_name = models.CharField(max_length=30,null=True,blank=True,default=settings.GS_BUCKET_NAME) # filename = models.FileField(upload_to=get_upload_path, blank=True,storage = CustomBucketSelection) Actually the thing is while im saving files its perfectly storing but while im retriving the files, i want signed urls with that corresponding storage buckets , so im trying like this, Please confirm me that is it possible … -
Django rosetta is saving translation but not showing new translations until the server (docker) restart
I'm using rosetta with default settings and it shows new translations in local server(no docker). but in production, I'm using docker and it's not showing updates until restart. docker-compose.yml: version: '3' volumes: production_postgres_data: { } # django production_temp_data: { } production_media: { } production_static: { } production_locale: { } services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile volumes: - production_temp_data:/tmp/ - production_media:/app/media/ - production_static:/app/staticfiles/ - production_locale:/app/locale/ depends_on: - postgres env_file: - ./.env command: /start restart: always logging: driver: "json-file" options: max-size: "100m" max-file: "10" ... django start command: #!/bin/bash set -o errexit set -o pipefail set -o nounset python /app/manage.py collectstatic --noinput python /app/manage.py makemessages --all --ignore=venv python /app/manage.py compilemessages --ignore=venv /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 -w 1 --threads 1 --access-logfile - --error-logfile - --log-level info --capture-output --enable-stdio-inheritance --chdir=/app --timeout 180 django==4.1.3 gunicorn==20.1.0 django-rosetta==0.9.8 There is no logs to debug. tried with ROSETTA_WSGI_AUTO_RELOAD=True but it didn't work. -
Wrong installed virtualenv
I wanted to intall virtualenv in CMD (Windows 11). Unfortunately it was downloaded in the place I did not want to install it (it was supposed to be installed on D but it was installed on C. Also the folder i was expecting to be created was not created. What should I do to completly get rid of it from my computer? That is what occured after typing "virtualenv django" in CMD (django is the name of the folder which was supposed to be created): created virtual environment CPython3.11.0.final.0-64 in 1709ms creator CPython3Windows(dest=D:\django, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\mmilk\AppData\Local\pypa\virtualenv) added seed packages: pip==22.3.1, setuptools==65.6.3, wheel==0.38.4 activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator I chose the folder I wanted to install the program typed "virtualenv django". Later on the program introduced me where is the whole data which was created. It was on C instead of D. Is it true if I turn off the computer the virtualenv gets deactivated? Can I download it once again but this time on the completly different drive? For example the wrong virtualenv on C, the correct virtualenv on D. I'd only work on the virtualenv on the D drive. -
Django Polls Tutorial No answer detected in choice.votes polls
I decided to learn Django and started with the 'Django Polls App' which I figured would be the most simple, I am gripping the idea of how it works but I am stuck. To learn a bit better, I changed the variables and names from the original docs to my own. Example : question_text = q_text, Choice = Choices, choice_text = choice.. etc. Now I can't figure out what's wrong with my code as I can't make the polls work. There is no error code but it simply doesn't display the number of votes or show a success sign. I was also following Traversy Media's Django Crash Course (Polls App). My code : views.py from django.http import Http404, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from django.template import loader from .models import Question, Choices def index(request): latest_ques = Question.objects.order_by('-published')[:5] context = {'latest_ques': latest_ques} return render(request, 'polls/index.html', context) def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choices_set.get(pk=request.POST['choices']) except (KeyError, Choices.DoesNotExist): return render(request, 'polls/detail.html', { 'question': … -
How to retrive image from django database?
I saved image in database, there are multiple images and i want to retrive it in my website. my image is stored in static folder inside app folder that is card/static/images. my images is showing when i enter link http://127.0.0.1:8000/images/p.jpeg this is my urls.py ` urlpatterns = [ path('admin/', admin.site.urls), path('', include('card.urls')), path('index/', include('card.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is my models.py class dish(models.Model): dish_name = models.CharField(max_length=255) dish_size = models.CharField(max_length=7) dish_price = models.IntegerField() dish_description = models.CharField(max_length=255) dish_image = models.ImageField() dish_date = models.DateField() this is my index.html file <img src="{{ request.dish.dish_image.url }}" height="100px" width="100px"> this is my setting.py STATIC_URL = 'static/' MEDIA_URL = 'images/' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'card/static/images') ` -
Python/Django MakeMigrations Error Traceback
Here is what appears when i try to use python manage.py makemigrations traceback error Here is models.py code ----------------------code------------------------------------- from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: verbose_name_plural = 'categories' # def get_absolute_url(self): # return reverse("store:category_list", args=[self.slug]) def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator') title = models.CharField(max_length=255) author = models.CharField(max_length=255,default='admin') description = models.TextField(blank=True) image = models.ImageField(upload_to='images/') slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=4, decimal_places=2) in_stock = models.BooleanField(default=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.title ------------------code end------------------------------- im new and i dont know whats the problem -
'ForwardManyToOneDescriptor' object has no attribute 'user_type'
Models.py class UserType(models.Model): owner=models.ForeignKey(User,on_delete=models.CASCADE,default=1) user_type=models.CharField(max_length=20,default='admin') Views.py def register(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') fname = request.POST.get('firstname') lname = request.POST.get('lastname') email = request.POST.get('email') newpass = make_password(password) newuser = User.objects.create(username=username,password=newpass,first_name=fname,last_name=lname,email=email) newuser.save() usertype = request.POST.get('usertype') newtype = UserType.objects.create(user_type=usertype) newtype.save() messages.success(request, "Registration successful") if UserType.owner.user_type == 'Student': return redirect('Stuproadd') elif UserType.owner.user_type == 'Teacher': return redirect('Teachproadd') else: return redirect('index') return render(request, 'register.html') register.html <body> <h1>Register</h1> <div class="container"> <form method="post"> {% csrf_token %} <label>Username:</label> <input type="text" name="username" placeholder="Enter your username" required /><br><br> <label>First Name:</label> <input type="text" name="firstname" placeholder="Enter First Name" required /><br><br> <label>Last Name:</label> <input type="text" name="lastname" placeholder="Enter last name" /><br><br> <label>Email:</label> <input type="text" name="email" placeholder="Enter your email" required /><br><br> <label>password</label> <input type="password" name="password" placeholder="enter your password" required /> <br><br> <label>confirm password</label> <input type="password" name="password" placeholder="confirm your password" required /> <br><br> <label>Select your Role:</label> <input type="radio" name="usertype" value="Student"> <label>Student</label> <input type="radio" name="usertype" value="Teacher"> <label>Teacher</label> <button type="submit">Register</button> Already User,<a href="{% url 'index' %}">Login Here</a> </form></div> </body> This is the code.I'm getting error as 'ForwardManyToOneDescriptor' object has no attribute 'user_type' After clicking register button, I want to go to stuproadd when the user type is student and teachproadd when the user type is teacher. How is it? pls help -
Django : meaning of {% url 'zzz' %}?{{ yyy }}?
I came across a code in a HTML file and I did not understand how it works. {% url 'calendar' %}?{{ prev_month }} Especially, what does the "?" mean? And how is the code interpreted? It is used in a button to switch between month but I cant figure out how it works. I tried to print different places in the code to see what is executed with but I did not find anything interesting. Thanks -
how to output data from a linked table in django?
I have a built-in User table and a Note table associated with it by key. class Note(models.Model): header = models.CharField(max_length=100) note_text = models.TextField() data = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) That is, a registered user may have several notes. How do I get all these notes from this particular user (who has now visited his page)? I need to get these notes in views.py. I tried different ways, don't know how to do that. -
create a subarray of products with unique username (django)
I need an array of customer orders where username are unique and the order quantity should be added on. I got the result using annotate but I need an subarray with product name and respective quantity as sub array. Please check the outputs I got and outputs required below. Thanks in advance views.py orders = Order.objects.values('staff_id', 'staff__username', 'product__name').annotate(quantity=Sum('order_quantity')).order_by() models.py class Product(models.Model): name = models.CharField(max_length=100, choices=PRODUCTS, null = True) quantity = models.PositiveIntegerField(null = True) class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) order_quantity = models.PositiveIntegerField(null=True) Output: [ { "staff_id":15, "staff__username":"John", "product__name":"samsung", "quantity":2 }, { "staff_id":15, "staff__username":"John", "product__name":"apple", "quantity":18 }, { "staff_id":16, "staff__username":"test", "product__name":"apple", "quantity":100 } ] Output required [ { "staff_id":15, "staff__username":"John", "product": [ { "product__name":"samsung", "quantity":2 }, { "product__name":"apple", "quantity":18 } ] }, { "staff_id":16, "staff__username":"test", "product": [ { "product__name":"apple", "quantity":100 } ] } ] -
How to merge two model in one fieldset in django admin module
I have two table like below tableA field1 field2 field3 tableB field4 field5 Group 1 field1: textfield (tableA) field3: textfield (tableA) field5: textfield (tableB) Group 2 field2: radiobutton (tableA) field4: textfield (tableB) I tried the solution like form inlines but I want the grouping of fields in one form, not a separate inline form. -
Any help, on why is returning the same status in every object here?
So I have a search endpoint here which will fetch the users that contains certain entry and check if there is any on going friends relationship. My endpoint: path('filter/', SearchUserByStringAPIView.as_view()), My View: class SearchUserByStringAPIView(ListAPIView): queryset = User.objects.all() serializer_class = UserProfileSerializer permission_classes = [IsAuthenticated] def get_queryset(self): queryset = self.queryset.filter(username__icontains=self.request.query_params.get('search')) return queryset My Serializer: class UserProfileSerializer(serializers.ModelSerializer): friendship = serializers.SerializerMethodField() def get_friendship(self, obj): user_obj = self.instance.values_list('id') friends_obj = Friend.objects.filter(Q(receiver=self.context['request'].user) | Q(requester=self.context['request'].user)).values_list('requester', 'receiver', 'status') if not friends_obj: pass else: for f in friends_obj: for i in user_obj: if int(i[0]) in f: return str(f[2]) pass class Meta: model = User fields = ['id', 'username', 'about_me', 'avatar', 'friendship'] My Response : [ { "id": 2, "username": "BB", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 3, "username": "BiG", "about_me": "", "avatar": "http://127.0.0.1:8000/media-files/BigG/Screen_Shot_2022-11-14_at_22.06.55.png", "friendship": "A" }, { "id": 7, "username": "babybabybear", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 13, "username": "shadabjamil", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 14, "username": "sirberkut", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 17, "username": "buddlehman", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 20, "username": "tforbes", "about_me": "", "avatar": null, "friendship": "A" }, { "id": 30, "username": "ol99bg", "about_me": "", "avatar": null, "friendship": … -
How to send mail from users Gmail with Oauth in django
I'm currently working on website project. It's intended to be used by business owners to send invoices to their customers. Each owner is a django user model instance and have an organization model associated to them. Now I don't know how to ask permission from owner to give me access to him account and used these credentials to send invoices to customers. I'm working with django and drf. A minimalist HTML CSS and JavaScript are used for front. I had already done mail sending with Gmail but only for desktop app and I needed to save app credentials to filesystem. Does exist anyway to do it with web app ? Thanks in advance. -
Why doesn't show profile picture from the database?
setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py profile_photo = models.ImageField(null=True,blank=True,upload_to='upload') everything all my pages - my question pages here my database problem I have tried many times and search everything in here. but not yet show profile_image in database. Can anyone tell me what's problem in my page? -
Using Flex To Create a 3x2 Grid | Django Template for loop
I am using Django Templating for my blog, and am adding cards using a for loop. I am trying to create a 3x2 structure of the added cards. Currently, each card takes up an equal amount of space within the div. I am trying to model what they have at Ahrefs Blog. That similar sort of structure for their most recent 6 posts. This is my HTML/Bootstrap 5 code: <div class="latest-articles"> {% for post in post_list %} <div class="card mb-4 mx-3 publishedPost"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text">{{ post.author }} | {{ post.createdOn }}</p> <p class="card-text">{{post.content|slice:":200" }}</p> <a href="{% url 'post_detail' post.slug %}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% endfor %} </div> This is my CSS code: .latest-articles { display: flex; flex-wrap: wrap; flex-direction: row; justify-content: center; align-items: stretch; padding-top: 0; text-align: center; position: relative; padding: 10px; } .publishedPost { flex: 1; } Any help is massively appreciated -
Pass data in body of API request
I need to update some info in my database using PUT request and Django rest framework So i have this urls and i need to update max_date parameter (pass True or False) but i have 0 ideas how to do it without passing a variable in the url, like api/config/max_date/<str:bool> -
How do I put django cms plugins classes inside multiple files instead of just putting it all inside cms_plugins.py?
So I have a project where I am using Django CMS as the root of my project. First of all I'm new to Django CMS, and I now want to code some plugins to put into my pages. I searched for the solution but everywhere it says that I should put it inside cms_plugins.py. I tried creating a folder named cms_plugins and created an __init__.py file inside it. Then I created the plugin inside a file named ThePlugin.py and coded my plugin the same way I did it in cms_plugins.py. Unfortunately it's not working. If someone can help me I'd be really gratefull. Thanks. -
Is Django only good for web applications where a user logs in? [closed]
Is Django only good for web applications where a user logs in? The reason I ask is because I recently learned Django and built a website where a user could sign up, input their measurements, and the website tells them how many calories they should eat. Is there a way to build this website in a way where the user doesn't need to sign up or log in? I've seen Javascript-based exampled where data is carried from page to page using cookies but using Python / Django the only way I know how to do this is by using a database. -
How to generate newsfeed / timeline consisting of different types of contents?
I have to implement a newsfeed for an application where I need to show different types of content. And in the future, some new types of content may come. I have the following idea in my mind at a high level. At this point of time, I'm not concerned about ranking, caching, etc. My focus is to generate newsfeeds having different types of content. class ContentType1(models.Model): pass class ContentType2(models.Model): pass class ContentType3(models.Model): pass class Content(models.Model): c_type = models.CharField( max_length=6, choices=[ ('TYPE1', 'Type 1 content'), ('TYPE2', 'Type 2 content'), ('TYPE3', 'Type 3 content') ] ) type_1 = models.ForeignKey(ContentType1, null=True, blank=True) type_2 = models.ForeignKey(ContentType2, null=True, blank=True) type_3 = models.ForeignKey(ContentType3, null=True, blank=True) The idea is to have a general Content model having separate fields for every type of content and a field named c_type which determines the type of the content and guides to access the corresponding field. And responding to users' requests from the Content queryset. I'm not fully satisfied with the approach, looking for a better approach maybe something with polymorphism or any better approach using Django. -
You're using the staticfiles app without having set the required STATIC_URL setting - Django
I have 5 months of experience in django and I can not just find the solution of the error which I encounter. I think it depends on frontend files, I can not deal with static files right now Recently, I have been building a chat app called PyChatt Whole project available on Github -> here Please I need your help urgently!!! traceback: Traceback (most recent call last): File "C:\Users\pytho\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\pytho\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "D:\python_projects\Webogram\Internal\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\core\management\commands\runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\management\commands\runserver.py", line 35, in get_handler return StaticFilesHandler(handler) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\handlers.py", line 75, in __init__ self.base_url = urlparse(self.get_base_url()) File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\handlers.py", line 30, in get_base_url utils.check_settings() File "D:\python_projects\Webogram\Internal\lib\site- packages\django\contrib\staticfiles\utils.py", line 49, in check_settings raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the required STATIC_URL setting. and settings.py: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-pke21+-&vpt2=ka6$a_=x5vz-@#_)o^ro#eet+h03sy&y-l+8w' DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'UsersAuthentication', 'MessageHandleEngine', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { … -
Check box field in django forms showing error
Based on my django project I want to add multiple users to a group and I'm trying to do this using a form. But when I try adding choices via CheckBoxSelectMultiple() widget its not working as expected. models.py file from django.db import models from members.models import User from django.contrib.auth.models import Group class Sprint(models.Model): status_choice = [('Working','Working'), ('Closed','Closed')] sprint_name = models.CharField(max_length=180) sprint_created = models.DateTimeField(auto_now= True) lead = models.ForeignKey(User, on_delete=models.CASCADE, related_name='team_lead') sprint_members = models.ForeignKey(Group, on_delete=models.CASCADE, related_name = "member") sprint_period = models.PositiveIntegerField() sprint_status = models.CharField(max_length=10, choices=status_choice, default='Working') forms.py file from django import forms from .models import Sprint from members.models import User from django.core.exceptions import ValidationError from django.contrib.auth.models import Group class SprintForm(forms.Form): sprint_name = forms.CharField() sprint_period = forms.IntegerField(label="Sprint period (in days)", min_value=7) lead = forms.ModelChoiceField(queryset= User.objects.filter(role = 'Developer'), label="Team Lead") sprint_members = forms.ModelChoiceField(queryset= User.objects.filter(role = 'Developer'), widget= forms.CheckboxSelectMultiple(), label="Team members") # class Meta: # model = Sprint # fields = ['sprint_name', 'lead', 'sprint_period', 'sprint_members'] def clean(self): cleaned_data = super().clean() lead = cleaned_data.get('lead') team = cleaned_data.get('sprint_members') if team and lead: if lead in team: raise ValidationError('Team lead cant be in team') def save(self): team = Group.objects.get_or_create(name=f'team{self.cleaned_data["sprint_name"]}')[0] for team_member in self.cleaned_data['sprint_members']: team.user_set.add(team_member) Sprint.objects.update_or_create( sprint_name=self.cleaned_data["sprint_name"], lead=self.cleaned_data["lead"], sprint_period=self.cleaned_data["sprint_period"], _members=team ) views.py file class SprintCreationView(generic.FormView): model = Sprint template_name … -
WebSocket dosn't work with postman (django channels)
I have a Django project which I run locally on my mac. And I use channels to create websocket connection. And an interesting thing happened: The web socket works when I try to connect through .html file: myTemplate.html const ws = new WebSocket( 'ws://' + window.location.host +'/ws/test/?token=' +'**mytoken**' );' I can send, and receive messages. But the same URL doesn't work in postman or https://websocketking.com/ Firstly, I thought it is because I run server locally. But on real server nothing works at all. I searched all stackoverflow and implement everything - to no avail. asgi.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spacetime.settings.dev') django.setup() from channels.routing import ProtocolTypeRouter,get_default_application from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.urls import path, re_path from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack from myapp import consumers, routing application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( JWTAuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ) ), }) settings ASGI_APPLICATION = 'spacetime.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', *** ] vccode console Django version 4.1.2, using settings 'spacetime.settings.dev' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the …