Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to create a signin page but after sign in a file with 0 kb is getting downloaded and getting CSRF verification failed
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Signup Page</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'login/signuppage.css' %}"> </head> <body> <div class="login"> <div class ="form"> <h3>Sign in</h3> <form class="registration-form" method="POST"> {% csrf_token %} {% for field in form %} <p>{{ field.label_tag }} {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <!--<input type="text" placeholder="Username"/> <input type="email" placeholder="Email ID"/> <input type="password" placeholder="Password"/> <input type="password" placeholder="Confirm Password"/>--> <button>Sign in</button> <p><a href ="#">Login</a></p> </form> </div> </div> </body> </html> Sign in page views views.py: def SignupPage(request): form = UserSigninForm() if request.method=='POST': form=UserSigninForm(request.POST) if form.is_valid(): user=form.save() auth_login(request, user) return redirect('/home/') else: form = UserSigninForm() context = {'form': form} return render(request,'login/signuppage.html',context) signin page forms forms.py: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from django.forms import ModelForm class UserSigninForm(UserCreationForm): class Meta: model = User fields=['username','email','password1','password2'] I am trying to create a signin page but after sign in a file with 0 kb is getting downloaded and getting CSRF verification failed. Request aborted as an error. I am trying not to exempt csrf token in code. What needs to be done here to resolve the issue? -
RabbitMQ, Celery and Django - connection to broker lost. Trying to re-establish the connection
Celery disconnects each time a task is passed to rabbitMQ, however the task does eventually succeed: My questions are: How can I solve this issue? What improvements can you suggest for my celery/rabbitmq configuration? Celery version: 5.1.2 RabbitMQ version: 3.9.0 Erlang version: 24.0.4 RabbitMQ error (sorry for the length of the log: ** Generic server <0.11908.0> terminating ** Last message in was {'$gen_cast', {method,{'basic.ack',1,false},none,noflow}} ** When Server state == {ch, {conf,running,rabbit_framing_amqp_0_9_1,1, <0.11899.0>,<0.11906.0>,<0.11899.0>, <<"someIPAddress:45610 -> someIPAddress:5672">>, undefined, {user,<<"someadmin">>, [administrator], [{rabbit_auth_backend_internal,none}]}, <<"backoffice">>,<<"celery">>,<0.11900.0>, [{<<"consumer_cancel_notify">>,bool,true}, {<<"connection.blocked">>,bool,true}, {<<"authentication_failure_close">>,bool,true}], none,0,134217728,1800000,#{},1000000000}, {lstate,<0.11907.0>,true}, none,2, {1, {[{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue,<<"celery">>}, 2097}], []}}, {state,#{},erlang}, #{<<"None4">> => {{amqqueue, {resource,<<"backoffice">>,queue,<<"celery">>}, true,false,none,[],<0.471.0>,[],[],[],undefined, undefined,[],[],live,0,[],<<"backoffice">>, #{user => <<"someadmin">>}, rabbit_classic_queue,#{}}, {false,0,false,[]}}}, #{{resource,<<"backoffice">>,queue,<<"celery">>} => {1,{<<"None4">>,nil,nil}}}, {state,none,5000,undefined}, false,1, {rabbit_confirms,undefined,#{}}, [],[],none,flow,[], {rabbit_queue_type, #{{resource,<<"backoffice">>,queue,<<"celery">>} => {ctx,rabbit_classic_queue, {resource,<<"backoffice">>,queue,<<"celery">>}, {rabbit_classic_queue,<0.471.0>, {resource,<<"backoffice">>,queue,<<"celery">>}, #{}}}}, #{<0.471.0> => {resource,<<"backoffice">>,queue,<<"celery">>}}}, #Ref<0.4203289403.2328100865.106387>,false} ** Reason for termination == ** {function_clause, [{rabbit_channel,'-notify_limiter/2-fun-0-', [{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue,<<"celery">>}, 2097}, 0], [{file,"src/rabbit_channel.erl"},{line,2124}]}, {lists,foldl,3,[{file,"lists.erl"},{line,1267}]}, {rabbit_channel,notify_limiter,2, [{file,"src/rabbit_channel.erl"},{line,2124}]}, {rabbit_channel,ack,2,[{file,"src/rabbit_channel.erl"},{line,2057}]}, {rabbit_channel,handle_method,3, [{file,"src/rabbit_channel.erl"},{line,1343}]}, {rabbit_channel,handle_cast,2, [{file,"src/rabbit_channel.erl"},{line,644}]}, {gen_server2,handle_msg,2,[{file,"src/gen_server2.erl"},{line,1067}]}, {proc_lib,wake_up,3,[{file,"proc_lib.erl"},{line,236}]}]} crasher: initial call: rabbit_channel:init/1 pid: <0.11908.0> registered_name: [] exception exit: {function_clause, [{rabbit_channel,'-notify_limiter/2-fun-0-', [{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue, <<"celery">>}, 2097}, 0], [{file,"src/rabbit_channel.erl"},{line,2124}]}, {lists,foldl,3,[{file,"lists.erl"},{line,1267}]}, {rabbit_channel,notify_limiter,2, [{file,"src/rabbit_channel.erl"},{line,2124}]}, {rabbit_channel,ack,2, [{file,"src/rabbit_channel.erl"},{line,2057}]}, {rabbit_channel,handle_method,3, [{file,"src/rabbit_channel.erl"},{line,1343}]}, {rabbit_channel,handle_cast,2, [{file,"src/rabbit_channel.erl"},{line,644}]}, {gen_server2,handle_msg,2, [{file,"src/gen_server2.erl"},{line,1067}]}, {proc_lib,wake_up,3, [{file,"proc_lib.erl"},{line,236}]}]} in function gen_server2:terminate/3 (src/gen_server2.erl, line 1183) ancestors: [<0.11905.0>,<0.11903.0>,<0.11898.0>,<0.11897.0>,<0.508.0>, <0.507.0>,<0.506.0>,<0.504.0>,<0.503.0>,rabbit_sup, <0.224.0>] message_queue_len: 0 messages: [] links: [<0.11905.0>] dictionary: [{channel_operation_timeout,15000}, {process_name, {rabbit_channel, {<<"someIPAddress:45610 -> someIPAddress:5672">>, 1}}}, … -
generator expression must be parenthesized
I'm using Python 3.8 and I'm adding a model in my models file, when I did the makemigration it gave me this reply enter image description here -
show error message for any incorrect path in Django
how can I show an error message for any incorrect slug in Django? URLs.py from django.urls import path, re_path from register import views urlpatterns = [ path('', views.index, name='home'), path('singup', views.Register_user, name='singup'), path('singin', views.login_user, name='singin'), path('registration/success/<slug:user_slug>', views.success_message, name='success_message'), path('registration/failed', views.failed_message, name='failed_message'), path('profile/<slug:user_slug>', views.user_detail, name='profile'), path('profile/<slug:user_slug>/new-blog', views.blog_post, name='new_blog'), path('<str:user_slug>', views.wrong_slug, name='error_msg') ] I trying "path('<str:user_slug>', views.wrong_slug, name='error_msg')" this but it not work after Slash('/'). -
how to create and show a task with POST method in django
i have a model that name is Task it have just name field from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import Task @csrf_exempt def list_create_tasks(request): if request.method == 'POST': name = request.POST.get("name") Task.objects.create(name=name) task = Task.objects.filter("name") return HttpResponse("Task Created: "+"'"+str(task)+"'") -
How to make form html for updateview
I was making my own forms for CreateView and UpdateView with my html file because I don't want to display the form like this {{form.as_p}}. forms.py from django import forms from .models import Post class PostCreationForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'cover', 'text',) widgets = { 'title': forms.TextInput(attrs={'class': 'title'}), 'cover': forms.FileInput(attrs={'class': 'image'}), 'text': forms.TextInput(attrs={'class': 'text'}) } class PostDeleteForm(forms.ModelForm): class Meta: model = Post fields = ('__all__') views.py from django.shortcuts import reverse from django.http import HttpResponseRedirect from django.views import generic from .models import Post from .forms import PostCreationForm, PostDeleteForm class PostListView(generic.ListView): model = Post context_object_view = 'post_list' template_name = 'forum/post_list.html' class PostDetailView(generic.DetailView): model = Post context_object_view = 'post' template_name = 'forum/post_detail.html' class PostCreateView(generic.CreateView): model = Post form_class = PostCreationForm template_name = 'forum/post_create.html' def form_valid(self, form): if form.is_valid(): response = form.save(commit = False) response.author = self.request.user response.save() return HttpResponseRedirect(reverse('post_detail', args=[str(response.id)])) class PostUpdateView(generic.UpdateView): model = Post context_object_view = 'post' form_class = PostCreationForm template_name = 'forum/post_edit.html' def get_post(self, pk): return get_object_or_404(Post, pk=pk) def form_valid(self, form): if form.is_valid(): response = form.save(commit = False) response.save() return HttpResponseRedirect(reverse('post_detail', args=[str(response.id)])) class PostDeleteView(generic.DeleteView): model = Post context_object_view = 'post' form_class = PostDeleteForm template_name = 'forum/post_delete.html' success_url = '/' def get_post(self, pk): return get_object_or_404(Post, pk=pk) post_create.html {% … -
Run JS after Django POST Request
I am learning Django Channels and I already have a few months of basic Django experience. Essentially what I am trying to do is after the POST request is sent, to trigger the JS function that will deal with sending the message. I have the following part of views.py code if request.method == "GET": # irrelevant logic pass if request.method == "POST": msg = Message(...) msg.save() return render(request, "index.html", {"msg":str(msg)}) return render("msg":"Hello World"})` And in my index.html, I have the following relevant part: HTML: <form method="post" id="send"> {% csrf_token %} .... </form> JS: var formData = $("#send"); socket.onmessage = function(e){ formData.submit( function(event){ event.preventDefault(); var finalData = { 'msg' : "{{msg}}" } console.log(JSON.stringify(finalData)); socket.send(JSON.stringify(finalData)); formData[0].reset() }) } However, when I try printing the event in my consumers.py as follows: async def websocket_receive(self, event): print("Received", event) What I would expect is to get the text of the message, but what I get in the console is: HTTP GET / 200 [0.01, 127.0.0.1:45652] ... Received {'type': 'websocket.receive', 'text': '{"msg":"Hello World"}'} ... HTTP POST / 200 [0.02, 127.0.0.1:45652] Which means the message gets sent before the post request goes through. Is there some convenient way to fix this? Thanks for your help :) -
How to give permission to some specific user to access some specific templates in django
I am trying to create a Online exam portal and I have created one admin portal for that site.I have 2 types of users in my site "Students" and "Teachers".How can I restrict students from accessing the admin portal and other views of admin panel? -
nip.io is not working, what can be the issue?
im using gmail authentication in Django, and its not accepting private address so I came up with a solution, that is, using wildcard DNS. its working fine in my laptop and im able to access the website from other devices using this IP address. but I when I repeat the same steps in my client laptop, the nip.io is not working. -
Django model querying for first N rows that sum up to a given number
I am sing Django 3.2 I have a model like this: class MyModel(models.Model): name = models.CharField(max_length=255) num_visits = models.PositiveSmallNumber() created_at = models.DateTimeField() class Meta: ordering = ['created_at'] I want to select the first N rows where the number of visits = 100 (as an example) A trivial (but probably DB intensive way) to do it would be to iterate through the rows in the table (i.e. elements of the queryset) - but I don't want to do that - for reasons that should be obvious. How can I write a query that fetches the first N rows where the sum of visits is a specified number? def get_rows_satisfying_visit_count(number=100): MyModel.objects.filter(/* what ? */) -
Best solution for extending user model twice (Student / Teacher)
I'm coding a application in Django where there are 2 types of users that need to login on the webapplication: teachers and students. Now I'm not sure what is the best approach for this. I already read a lot of tutorials and Stackoverflow questions that explains how to extend the user model, but I'm not sure which is the best option. The requirements: 2 kind of profiles with different fields needed (teacher and student) Possibility to have separate admin "objects" where the superstaff of the application can login in the backend and manage the separate objects. Option 1: Make use of the method to extend the AbstractUser class. This works for now, however I don't know if I can use AUTH_USER_MODEL twice (teacher and student). Now it's one profile with both fields for students and teachers. With proxy models I can show only the necessary fields for teachers or students. Option 2: (I think this is the best solution) Make 2 models (Teacher and Student) with each a Foreignkey to User (OneToOneField). Problem here is that if the Administrator of the website creates a new teacher or student, they also need to create a separate user first (that can login) … -
how to send an image to Django-rest-framework without having the unicodeDecode error
I'm trying to upload an image to my Django project using DRF but I get this error : 'utf-8' codec can't decode byte 0xfd in position 34: invalid start byte Here is how I do it on Django : models class Project(models.Model): # relations supplier = models.ForeignKey(User, on_delete=models.CASCADE, related_name="project_supplier", null=True, blank=True) client = models.ForeignKey(User, on_delete=models.CASCADE, related_name="project_client", null=True, blank=True) # fields created = models.DateTimeField(auto_now_add=True, editable=False,null=True) name = models.CharField(max_length=200) cost = models.PositiveIntegerField(null=True, blank=True) rate = models.PositiveIntegerField(null=True, blank=True) is_done = models.BooleanField(default=True) image_1 = models.ImageField(upload_to="upload/images/") image_2 = models.ImageField(upload_to="upload/images/") image_3 = models.ImageField(upload_to="upload/images/") image_4 = models.ImageField(upload_to="upload/images/", null=True, blank=True) image_5 = models.ImageField(upload_to="upload/images/", null=True, blank=True) API @api_view(["POST", ]) def create_new_project(request): if is_post(request): lang = request.data["lang"] name = request.data["name"] image_1 = request.data["image_1"] image_2 = request.data["image_2"] if request.data["image_2"] is not "" else None image_3 = request.data["image_3"] if request.data["image_3"] is not "" else None image_4 = request.data["image_4"] if request.data["image_4"] is not "" else None image_5 = request.data["image_5"] if request.data["image_5"] is not "" else None the_token = request.META.get('HTTP_AUTHORIZATION')[6:] user = Token.objects.get(key=the_token).user try: new_project = Project.objects.create(supplier=user, name=name, image_1=image_1, image_2=image_2, image_3=image_3, image_4=image_4, image_5=image_5) data = model_to_dict(new_project) return generate_response(True, "Projected added successfully" if lang == "en" else "تم إضافة المشروع بنجاح", data) except Exception as e: return generate_response(False, e, None) And here Is how i … -
How to redirect to an absolute url path in django?
I am trying to reroute to the "listing" path from the the watchlist page using the 'url' attribute in Django templates. However, the problem is that Django ignores the parts of the URL it has already used in rerouting (i.e."/watchlist") and so looks for the url with path "/watchlist/listing_title" instead of just "/listing_title", which is what I want. Is there a way to work around this? urls.py path("", views.index, name="index"), path("<str:listing_title>", views.listing, name="listing"), path("watchlist", views.watchlist, name="watchlist"), watchlist.html <a href={% url 'listing' listing.title %}"> -
Django Rest Framework "detail": "Not found."
Here is the URL in url.py: path('follow/<int:pk>/', FollowUser.as_view()), And here is the Class Based View: class FollowUser(UpdateAPIView): """ Follow a user by their PK """ serializer_class = FollowingSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Following.objects.get(user=self.request.user) Why am I getting {"detail": "Not found."} Here is the end point I'm trying to hit: http://localhost:8000/fapi/follow/23/ -
Why is django not making migrations for my models
I uploaded my django app to pythonanywhere and it worked with sqlite database, but on switching to mysql it doesnt make migrations but it migrates the admin tables when i rum python manage.py migrate this is my settings app import os from pathlib import Path import environ env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() DEBUG = env('DEBUG') BASE_DIR = Path(__file__).resolve().parent.parent # Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') if DEBUG: ALLOWED_HOSTS = [] else: ALLOWED_HOSTS = [ '*', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'projects', 'services', 'crispy_forms', 'crispy_bootstrap5', # should be at bottom 'django_cleanup.apps.CleanupConfig', ] 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 = 'vectorapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'vectorapp.wsgi.application' if not DEBUG: DATABASES = { 'default': { 'ENGINE': os.getenv("DB_ENGINE"), 'NAME': os.getenv("DB_NAME"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), # 'PORT': os.getenv("DB_PORT"), "OPTIONS": { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1", 'charset': 'utf8mb4', "autocommit": True, } } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', … -
Not all fields are showing correctly in django admin
I've added a plan field to my custom Account class, but cannot get it to show on the individual account page in the django admin. It shows correctly in table of all accounts in the list view (as denoted by list_display), but does not show on each individual account page. Here's my Account model: class Account(AbstractUser): PLANS = ( ("free", "free"), ("pro", "pro") ) plan = models.CharField(max_length=10, choices=PLANS, default="free") def __str__(self) -> str: return self.first_name And my admin file: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from accounts.models import Account from subscribers.models import Subscriber class SubscriberInline(admin.TabularInline): model = Subscriber extra = 0 class AccountAdmin(UserAdmin): inlines = [SubscriberInline, ] list_display = ("first_name", "plan", "email") # fields = ("first_name", "plan", "email") admin.site.register(Account, AccountAdmin) Why does this happen? Is the problem related to the custom Account class which inherits from the AbstractUser model? I thought to add fields to the AccountAdmin class, but that just returns the below error: ERRORS: <class 'accounts.admin.AccountAdmin'>: (admin.E005) Both 'fieldsets' and 'fields' are specified. The plan field also doesn't show in the admin panel when trying to create a new account (mind you, neither do most of the other fields as it only asks for the username, … -
ProgrammingError at /admin/customers/customers/
my model class Customers(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) contact_no = models.CharField(max_length=25) time_joined = models.DateTimeField(auto_now_add=True) city = models.ForeignKey(to='restaurants.City', on_delete=models.CASCADE,blank=True,null=True) gender = models.CharField(max_length=10) city model class City(models.Model): city_name = models.CharField(max_length=30) zip_code = models.IntegerField() I previously had an issue with circular import but now, it's throwing this error, I tried to insert some data in the City model but it's showing the same... I am currently completely stuck i am able to run my migrations though, i have read some solutions saying delete all migrations, tried that as well still showing the same tried adding id field still the same i am also getting this error when i am trying to access customers in admin panel my Trace Traceback (most recent call last): File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (column customers_customers.city_id does not exist LINE 1: ...contact_no", "customers_customers"."time_joined", "customers... ^ ) was the direct cause of the following exception: File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response … -
uwsgi shows "TemplateDoesNotExist at /" but django runserver works fine
I am building a web server with Nginx, uwsgi and Django. But when I try to build a test app with template, it shows correctly when I run " python manage.py runserver". But when browsing through nginx/uwsgi, it shows "TemplateDoesNotExist at /". /mysite01/settings.py TEMPLATES_DIR = BASE_DIR.joinpath('templates') ... TEMPLATES = [ { ... 'DIRS': [TEMPLATES_DIR], /mysite01/myapp01/urls.py urlpatterns = [ # ex: /myapp01/ path('', views.index, name='index'),] /mysite01/myapp01/views.py def index(request): content_dict = {'insert_me': "'Hello, I am coming from myapp01/index.html template!"} return render(request, 'myapp01/index.html', context=content_dict) /mysite01/tempaltes/myapp01/index.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Polls Index</title> <link rel='stylesheet' href="{% static 'css/myapp01.css' %}"/> </head> <body> <h1>Welcome to myapp01!</h1> <p>{{ insert_me }}</p> </body> </html> And this is my uwsgi.ini config: [uwsgi] # full path to Django project's root directory chdir = /home/admin/mysite01/ # Django's wsgi file module = mysite01.wsgi # full path to python virtual env home = /home/admin/env/MyDjangoEnv # enable uwsgi master process master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /home/admin/mysite01/mysite01.sock # socket permissions chmod-socket = 664 # clear environment on exit vacuum = true # daemonize uwsgi and write messages into given log daemonize = … -
return value.utcoffset() is not None AttributeError: 'datetime.date' object has no attribute 'utcoffset'
Pardon me but I am a bit new to Django, Django does not even tell me the field having issues I keep getting an error I don't understand How do I know the field having issues? When I try to fetch a user profile(Basically a get call) on this model, see the error I keep getting I checked a lot of stack overflow posts but none seems to give me the information I need to resolve these errors on this get profile call File "/MyPath/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/MyPath/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/MyPath/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/MyPath/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/MyPath/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/MyPath/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/MyPath/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/MyPath/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/MyPath/app_features/views.py", line 36, in list return Response(serializer.data) File "/MyPath/lib/python3.8/site-packages/rest_framework/serializers.py", line 745, in data ret = super().data File "/MyPath/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data self._data = self.to_representation(self.instance) File "/MyPath/lib/python3.8/site-packages/rest_framework/serializers.py", line 663, in to_representation return [ File "/MyPath/lib/python3.8/site-packages/rest_framework/serializers.py", line 664, in <listcomp> self.child.to_representation(item) for item … -
WebRTC local and remote descriptions set but data channel is not being set
I am trying to make a video calling app using Django and WebRTC Here is my js code let video=document.getElementById('video') let video_container=document.getElementById('video-container') let video_btn=document.getElementById('video-btn') let audio_btn=document.getElementById('audio-btn') let join_btn=document.getElementById('username-btn') let username_input=document.getElementById('username') let username="" //video navigator.mediaDevices.getUserMedia({'video':true,'audio':true}).then(stream=>{ video.srcObject=stream video.muted=true var audiotrack = stream.getAudioTracks() var videotrack = stream.getVideoTracks() audiotrack[0].enabled=true videotrack[0].enabled=true video_btn.addEventListener('click',e=>{ videotrack[0].enabled=!videotrack[0].enabled if(videotrack[0].enabled==true)video_btn.innerHTML="Turn Video off" else video_btn.innerHTML="Turn Video On" }) audio_btn.addEventListener('click',e=>{ audiotrack[0].enabled=!audiotrack[0].enabled if(audiotrack[0].enabled==true)audio_btn.innerHTML="Turn audio off" else audio_btn.innerHTML="Turn audio On" }) }) //send signal async function send_signal(user_name,action,etc){ data={ 'username':user_name, 'action':action, 'etc':etc } await socket.send(JSON.stringify(data)) } //add video for new peer function add_video(user_name){ new_video=document.createElement('video') new_video.autoplay=true new_video.id="video-"+user_name video_container.appendChild(new_video) } //send offer to specific channel async function sendoffer(data){ lc =new RTCPeerConnection() rc =lc.createDataChannel('channel') await lc.createOffer().then(e=>lc.setLocalDescription(e)) await send_signal(user_name=username,action="new-offer",etc={'sdp':JSON.stringify(lc.localDescription),'channel':data['etc']['channel']}) rc.addEventListener('message',e=>console.log(e.data)) rc.addEventListener('open',e=>console.log('connection opened')) } //send Answer to all channels async function sendanswer(data){ lc = new RTCPeerConnection() lc.addEventListener("datachannel",ev=>{ console.log("data channel set") lc.rc=ev.channel }) await lc.setRemoteDescription(JSON.parse(data['etc']['sdp'])) await lc.createAnswer().then(e=>lc.setLocalDescription(e)) await send_signal(user_name=username,action="new-answer",etc={'sdp':JSON.stringify(lc.localDescription),'channel':data['etc']['channel']}) } //set answer sdp to local connection async function setanswer(data){ console.log("setting") await lc.setRemoteDescription(JSON.parse(data['etc']['sdp'])) } //Socket Handling join_btn.addEventListener('click',e=>{ username=username_input.value join_btn.disabled=true username_input.disabled=true socket = new WebSocket("ws://"+window.location.host+"/ws/") socket.addEventListener('open',async e=>{ console.log("connection opened") await send_signal(user_name=username,action="new-peer",etc={}) }) socket.addEventListener('close',e=>{ console.log("connection closed") }) socket.addEventListener('error',e=>{ console.log("connection error") }) socket.addEventListener('message',async e=>{ data= JSON.parse(e.data) console.log("message" + e.data) if(data['username']==username)return else if (data['action']=='new-peer'){ console.log('new user added') add_video(data['username']) await sendoffer(data) } else if(data['action']=='new-offer'){ console.log('new offer added') await … -
What is the differnce between templateview and detailview in django?
Each of this is for displaying a single template as we want,then what is actually it's difference which make it differ? And which is better for using and Why? -
Django Custom User Model migration return error : ValueError: Related model 'user_profile.customuser' cannot be resolved
I have modified the the user authentication to create a custom user. In my user_profile model I log in with email instead of username. I have extended AbstractUserModel for this purpose and have implemented manager and serializer as mentioned bellow. My makemigrations command is executes with success but when I run migration I get an error. I had deleted the entire database and started migrations afresh. As the project is in development I have option to manipulate database as needed. Environment Python==3.9.1 Django==3.2.3 djangorestframework==3.12.4 user_profiles manager.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if email is None: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, … -
Gmail verificated failed in django
I created two class in view.py to achieve account register and verificate. This is my thought.When user registers,django will send an active_link to user's gmail and now user.is_active = False.After clicking it so that user.is_active = True and account verificates successfully.The situation is that my gmail got the aitive_link,but User.objects still equals False after clicking the link. This is my registraion class. class RegistrationView(View): def get(self, request): return render(request, 'authentication/register.html') def post(self, request): username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] context = { 'fieldValues': request.POST } if not User.objects.filter(username=username).exists(): if not User.objects.filter(email=email).exists(): if len(password) < 8: messages.error(request, '密码不会8位都没吧,不会吧') return render(request, 'authentication/register.html', context) user = User.objects.create_user(username=username, email=email) user.set_password(password) user.is_active = False user.save() uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) domain = get_current_site(request).domain link = reverse('activate', kwargs={'uidb64': uidb64,'token': account_activation_token.make_token(user)}) activate_url = 'http://' + domain + link email_body = 'Hi ' + user.username + ' 没时间解释了快点链接认证账户\n' + activate_url email_subject = '激活你的邮箱' email = EmailMessage( email_subject, email_body, 'noreply@gmail.com', [email], ) email.send(fail_silently=False) messages.success(request, '邮箱验证完这帐户就是他娘你的了') return render(request, 'authentication/register.html') return render(request, 'authentication/register.html') This is my Verification class. class VerificationView(View): def get(self, request, uidb64, token): try: id = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=id) if not account_activation_token.check_token(user, token): return redirect('login'+'?message='+'User already activated') if user.is_active: return redirect('login') user.is_active = True user.save() messages.success(request, '账户创建成功') … -
django many to many "through" table which inherits base model in sqlalchemy
I need to migrate saleor product models which is in django to fastapi using sqlalchemy orm. I am having hard time on many to many model part. In case of saleor's product model AssignedProductAttribute is a through model which itself inherits BaseAssignedAttribute abstract model which has another many to many fields. I mean the model related to product attributes look like this in django class BaseAssignedAttribute(models.Model): assignment = None class Meta: abstract = True @property def attribute(self): return self.assignment.attribute @property def attribute_pk(self): return self.assignment.attribute_id class Attribute(ModelWithMetadata): slug = models.SlugField(max_length=250, unique=True, allow_unicode=True) name = models.CharField(max_length=255) product_types = models.ManyToManyField( ProductType, blank=True, related_name="product_attributes", through="AttributeProduct", through_fields=("attribute", "product_type"), ) product_variant_types = models.ManyToManyField( ProductType, blank=True, related_name="variant_attributes", through="AttributeVariant", through_fields=("attribute", "product_type"), ) value_required = models.BooleanField(default=False, blank=True) class AssignedProductAttributeValue(SortableModel): value = models.ForeignKey( "AttributeValue", on_delete=models.CASCADE, related_name="productvalueassignment", ) assignment = models.ForeignKey( "AssignedProductAttribute", on_delete=models.CASCADE, related_name="productvalueassignment", ) class Meta: unique_together = (("value", "assignment"),) ordering = ("sort_order", "pk") def get_ordering_queryset(self): return self.assignment.productvalueassignment.all() class AssignedProductAttribute(BaseAssignedAttribute): """Associate a product type attribute and selected values to a given product.""" product = models.ForeignKey( Product, related_name="attributes", on_delete=models.CASCADE ) assignment = models.ForeignKey( "AttributeProduct", on_delete=models.CASCADE, related_name="productassignments" ) values = models.ManyToManyField( "AttributeValue", blank=True, related_name="productassignments", through=AssignedProductAttributeValue, ) class Meta: unique_together = (("product", "assignment"),) class AttributeProduct(SortableModel): attribute = models.ForeignKey( "Attribute", related_name="attributeproduct", on_delete=models.CASCADE ) product_type … -
Error while running '$ python manage.py collectstatic --noinput' while deploying app
New to Django, trying to deploy my web app but keep getting this error. I do understand the traceback. Any help will be appreciated. remote: Traceback (most recent call last): remote: File "/tmp/build_3810ef0f/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_3810ef0f/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 329, in run_from_argv remote: connections.close_all() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 225, in close_all remote: connection.close() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 190, in close remote: if not self.is_in_memory_db(): remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 280, in is_in_memory_db remote: return self.creation.is_in_memory_db(self.settings_dict['NAME']) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db remote: return database_name == ':memory:' or 'mode=memory' in database_name remote: TypeError: argument of type 'PosixPath' is not iterable remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. My requirements.txt boto3==1.9.96 botocore==1.12.96 certifi==2018.10.15 chardet==3.0.4 dj-database-url==0.5.0 Django==2.1 django-crispy-forms==1.7.2 django-heroku==0.3.1 django-storages==1.7.1 docutils==0.14 gunicorn==19.9.0 …