Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How do I pass the 'partial' kwarg from a Serializer to its child serializer
When I submit a PATCH request, its sets a partial=True kwarg on the Viewset's serializer, in this case Book, however when Book has an embedded serializer (Chapter), it does not set partial=True on the Book nested serializer. Original code is this: BookSerializer(ModelSerializer): chapters = ChapterSerializer(many=True, read_only=False, required=False) I've tried something like this to pass partial down but its not working: BookSerializer(ModelSerializer): chapters = SerializerMethodField() def get_chapters(self,obj): return ChapterSerializer(many=True, read_only=False, required=False, partial=self.partial) The json request would be something like this: { "id" : 1, "title" : "New Book Title", "chapters" : [ { "id" : 1, "title" : New Chapter 1 Title }, { "id" : 7, "title" : New Chapter 7 Title }, ] } So during the request, those two Chapters need to have a partial_update, and take that into account when getting validated. -
Django-admin startproject creates broken manage.py file
I've tried this using virtualenv as well with no luck as well, I know there's a preference against "python -m venv .env" but that is very unlikely to be the issue. Django and virtual environments have worked fine in the past on this machine as well. The manage.py file created: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'firebackend.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() steps to recreate: python -m venv .env source .env/bin/activate Appears to be working normal pip install django, django-rest-framework, etc Looking at everything and running the command again it appears to install fine. Tried this with Django 3 and 4 same results django-admin startproject backend . (with or without specifying the current directory, tested that out) And no matter what I do I get the manage.py file above. "Which python" and "which django-admin" point to the env result of 'python -c "import sys; print(sys.path)"' ['', '/usr/lib/python38.zip', '/usr/lib/python3.8', … -
Can the aggregate(Avg()) method in django slow down code execution?
This is how I calculate the average rating, that is, I use Avg (I'm trying to create an online store and I need to count the average rating of the product) average_rt = Review.objects.filter(product_connected=self.get_object()).aggregate(Avg('rating')) And it works, but I have a question: if I have, for example, a couple of thousand reviews, then when the page loads (my rating is counted in get_context_data), these calculations will not slow down the code? And if it slows down a lot, what solutions are there to fix it? I just don't quite understand how this method works -
How can I change the sites url depending on the anchor tags?
urls.py app_name='listing' urlpatterns = [ url(r'^listing/select/$',views.platformselect,name='listingselect'), url(r'^listing/',views.listingpage,name='listingpage'), ] views.py def platformselect(request): return render(request,'listing/platform_select.html') platform_selection.html <a href="{% url 'listing:listingpage' %}">amazon</a> <a href="{% url 'listing:listingpage' %}">ebay</a> <a href="{% url 'listing:listingpage' %}">google</a> Greetings. How can I change the urls according to the options. For example when I click the 'amazon' anchor tag I want it go to "mysite.com/listing/amazon". Same for the other options. How can I change the sites url depending on the anchor tags? -
PostgreSQL match operator @@ in Django for custom full text search ranking
I'm using a full text search in Django + PostgreSQL. So far the various configurations of SearchRank don't quite give the best ordering in my case. However, after some experimentation, what I want I think is a rank value that is 1/(number of words in field), if the field matches the search query 0 otherwise Which in raw SQL would be: (to_tsvector('english', title) @@ plainto_tsquery('english', 'my search query')) ::int::float / array_length(regexp_split_to_array(title, '\s+'), 1), How can I alias/annotate a queryset to have such a field in Django? The issue seems to be that the match operator @@ is abstracted away by Django - I can't seem to see any combination of functions at https://docs.djangoproject.com/en/4.0/ref/contrib/postgres/search/ that allows me to to this. -
Rewriting User standard model when customizing User class
guys! I'm using standard User model from django.contrib.auth.models import User. And I want to customize User model, expecially to add a field with ForeignKey. For example: class User(models.Model): this_users_team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) If I wrote this code is the django will overwriting standard User model with my data in databases or will it cause the issues? One more time, I haven't not any class User in my code. But I'm using User in other models, for example: id_user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) -
TypeError: set() takes 2 positional arguments but 3 were given in Django rest framework
I have an update api in which I have to delete the images files first and then update with other new image files. But when I call the api, it gets above error. My models: class Gallery(TimeStampAbstractModel): picture = VersatileImageField( "Image", upload_to=upload_path, blank=True, ) updated_at = None class Meta: ordering = ["created_at"] class Articles(TimeStampAbstractModel): creator = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name="articles", ) title = models.CharField(max_length=255, blank=True) tags = TaggableManager() image_files = models.ManyToManyField(Gallery, related_name="articles") content = models.TextField(blank=True) video_content = models.URLField(max_length=255, blank=True) post_views = models.IntegerField(default=0) unique_visitors = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="article_views" ) launch_date = models.DateTimeField(null=True) description = models.CharField(max_length=200, blank=True, default=None, null=True) def __str__(self): return self.title My view: class ArticlesView(viewsets.ModelViewSet): queryset = Articles.objects.all() serializer_class = ArticleSerializer permission_classes = [IsAdminUser] def update(self, request, *args, **kwargs): instance = self.get_object() print(instance) files = request.FILES.getlist("image_files") if files: instance.image_files.all().delete() for file in files: image_content = Gallery.objects.create(picture=file) instance.image_files.add(image_content.id) partial = False if "PATCH" in request.method: partial = True serializer = self.get_serializer(instance, data=request.data,partial=partial) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response( { "message": "Article has been updated.", "updated_data": serializer.data, }, status=status.HTTP_200_OK, ) My serializer is : class ArticleSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField(required=False) image_files = GallerySerializer(many=True, read_only=True) user = serializers.StringRelatedField(source="creator") total_shares = serializers.FloatField(read_only=True) total_reacts = serializers.FloatField(read_only=True) bad_reacts = serializers.FloatField(read_only=True) good_reacts = … -
How to display container that is centered with content that is in the far left and far right of it
I would like to display the price of an object on my html website. This is what I would like it to look like: Dynamic The container is centered on the page with a max width of 400px The "price" string is on the far left while the actual price is on the right of the centered content This is what my html looks like: <div class="price-container"> <div class="price">price:</div> <div class="price-number">{{ event.price }}.00</div> </div> This is what my css looks like: .price-container{ font-family: Montserrat; text-transform: uppercase; color: white; font-weight: 700; font-size: 20px; width: 90%; max-width: 400px; } .price{ float: left; } .price-number{ float: right; } -
How to validate a login using a manually added field in a django admin users table
I want to link my login page to my django admin users table. So that users of the page can only access the check in page if their ID and pin is saved in the django admin field. The field already has manually added values and I want to connect these values to a login form. Please I am new to Django Create your views here. def login(request): if request.method == 'POST': from django.views.decorators.csrf import csrf_protect @csrf_protect def checkit(request): if request.method == "POST": r_number = request.POST.get("room") a_paid = request.POST.get("amount") o_name = request.POST.get("occuname") o_email = request.POST.get("occumail") o_occupation = request.POST.get("occu") n_of_n = request.POST.get("night") s_date = request.POST.get("start") e_date = request.POST.get("end") new_data = chech_in(room_number=r_number, amount_paid=a_paid, occupant_name=o_name, occupant_email=o_email, occupant_occupation=o_occupation, number_of_nights=n_of_n, start_date=s_date, end_date=e_date ) new_data.save() return redirect('check:checkit') return render(request, 'check/checkin.html') -
Django for loop in JavaScript syntax error
I am trying to use Django for loop in JavaScript but I am getting a syntax error <script> var config = { type: 'pie', data: { datasets: [{ data: [1780000, 1630000], backgroundColor: [ '#ff0000', '#0000ff', '#ff0080', '#73ffff', '#5c26ff', '#002db3', '#ffff26', '#4cff4c', '#ff00ff' ], label: 'Population' }], labels: [{% for label in labels %} {{ label }}, {% endfor %}] }, options: { responsive: true } }; </script> this part is what i a have a problem with to be exact {% for label in labels %} {{ label }}, {% endfor %} just typing {% for %} gives me a syntax error I looked at similar stack overflow questions and they just use the for loop normally without any problems so why am I getting a syntax error. I even tried it in an an empty Js file and still get a syntax error. Am I forgetting to import something ? It works just fine the HTML file Help is much appreciated I have been stuck for hours now :) -
How to get <a> tags value to django views?
In my django template I have some tags. They linked to my other pages. I want to know which anchor tag clicked in my views. How can I do that? <div class="amazon"> <a href="{% url 'listing:listingpage' %}"><img id="amazon" src="{% static 'images/amazon_logo.png' %}" alt=""></a> </div> <div class="facebook"> <a href="#"><img id="facebook"src="{% static 'images/facebook_logo.png' %}" alt=""></a> </div> <div class="youtube"> <a href="#"><img id="youtube" src="{% static 'images/youtube_logo.png' %}" alt=""></a> </div> <div class="google"> <a href="#"><img id="google" src="{% static 'images/google_logo.png' %}" alt=""></a> </div> <div class="instagram"> <a href="#"><img id="instagram" src="{% static 'images/instagram_logo.png' %}" alt=""></a> </div> views.py def platformselect(request): return render(request,'listing/platform_select.html') -
How can I inherit another model after creating one with models.Model, [(models.Model) ---> (BaseModel)]
Earlier I created a model like this. class BloodDiscard(models.Model): timestamp = models.DateTimeField(auto_now_add=True, blank=True) created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True) blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True) blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True) quantity = models.FloatField() But now I need to apply inheritance to my model, like this. [(models.Model) ---> (BaseModel)] class BloodDiscard(BaseModel): timestamp = models.DateTimeField(auto_now_add=True, blank=True) created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True) blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True) blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True) quantity = models.FloatField() BaseModel is another model I have created before but forgot to inherit it in my current model. class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status_master = models.ForeignKey(StatusMaster,on_delete=models.SET_NULL,default=3,null=True, blank=True) I applied "python manage.py makemigrations" after changing (models.Model) ---> (BaseModel) and got this... (venv) G:\office\medicover\medicover_bloodbank_django>python manage.py makemigrations You are trying to add the field 'created_at' with 'auto_now_add=True' to blooddiscard without a default; the database needs something to populate existing rows. 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value. The datetime and django.utils.timezone modules are available, so you can … -
pygraphviz cannot be installed in heroku PLEASE HELP ME (HEROKU)
I am trying to deploy django projects using heroku. I set all the dependencies in requirements.txt however, when I push the project to heroku one of the dependency (pygraphviz) keep throws error just like below. I believe that the path is not setted but I do not know how to set the path in heroku Please help me. I believe I need to do something with graphviz/cgraph.h..... remote: [pipenv.exceptions.InstallError]: 2711 | #include "graphviz/cgraph.h```` remote: [pipenv.exceptions.InstallError]: × python setup.py bdist_wheel did not run successfully. remote: [pipenv.exceptions.InstallError]: │ exit code: 1 remote: [pipenv.exceptions.InstallError]: ╰─> [57 lines of output] remote: [pipenv.exceptions.InstallError]: running bdist_wheel remote: [pipenv.exceptions.InstallError]: running build remote: [pipenv.exceptions.InstallError]: running build_py remote: [pipenv.exceptions.InstallError]: creating build remote: [pipenv.exceptions.InstallError]: creating build/lib.linux-x86_64-cpython-39 remote: [pipenv.exceptions.InstallError]: creating build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/testing.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/agraph.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/__init__.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/scraper.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: copying pygraphviz/graphviz.py -> build/lib.linux-x86_64-cpython-39/pygraphviz remote: [pipenv.exceptions.InstallError]: creating build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_edge_attributes.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_attribute_defaults.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_graph.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_string.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/__init__.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_scraper.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_readwrite.py -> build/lib.linux-x86_64-cpython-39/pygraphviz/tests remote: [pipenv.exceptions.InstallError]: copying pygraphviz/tests/test_layout.py … -
How do you crawl a url that has Slug in google search console and social media crawling
is anybody who can tell me how to crawl my url that has slug in google search console and social media crawling system like facebook and twitter: this is the url that I want it to be crawled: path('ViewQuestion/<slug:slug>/', views.viewQuestion, name='view-Question'), this is the template of this url: <meta charset="UTF-8"> <title>Question Page</title> <!--Used by Facebook, Pinterest, Google --> <meta property="og:title" content="Question Page"> <meta property="og:url" content="https://www.borinati.com/ViewQuestion"> <meta property="og:image" content="https://res.cloudinary.com/drivemetech/image/upload/v1655308776/ygnvjkbw8tzeqaxhuwxl.jpg"> <meta property="og:site_name" content="Borinati"> <!--Used exclusively by Twitter --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="View-Question Page"> <meta name="twitter:url" content="https://www.borinati.com/ViewQuestion"> <meta name="twitter:image" content="https://res.cloudinary.com/drivemetech/image/upload/v1655308776/ygnvjkbw8tzeqaxhuwxl.jpg"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> when i try to crawl it on facebook under Sharing Debugger: Bad Response Code URL returned a bad HTTP response code. og:title Not Found is any body who can help please ? -
how to upload custom font w/ django project
I am working on a project w/ Django and I am having trouble with fonts. I am able to see the uploaded font on my computer but not on my phone. This is my file path: static | interface | main.css folsom-black.otf This is my code for my html file <style> @font-face { font-family: 'Folsom'; src: url("{% static 'interface/folsom-black.otf' %} format('otf')"); } </style> This is the code for my css file @font-face { font-family: 'Folsom'; src: url('../interface/folsom-black.otf') format('otf'); } -
Showing error after writing command "pip install mysqlclient" for connecting mysql with django framework
As a beginner, I try to connect mysql with django framework. For connecting mysql with django, I changed the settings.py file of "My_First_Porject" project file after creating a database named "my_first_django" in phpmyadmin - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_first_django', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } After that I write "pip install mysqlclient" command to connect mysql with django. Then when I try to migrate by writing "python manage.py migrate", it shows the following error - Traceback (most recent call last): File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "F:\web-development\django-projects\My_First_Porject\manage.py", line 22, in <module> main() File "F:\web-development\django-projects\My_First_Porject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 401, in execute django.setup() File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "C:\Users\NCC\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in … -
Django changes not reflecting AWS Nginx and got CSRF Failed: CSRF token missing while post a request
I hosted my Django app on AWS with Nginx, gunicorn and Postgres. Now I got 3 issues Django changes not reflecting Style not working CSRF Failed: CSRF token missing while post a request Style not working I added STATIC_URL = '/static/' , STATIC_ROOT = os.path.join(BASE_DIR, 'static') on settings.py and + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) on urls.py. CSRF Failed: CSRF token missing while post a request And I'm not using Django rest framework default authentication But I'm using just my own logic. Here is it @csrf_exempt @api_view(['POST']) def student_login(request): if request.method == 'POST': name = request.data['name'] password= request.data['password'] try: user_obj = Admission.objects.get(name = name, password = password) return Response({"Token": user_obj.student_token}, status=status.HTTP_200_OK) except Admission.DoesNotExist: return Response({"Error": "Invalid username or password!"}, status=status.HTTP_400_BAD_REQUEST) return Response({"Error": "Somthing went wrong!"}, status=status.HTTP_400_BAD_REQUEST) -
checkbox django return all false
My checkbox always return False value my model ho_so_giu=models.BooleanField(default=False) my form ho_so_giu = forms.BooleanField(label="Hồ sơ giữ", widget=forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'ho_so_giu_text', 'name': 'ho_so_giu_text',}),required=False) in my html template <div class="form-check form-switch"> {{form.ho_so_giu}} <label class="form-check-label" for="ho_so_giu_text">Hồ sơ giữ</label> </div> in my view, print(form.cleaned_data["ho_so_giu"]) ## return False print(request.POST.get("ho_so_giu")) ## return None print(request.GET.get("ho_so_giu")) ## return None if I try to print ho_so_giu_text it show errors print(form.cleaned_data["ho_so_giu_text"]) KeyError: 'ho_so_giu_text' I am using ajax to return my value from code ho_so_giu =$('#ho_so_giu_text').val() //return on Thanks for reading anh help me -
Validating List Object in Python API Request from JSON Schema
I have defined the schema for validating django rest api request : { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "required": [ "vmname", "os_env", "topology_id", "boot_type" ], "properties": { "failed_devices_list": { "type": "list", "default": [] }, "os_env": { "type": "string", "description": "Name of environment" }, "vmname": { "type": "string", "description": "Name of the VM" }, "topology_id ": { "type": "integer", "description": "Topology Request ID" }, "boot_type": { "type" : "string", "enum": [ "X", "Y" ], "description": "Type of authentication" } } } Its validating perfectly to all the parameters, except failed_devices_list. Its an optional request argument, which has to be empty by default or should have string objects like : failed_devices_list = ["VM001","VM002"] Not sure, how to do it. Any help, is appreciable. Thank you. -
Celery error when getting settings file through environment variable
In my manage.py file I'm getting the name of the settings file through an environment variable: default = os.environ.get('DJANGO_SETTINGS_MODULE_DEFAULT', 'mysite.settings.base') os.environ.setdefault('DJANGO_SETTINGS_MODULE', default) And then I'm setting DJANGO_SETTINGS_MODULE_DEFAULT to a relevant value in each environment, like mysite.settings.dev1 for a certain developer, mysite.settings.staging for our staging server or mysite.settings.production for production. This has been working fine with our Gunicorn server, launched with Supervisor. But with celery, I'm getting the following error both in the worker and beat logs: django.db.utils.OperationalError: FATAL: role "root" does not exist The full stack trace being: Traceback (most recent call last): File "/home/scheduler/scheduler/mysite/manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "/home/scheduler/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/scheduler/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/home/scheduler/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/scheduler/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/scheduler/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/scheduler/scheduler/mysite/notifications/models.py", line 25, in <module> class TeamAssignmentNotification(ChangeNotification): File "/home/scheduler/scheduler/mysite/notifications/models.py", line 48, in TeamAssignmentNotification def send(self, site=Site.objects.get_current()): File "/home/scheduler/local/lib/python2.7/site-packages/django/contrib/sites/models.py", line 60, in get_current return self._get_site_by_id(site_id) File "/home/scheduler/local/lib/python2.7/site-packages/django/contrib/sites/models.py", line 39, in _get_site_by_id site = self.get(pk=site_id) File "/home/scheduler/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/scheduler/local/lib/python2.7/site-packages/django/db/models/query.py", line 328, in get num = len(clone) File "/home/scheduler/local/lib/python2.7/site-packages/django/db/models/query.py", line … -
Django channels with redis
I am trying to make a chat app in Django with channels. I did it from this video. But the way that is used in the video to make the app is with InMemoryChannelLayer that should not be used for production. Then I tried to make the exact same thing that made from channel docs but it didn't work. The only thing that I didn't write in the tutorial of the docs was the docker run -p 6379:6379 -d redis:5. Am I doing something wrong? Please write me an answer of how to do it. Thanks. -
Authorization flow for Microsoft graph API in django and react
I am trying to integrate Microsoft Graph API with my Django backend application. I want to be able to read, manage and send emails on behalf of users. The frontend is built with React My issue now is how the authorization flow will work. I want users to authorize the app(prolly using Oauth) on the frontend after which I will get some kind of access code that I can save on the backend and subsequently use to make requests to the graph APIs on the user's behalf Pls, how do I achieve this flow ?? Any help will be appreciated. I have been scrambling through the docs all day, need someone to point me in the right direction -
Best way to use Oauth2 (for Google Ads API) in Django (Python)
I'm a Django/Python beginner and I want to use the Google Ads API. To access that API, I need to use Oauth2. I've tried following this official example: https://developers.google.com/google-ads/api/docs/client-libs/python/oauth-web But it doesn't work for me and they say it's just a basic implementation (probably not good for production). They mention another doc (https://developers.google.com/identity/protocols/oauth2/web-server#python), but I get lost there and I'm afraid that even if I could create something that works, I would create code that is buggy or insecure (and I guess authentication is an important part to get the security right). I've seen that there are a lot of Django packages for Oauth and I guess they could be a great option for me: https://djangopackages.org/grids/g/oauth/ But I don't know which packages are better. After reading their descriptions, I'm not even sure of which ones can be used for accessing the Google Ads API using Oauth (what I want) and which ones are for creating your own Oauth authentication system (not what I want). Can you give me some recommendations or at least articles/guides to read about this? Thanks a lot! -
How to open django login form in a modal window?
How can i open dJango modal form in a modal popup window? from django_base.forms import User_registration_form def login_view(request): if request.method == 'POST': form = AuthenticationForm(request, data = request.POST) -
Certbot, Apache, Django - Current configuration does not support automated redirection
I want to add ssl certificate for my domain, let's call it "domain.net" I have VPS on Bluehost, Django on Apache and wanted to add certificate using Certbot. During the installation, I got these messages: Deploying certificate Successfully deployed certificate for domain.net to /etc/apache2/conf/httpd.conf Successfully deployed certificate for www.domain.net to /etc/apache2/conf/httpd.conf Failed redirect for domain.net Unable to set the redirect enhancement for domain.net. NEXT STEPS: The certificate was saved, but could not be installed (installer: apache). After fixing the error shown below, try installing it again by running: certbot install --cert-name domain.net Unable to find corresponding HTTP vhost; Unable to create one as intended addresses conflict; Current configuration does not support automated redirection Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details. How to solve this error? Not sure if that will help but here is a 'apachectl -S' out VirtualHost configuration: 127.0.0.1:80 is a NameVirtualHost default server server.domain.com (/etc/apache2/conf/httpd.conf:300) port 80 namevhost server.domain.com (/etc/apache2/conf/httpd.conf:300) port 80 namevhost proxy-subdomains-vhost.localhost (/etc/apache2/conf/httpd.conf:663) wild alias cpanel.* wild alias whm.* wild alias webmail.* wild alias webdisk.* wild alias cpcalendars.* wild alias cpcontacts.* 127.0.0.1:443 is a NameVirtualHost default server server.domain.com (/etc/apache2/conf/httpd.conf:771) port 443 …