Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Installing Django to Windows 8.1
I have been following this tutorial (https://tutorial.djangogirls.org/en/django_installation/) to learn some python but I have become stuck at the 'Django installation' step. I have managed to create a virtual environment and the .txt file but inputting 'pip install -r requirements.txt' into the command-line I get the error 'could not find version that satisfies requirement'and'no matching distribution found'. This error occurs when I have entered versions 2.2.4 & 3.0.5 of Django into the .txt file. Have also just tried 'pip install django' and have come across the same errors. Have tried in the windows command prompt but i get an error stating pip is not recognized as an internal or external command. Any help is very much appreciated -
Django enable show_close button on admin page
How to enable show_close button on Django admin page? I tried the following but not work. class ModelAdminSite(AdminSite): def each_context(self, request): context = super().each_context(request) print(context) context['show_close'] = True return context -
I can't organize my messages by recent chat in Django
I've been trying to fix my messages in order to show the messages by most recent. I can't figure out where did I go wrong in the code. I am thinking that I can use sent_at to know the last active conversation in an active chat but I don't know where to start. Here are my codes: models.py from django.db import models from django.core.exceptions import ValidationError from django.utils import timezone from django.conf import settings AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') class Message(models.Model): """ A private direct message. """ content = models.TextField('Content') document = models.FileField(upload_to='direct_messages', blank=True, null=True) sender = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_dm', verbose_name='Sender' ) recipient = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_dm', verbose_name='Recipient' ) sent_at = models.DateTimeField('sent at', auto_now_add=True) read_at = models.DateTimeField('read at', null=True, blank=True) class Meta: ordering = ['-sent_at'] @property def unread(self): """ Returns whether the message was read or not. """ if self.read_at is not None: return True def __str__(self): return self.content def save(self, **kwargs): """ Check message sender and recipient and raise error if the are saved. Save message when the condition passes. """ if self.sender == self.recipient: raise ValidationError("You cant't send messages to yourself!") if not self.id: self.sent_at = timezone.now() super(Message, self).save(**kwargs) class ChatRoom(models.Model): """ A private char room … -
Javascript doesn't load in Django template
I want to add some javascript function in python django template but the staticfile I load doesn't load the javasctipt file . The file doesn't have ?v=2.17 but I want them to for jquery version <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox --> <link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/jquery.fancybox.css?v=2.1.7" type="text/css" media="screen" /> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/jquery.fancybox.pack.js"></script> <!-- Optionally add helpers - button, thumbnail and/or media --> <link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" /> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" /> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <script type="text/javascript"> $(document).ready(function() { $(".fancybox").fancybox(); }); </script> This is my settings.py file and url.py file from project : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/var/www/static/', ] CRISPY_TEMPLATE_PACK = 'bootstrap3' -
Returning an video URL as a "Blob Response" in Django?
I've been looking at researching a way of transporting a video as a blob object, for cross browser compatibility for playing videos uploaded ... I believe that blobs are the most reliable way of achieving this. However, I am unsure of the best way to impliment this with Django? Would it be some sort of FileResponse object, or HttpStreamResponse? ...or, as my research is suggesting...this is entirely a client side operation with the Blob() web API? -
from django.utils.encoding import python_2_unicode_compatible
i've been using django for a while without having any issues, I don't really know what I did by mistake, but now, some errors pop up when I try to run my server or to migrate or to type whatever command that comes after python manage.py. I'm using django 3.0.5 (should be the latest version), and python 3.8.2. the error actually comes from some files written by default like init.py, autoreloader.py , runserver.py ... I think it must be a certain confusion between the two versions. Any help please? Picture : https://i.stack.imgur.com/eQq52.png -
Impact migrating between multiple role models to one model IntegerField
In former times I was using three models named User (from AbstractBaseUser), Teacher and Student. A Student could create a Request and a Teacher could ask to be responsible for that Request. If Student accepted, then the Teacher would become the responsible for that Request. This is how the Request table looked like: class Request(models.Model): request_id = models.CharField(db_column='requestId', primary_key=True, max_length=36) date_created = models.DateField(db_column='dateCreated') title = models.CharField(max_length=30) request_description = models.CharField(db_column='requestDescription', max_length=280, blank=True, null=True) expiration_date = models.DateField(db_column='expirationDate', blank=True, null=True) done = models.IntegerField(blank=True, null=True) student_id = models.ForeignKey(Student, models.DO_NOTHING, db_column='studentId') teacher_id = models.ForeignKey(Teacher, models.DO_NOTHING, db_column='teacherId', blank=True, null=True) As you can see, there's student_id and teacher_id with ForeignKey to, respectively, Student and Teacher models. Now, I'm using only one model to represent User, Teacher and Student, called MyUser. In this model, got a field user_type = models.IntegerField(db_column='userType') where 0 is the MyUser with more permissions and 255 is an unspecified MyUser. What happens now to the FKs in Request? Also, how to handle the Teacher and Student through this field? -
Why do tests for Django Websockets have to be written in pytest?
All tutorials and official documents point to using pytest for testing Django's websockets. My question is why Django's unittest framework cannot be used directly and when this might change? -
Replacing M2M field with property
I'd like to replace M2M field with a property decorated funcition. Is it even possible? Like I have something along the lines of: members = models.ManyToManyField('Person', related_name='group') and would like to change that into: @property def members(self): return Person.objects.all() And accordingly add @property group to Person model? I just need to store data about members in couple of different fields but still wants members property to return all of them. Is it even feasible in django? When I tried it i'm getting FieldError: Cannot resolve keyword 'members' into field? -
Django serialization error 'dict' object has no attribute 'mymodelfield' in .values() aggregation
I am trying to do aggregation of a model (Reply) by geographic area (Hexgrid_10km2). Similar to SQL 'group by'. I am using .values(Hexgrid_10km) to do this. I am then annotating some numbers onto this. I am getting the following error in te serialization to geojson: 'dict' object has no attribute 'hexgrid_10km2' But Reply does a have field 'hexgrid_10km2'. Anybody know what is up? Many thanks! I am using djangorestframework-gis Models class Hexgrid_10km2(models.Model): lng = models.FloatField() lat = models.FloatField() polygon = models.MultiPolygonField(srid=4326) centroid = models.PointField(default=Point(0,0), srid=4326) def __str__(self): return f'lng: { self.lng } lat: {self.lat }' class Animal (models.Model): name = models.CharField(max_length=200) class Reply(models.Model): animal = models.ForeignKey(Animal, on_delete=models.CASCADE) ability = models.IntegerField(default = 0) hexgrid_10km2 = models.ForeignKey(Hexgrid_10km2, on_delete=models.CASCADE, null=True, blank=True) @property def polygon_10km2(self): return self.hexgrid_10km2.polygon Views from rest_framework.views import APIView from rest_framework.response import Response from.models import Animal, Reply, Hexgrid_10km2 from django.db.models import Avg, Sum class ReplyHeatmapAPIView(APIView): def get(self, request, pk): animal = get_object_or_404(Animal, pk=pk) final = Reply.objects.filter(animal=animal).values('hexgrid_10km2').annotate(average_ability=Avg('ability'), sum_ability=Sum('ability')) serializer = ReplyHeatmapSerializer(final, many=True) return Response(serializer.data) Serializer from rest_framework_gis.fields import GeometrySerializerMethodField from rest_framework_gis.serializers import GeoFeatureModelSerializer class ReplyHeatmapSerializer(GeoFeatureModelSerializer): """ A class to serialize hex polygons as GeoJSON compatible data """ average_ability = serializers.FloatField() sum_ability = serializers.FloatField() polygon = GeometrySerializerMethodField() def get_polygon(self, obj): return obj.hexgrid_10km2.polygon class … -
Vuejs into Django Deployment to Production Using Webpack
When I do npm run build it created a bunch of file on dist folder. So I dont know how to integrate this files to django. Iam running 2 server on my development one for backend(django) one for front end (vuejs). So I wanna run only my django server on my production. I watched so online course but they have only few files like only one bundle.js and one bundle.css. For my case there is different. -
What does "or" in function-parameters in python mean?
I just was watching a tutorial and the following pattern appeared: #some code function(Variable1 or Variable2) #more code I'm really wondering what this or means in this case. Could someone explain the purpose of orin function parameters?? Thanks for your help and stay healthy! -
Override Default Meta Setting
Due to the requirement, I would like to adjust all the default setting table name. Even though I alter the core directly in venv.lib.site-packages files then run the command below, Django migrations still cannot detect the changes. python manage.py makemigrations Below is the meta setting and the place I would like to change, I tried to place it in the project's or application's _init.py and it doesn't work from django.db.migrations.recorder import MigrationRecorder from django.contrib.sessions.models import Session from django.contrib.contenttypes.models import ContentType from django.contrib.admin.models import LogEntry from django.contrib.auth.models import Permission from django.contrib.auth.models import Group from django.contrib.auth.models import User from rest_framework.authtoken.models import Token Session._meta.db_table = "extData_django_session" MigrationRecorder.Migration._meta.db_table = "extData_django_migrations" ContentType._meta.db_table = "extData_django_content_type" LogEntry._meta.db_table = "test_django_admin_log" Permission._meta.db_table = "extData_auth_permission" Group._meta.db_table = "extData_auth_group" User._meta.db_table = "extData_auth_user" Token._meta.db_table = "extData_authtoken_token" -
Django Rest Framework , How does Modelserializer validate the user input?
I have a method in ArticleSerializer that check if the length of title property. The title property is associated with the model (Article). How does the validate_title function execute itself when calling ArticleSerializer class ? How does the validate_title function take value from title property ? #necessary module imports from .models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article exclude = ("id",) def validate_title(self, value): """ check that title is at least 30 chars long """ if len(value) < 30: raise serializers.ValidationError("type less") return value I am learning Django rest framwork in Udemy Github link : https://github.com/pymike00/The-Complete-Guide-To-DRF-and-VueJS/blob/master/03-DRF-LEVEL-ONE/newsapi/news/api/serializers.py -
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
when i run git push heroku master it says that my STATIC_ROOT is improperly configured (ERROR:raise ImproperlyConfigured("You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path".). I have set my STATIC_ROOT just as shown in a video tutuorial. settings.py import django_heroku import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '###############################' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.environ.get('DEBUG_VALUE') == 'True') ALLOWED_HOSTS = ['http://mypytalk.herokuapp.com/'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages' ] 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 = 'pytalk.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'pytalk.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = … -
Error in Django makemigrations - class meta - invalid attributes
I've added models from django.db import models #About model class About(models.Model): short_description = models.TextField() description = models.TextField() image = models.ImageField(upload_to="about") class Meta: verbosse_name = "About me" verbose_name_plural = "About me" def __str__(self): return "About me" #Service Model class Service(models.Model): name = models.CharField(max_length=100, verbosse_name="Service name") description = models.TextField(verbosse_name="About service") def __str__(self): return self.name #Recent Work Model class Client(models.Model): name = models.CharField(max_length=100, verbosse_name="Client name") description = models.TextField(verbosse_name="Client say") image = models.ImageField(upload_to="clients", default="default.png") def __str__(self): return self.name to models.py in my Django(3, 0, 5, 'final', 0) core app, and after running python manage.py makemigrations core I'a getting strange and very long error Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/jakubswistak/Desktop/portfolioDjango/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/jakubswistak/Desktop/portfolioDjango/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/jakubswistak/Desktop/portfolioDjango/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/jakubswistak/Desktop/portfolioDjango/venv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/jakubswistak/Desktop/portfolioDjango/venv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/jakubswistak/Desktop/portfolioDjango/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module … -
Rendering specific fields multiple times in Django model form
I am learning django and have encountered a challenge. I have a model in which I want to render specific fields multiple times depending on how much the user wants to fill in, while rest of the model fields remain the same. Below is an example model. I want to render the model form in such a way that the fields 'building' and 'tour_date' can be repeated as many times as required while 'client_name' and 'client_email' remain the same. I looked at inlineformset_factory but I think it needs a parent model. I don't think it serves my purpose although I would love to have some of its features like 'extra' and 'can_delete'. The saved records have to be saved as new rows in the 'Tour' table. Another challenge I am facing with the below example is that the 'building' field has to be a drop-down. I have provided the forms.py below for reference. How can I write a view for such a requirement in Django 3.0? Requesting some assistance and guidance. models.py: class Tour(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100) building = models.CharField(max_length=255) tour_date = models.DateField() ... class Meta: managed = True unique_together = ('name', 'building') forms.py: class TourForm(forms.ModelForm): building … -
Django Rest Framework APi return value from function
I use the Django Rest Framework to create a little API. This is my current views.py: from django.shortcuts import render from django.http import HttpResponse from rest_framework.renderers import JSONRenderer from rest_framework.decorators import api_view from .models import Repo, Category from .serializers import repoSerializer, categorySerializer, releaseSerializer # Just wraps a simple HTTP Response to a JSON Response class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) def index(request): return HttpResponse("<h3>Welcome to DebGen API v1.0</h3>") @api_view(['GET']) def repos(request): repos = Repo.objects.all() serializer = repoSerializer(repos, many=True) return JSONResponse(serializer.data) Now I added this part: @api_view(['GET']) def random(request): return JSONResponse(random()) But when I call this part in the API, I get this error: TypeError at /api/random/ view() missing 1 required positional argument: 'request' So what can I do show the random number in the API call? -
RuntimeError: Model class products.models.Product doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Mac OS Python 3.7.3 Django 2.0.7 I'm trying to import in Ipython, this happens: (trydjango) (base) MacBook-Pro:src qizhilin$ python manage.py shell Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from products.models import Product Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/qizhilin/Dev/trydjango/src/products/models.py", line 4, in <module> class Product(models.Model): File "/Users/qizhilin/Dev/trydjango/lib/python3.7/site-packages/django/db/models/base.py", line 108, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class products.models.Product doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I've searched Stackoverflow, a lot of people mentioned add to INSTALLED_APPS but I have it already. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party # own 'pages', 'products', ] what should i do? here's some (maybe)relevant code, if helps: admin.py: from django.contrib import admin # Register your models here. from .models import Product admin.site.register(Product) apps.py: from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' models.py: from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length = 120) #max_length = required description = models.TextField(blank=True,null=True) price = models.DecimalField(decimal_places=2,max_digits=1000) summary = models.TextField(blank=False,null=False) featured = models.BooleanField() # null=True, default=True -
Why heroku saying couldn't find that app even when the build is successful?
I am trying to deploy my django app on heroku. I created an app, connected my app with github, selected automatic deploy and then manually deployed from my github master branch. The activity saying build successful and deployed. But whenever I'm trying to open the app it is raising an error. When I'm checking my logs it is saying "Couldn't find that app" My build log: -----> Python app detected -----> Clearing cached dependencies -----> Installing python-3.6.10 -----> Installing pip -----> Installing SQLite3 Sqlite3 successfully installed. -----> Installing requirements with pip Collecting django==3.0.4 Downloading Django-3.0.4-py3-none-any.whl (7.5 MB) Collecting folium==0.10.1 Downloading folium-0.10.1-py2.py3-none-any.whl (91 kB) Collecting pandas==1.0.3 Downloading pandas-1.0.3-cp36-cp36m-manylinux1_x86_64.whl (10.0 MB) Collecting pytz Downloading pytz-2019.3-py2.py3-none-any.whl (509 kB) Collecting asgiref~=3.2 Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Collecting branca>=0.3.0 Downloading branca-0.4.0-py3-none-any.whl (25 kB) Collecting numpy Downloading numpy-1.18.2-cp36-cp36m-manylinux1_x86_64.whl (20.2 MB) Collecting requests Downloading requests-2.23.0-py2.py3-none-any.whl (58 kB) Collecting jinja2>=2.9 Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB) Collecting python-dateutil>=2.6.1 Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB) Collecting six Downloading six-1.14.0-py2.py3-none-any.whl (10 kB) Collecting certifi>=2017.4.17 Downloading certifi-2020.4.5.1-py2.py3-none-any.whl (157 kB) Collecting chardet<4,>=3.0.2 Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 Downloading urllib3-1.25.8-py2.py3-none-any.whl (125 kB) Collecting idna<3,>=2.5 Downloading idna-2.9-py2.py3-none-any.whl (58 kB) Collecting MarkupSafe>=0.23 Downloading MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl (27 kB) Installing collected packages: pytz, asgiref, sqlparse, django, … -
Using sendgrid api I am getting a getaddrinfo error?
guys, I have to build a simple contact form in django,I have done that job a thousand times before but today it's giving me a wierd error. I tried to do def post(self,request,*args,**kwargs): request_data = request.POST message = Mail( from_email="from_email@gmail.com", to_emails='to_email@gmail.com', subject='Email recieved from salesproject', html_content="hey what's up") sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) This is an integration test that SendGrid gives us, this doesn't require us to use email_host and other stuff... After doing it I'm now getting this weird error. Traceback (most recent call last): File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "D:\projects\python\salesproject\app\views.py", line 55, in post response = sg.send(message) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\sendgrid\sendgrid.py", line 98, in send response = self.client.mail.send.post(request_body=message.get()) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\python_http_client\client.py", line 262, in http_request self._make_request(opener, request, timeout=timeout) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\python_http_client\client.py", line 174, in _make_request return opener.open(request, timeout=timeout) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 526, in open response = self._open(req, data) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 544, in _open '_open', … -
PUT and PATCH request on same api in django rest framework
i am creating a crud where user can update data using put request and he can also update only particular column that i was trying to integrate with PATCH method but it updates all data Is there any example or documentation which i can refer to do this. -
How to pass argument to form in updateview?
I want to use UpdateView in my model Event. This model had this field: employee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='event_employee') My view : class UpdateEvent(UpdateView): model = Event template_name = 'dashboard/pro_update_event.html' form_class = UpdateEventForm other_variable = None def get_form_kwargs(self): kwargs = super(UpdateEvent, self).get_form_kwargs() names_clients = Particulier.objects.filter(professionnels=self.request.user) kwargs.update({'names_clients': names_clients}) return kwargs def get_success_url(self, *args, **kwargs): return reverse_lazy('pro_details_event', kwargs={'pk': self.object.pk}) My Form : class UpdateEventForm(forms.ModelForm): """ edit an event """ class Meta(): model = Event fields = ('employee', 'date_start', 'date_end') def __init__(self, names_clients, *args, **kwargs): super(UpdateEventForm, self).__init__(*args, **kwargs) self.fields['employee'] = forms.ChoiceField(choices=tuple([(client.pk, client) for client in names_clients])) It seems work, the widget "select" contain the correct values. example : <option value="2">Dupond Jean</option> But when I submit the form : Cannot assign "'2'": "Event.employee" must be a "User" instance. I don't understand because if remove "get_form_kwargs" in my view and "def init" in my form, the value passed is the same (the pk of the employee). It's works with this way. But the problem is all employee are selectable and the username is display not the firstname and lastname. -
How to define django app specific exception handler
For my django app I am creating a custom exception handler as defined in https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling Is there a way to define REST_FRAMEWORK variable in some app specific settings file instead of global settings.py -
Develop a DIY video creator
I want to develop a video creator using Python (Django). I am not sure about the packages to be used. I tried working with moviepy but it did not satisfy all the requirements Inputs : Text Images Expected output: The text entered must be converted to voice with the slideshow of images which should be exported to mp4. The text should be flexible with the duration and position with the images