Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding file in django 3.0
I'm trying to add a file in a form.In my views.py i am trying to fetch subject_id from subject model and session_year_id from SessionYearModel. But it is not processing.and gives a message of "Failed to add Notes". Below is the code. My views.py def staff_add_notes_save(request): if request.method != "POST": return HttpResponseRedirect(reverse("staff_apply_leave")) else: subject_id = request.POST.get("subject_id") session_year_id = request.POST.get("session_year_id") notesfile1 = request.FILES["notesfile"] subject_model = Subjects.objects.filter(id=subject_id) session_model = SessionYearModel.object.filter(id=session_year_id) try: notes = Notes.objects.create(subject_id=subject_model,session_year_id=session_model,notesfile=notesfile1) notes.save() messages.success(request, "Successfully added Notes") return HttpResponseRedirect(reverse("staff_add_notes")) except: messages.error(request, "Failed to add Notes") return HttpResponseRedirect(reverse("staff_add_notes")) staff_add_notes.html(TEMPLATE) <form role="form" action="/staff_add_notes_save" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label>Subject </label> <select class="form-control" name="subject" id="subject"> {% for subject in subjects %} <option value="{{ subject.id }}">{{ subject.subject_name }}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Session Year</label> <select class="form-control" name="session_year" id="session_year"> {% for session_year in session_years %} <option value="{{ session_year.id }}">{{ session_year.session_start_year }} TO {{session_year.session_end_year }}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Add notes</label> <input type="file" name="notesfile" class="form-control"> </div> <div class="form-group"> {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alert alert-danger" style="margin-top:10px">{{ message }}</div> {% endif %} {% if message.tags == 'success' %} <div class="alert alert-success" style="margin-top:10px">{{ message }}</div> {% endif %} {% … -
Using django pytest with multiple config files
I am using Django with multiple configuration files for different environments that get detected automatically. For this, I pretty much have a setup like this: settings |__init__.py |base.py |dev.py |staging.py in init.py I configure how base.py should be extended depending on the environment like this: import os if os.getenv('STAGING_APP', None): from .staging import * else: #dev environment from .dev import * Now when I use pytest, the extensions aren't loaded and the settings are incomplete. The pytest.ini looks like this: DJANGO_SETTINGS_MODULE = settings.base How can I make it clear in the ini file that settings.base has to be extended with either dev or staging? -
Django template blocks not appearing in correct place in rendered template - resulting in jQuery "$ is not defined" error
I am using Django 3.2 This is my base template (snippet): {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content={% block page_description %}""{% endblock page_description %}> <meta name="keywords" content={% block page_keywords %}""{% endblock page_keywords %}> <link rel='icon' href='{% static "img/favicon.ico" %}' type='image/x-icon'/ > <title>{% block page_title %}Demo{% endblock page_title %}</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans%3A400%2C300%2C500%2C600%2C700%7CPlayfair+Display%7CRoboto%7CRaleway%7CSpectral%7CRubik"> <link rel="stylesheet" href="{% static 'css/footer.css' %}"> <link rel="stylesheet" href="{% static 'css/header.css' %}"> {% block head_styles %} {% endblock head_styles %} {% block head_js %} {% endblock head_js %} </head> <body> {% block header %} {% include "partials/header.html" %} {% endblock header %} {% block messages %} {% include 'partials/messages.html' %} {% endblock messages %} <!-- Page Content --> <div class="d-flex flex-column sticky-footer-wrapper"> {% block content %} {% endblock content %} </div> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script> <!-- Bootstrap core JavaScript --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> <!-- Site footer --> {% block footer %} {% include 'partials/footer.html' %} {% endblock footer %} {% block body_js %} {% endblock body_js %} <script> $().ready(function() { }); </script> </body> </html> /path/to/header.html {% load … -
Password reset view, email is not sending
after resetting password Im instantly redirecting to the password_reset/done view and im not receiving the email. I send email manually to chceck if its working and everything is ok, so the problem is with the " path('password_reset/', auth_views.PasswordResetView.as_view(success_url=reverse_lazy('profile:password_reset_done')), name='password_reset'), ", Is this problem with the app_name or something, I cant find any working solution to this from django.urls import path, reverse_lazy from .views import ProfileDetail, FollowUser, RegisterUser from django.contrib.auth import views as auth_views app_name = 'profile' urlpatterns = [ path('<slug:slug>/profile/', ProfileDetail.as_view(), name='profile-details'), path('follow/', FollowUser.as_view(), name='follow'), path('register/', RegisterUser.as_view(), name='register'), path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_reset/', auth_views.PasswordResetView.as_view(success_url=reverse_lazy('profile:password_reset_done')), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] main urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('post.urls', namespace='post')), path('profile/', include('user_profile.urls', namespace='profile')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings config: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = *** EMAIL_HOST_PASSWORD = *** DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
Server logged HTTP status code of 200, but Chrome HAR shows 403 - can the HTTP status code change?
I work on an application that uses Django / Gunicorn / Nginx / Amazon Load Balancer (ALB). A user that only has access to Chrome has submitted two different HAR files that have recorded a 403 for a simple JSON API endpoint that hasn't been known to have issues for other users. According to our logs from Nginx and Django middleware, those API requests returned 200 for that particular user. Primary Questions The network - Practically speaking, is there any likely scenario which can cause an intermediary network to change a 200 to a 403 by the intermediary network? For example, is there any plausible scenario in which a compromised router attempting a MITM attack could cause a 200 to change into a 403? The browser - Is there anything in particular about HAR files or Chrome in general which could cause a browser to take a 200 as a 403? For example, if a user's clock is off or a checksum on a packet is invalidated, could that result Secondary questions Nginx - Is there anything that could cause Nginx to record a 200 when a 403 was returned? ALB - Is there any situation in which ALBs can … -
How i can display only products uploaded by particular user?
First, i say that i am new programming django with python. Sorry, if asked small problems. And also , its seems a long code, but very clean. The problem I am facing that I want to display only user's products which is uploaded by him, not by admin or other user. [[like a user using his dashboard and seeing his products and items .]] Here is my models.py: #Product details uploaded class AffProduct(models.Model): product_title = models.CharField(max_length=255) uid = models.IntegerField(primary_key=True) specification = models.CharField(max_length=255) sale_price = models.IntegerField() discount = models.IntegerField() img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") promote_method = models.TextChoices terms_conditions = models.CharField(max_length=255) promote_method = models.CharField( max_length=20, choices=promote_choices, default='PPC' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: app_label = 'affiliation' db_table = 'affproduct' managed = False Here views.py: def AddNewProduct(request): if request.method == "POST": product_title =request.POST['product_title'] uid = request.POST['uid'] specification =request.POST['specification'] sale_price = request.POST['sale_price'] discount = request.POST['discount'] img1 = request.FILES['img1'] img2 = request.FILES['img2'] promote_method = request.POST['promote_method'] terms_conditions = request.POST['terms_conditions'] newproduct = AffProduct(product_title=product_title, uid=uid, specification=specification, sale_price=sale_price, discount=discount, img1=request.FILES.get('img1'), img2=request.FILES.get('img2'), promote_method=promote_method, terms_conditions=terms_conditions) newproduct.save() ##** Here I am trying to fetch products uploaded by the particular user,So i can display products for particular user.{It,s like user using his dashboard … -
Using Django, why do I get a 404-error page not found, when I try to acces a page that should exist?
I made a project called trydjango where I can access products I created with the products/<int:my_id> [name='product'] link, but somehow it isnt working and I cant find the error. When i open http://127.0.0.1:8000/products/1/ , i get a 404 page not found error that looks like this Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/1/ Using the URLconf defined in trydjango.urls, Django tried these URL patterns, in this order: products/<int:my_id> [name='product'] products/ [name='product-list'] products/<int:my_id>/delete/ [name='product-delete'] about/ [name='home'] contact/ admin/ create/ initial/ The current path, products/1/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. even though i have a product with the id=1 saved. I'm using the URL that I have configured in URL's and I can see that a product with the correct id exists when I access it from the page http://127.0.0.1:8000/products/, where I can see a list of all products with their id's. This is my url's: from django.urls import path from pages.views import home_view, contact_view, about_view from products.views import ( product_list_view, product_delete_view, product_create_view, render_initial_data, dynamic_lookup_view, ) urlpatterns = [ path("products/<int:my_id>", dynamic_lookup_view, name='product'), … -
Django-Python log error on MS Azure web app
Good afternoon, we have a Django web app deployed on MS Azure (App Service). We are unable to open correctly the log stream of the Web App by using the shell (local-cmd OR MS Azure shell on dashboard, same error). Here the attempt to open the log stream on Azure dashboard: user@Azure:~$ az webapp log tail --resource-group OUR_RESOURCES_GROUP --name OUR_WEB_APP_NAME Exception in thread Thread-1: Traceback (most recent call last): File "/opt/az/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/opt/az/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/custom.py", line 2345, in _get_log .decode(std_encoding, errors='replace'), end='') # each line of log has CRLF. File "/opt/az/lib/python3.6/logging/__init__.py", line 1320, in warning self._log(WARNING, msg, args, **kwargs) TypeError: _log() got an unexpected keyword argument 'end' Microsoft support tell us that this is a configuration problem, but we checked some times the python version and the other few configurations. May anyone help ? Thanks -
Put a button in the creation of a model
I would like to make sure that in addition to the title, color and description, I would like to make sure that when I create a model it makes me choose which url to render it when Ia person clicks the button. It's possible? models.py from django.db import models from colorfield.fields import ColorField class Aziende(models.Model): immagine = models.ImageField() nome = models.CharField(max_length=250) prezzo = models.FloatField() descrizione = models.CharField(max_length=250) nome_color = ColorField(default='#FF0000') def __str__(self): return self.nome class Meta: verbose_name_plural = "Aziende" home.html [...] <div class="container"> <div class="row"> {% for Aziende in Borsa %} <div class="col"><br> <div class="container text-center"> <div class="card" style="width: 18rem;"> <img src="{{ Aziende.immagine.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="title" style="color: {{Aziende.nome_color}}" >{{Aziende.nome}}</h5> <p class="card-text">{{Aziende.descrizione}}</p> <p class="card-text fst-italic text-primary">Valore Attuale: €{{Aziende.prezzo}}</p> <a href="#" class="btn btn-primary">Più info</a> </div> </div> </div> </div> {% endfor %} </div> </div> [...] Thanks in advance! -
Correct approach to creating API endpoints
I'm creating an API in Django Rest Framework and i'm thinking about best approach to provide actions like adding a post to user reading list. Firstly i've done it by GET request, because it was looking most natural and url for example looks like /api/posts/{id}/add_to_reading_list/. Now i recognized that GET should be used only to retrieve data so i've changed it to POST method and now url is looking like /api/posts/add_to_reading_list/. The first thing is that i needed to create new serializer specially to handle this action which accepts only id field, because this endpoint should accept only already created posts. Is it how it should be done? I was thinking about sending whole post object in POST method, but doesn't it a waste of bandwidth when i need only id? It will prevent me of creating a new serializer for this specific case, but i don't think that it is a correct approach. -
CAS django - how to send username and password directly without redirecting to CAS server -
i'm using this code from django.http import HttpRequest, HttpResponse from .signals import cas_user_authenticated_callback import json from rest_framework.response import Response from django_cas_ng.views import LoginView from .ldap import get_LDAP_user from datetime import timedelta from importlib import import_module from urllib import parse as urllib_parse from django.conf import settings from django.contrib import messages from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.core.exceptions import PermissionDenied from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect from django.utils import timezone from django.utils.decorators import method_decorator from django.utils.translation import gettext_lazy as _ from django.views import View from django.views.decorators.csrf import csrf_exempt from django_cas_ng.models import ProxyGrantingTicket, SessionTicket from django_cas_ng.signals import cas_user_logout from django_cas_ng.utils import ( get_cas_client, get_protocol, get_redirect_url, get_service_url, get_user_from_session, ) SessionStore = import_module(settings.SESSION_ENGINE).SessionStore __all__ = ['LoginView', 'LogoutView', 'CallbackView'] def clean_next_page(request, next_page): """ set settings.CAS_CHECK_NEXT to lambda _: True if you want to bypass this check. """ if not next_page: return next_page is_safe = getattr(settings, 'CAS_CHECK_NEXT', lambda _next_page: is_local_url(request.build_absolute_uri('/'), _next_page)) if not is_safe(next_page): raise Exception("Non-local url is forbidden to be redirected to.") return next_page def is_local_url(host_url, url): url = url.strip() parsed_url = urllib_parse.urlparse(url) if not parsed_url.netloc: return True parsed_host = urllib_parse.urlparse(host_url) if parsed_url.netloc != parsed_host.netloc: return False if parsed_url.scheme != parsed_host.scheme and parsed_url.scheme: return False url_path = parsed_url.path if parsed_url.path.endswith( '/') … -
Why is the password stored in a raw format to the database in Django? [closed]
I have this Serializer: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): name = validated_data['name'], id = validated_data['id'], user = Person.objects.create(name=name, password=validated_data['password'], id=id) return user I thought that passwords are automatically saved as hashs in the database but with this serializer the password is saved in a raw format. How could I modify this to save the hash, not the raw version? -
Matplotlib unaligned values and names of graphs
Good day! I am making a django app that would plot graphs from a text document. In the text document data is aligned this way: name 10 name_2 20 name_3 100 typeofthegrah I just split everything by spaces and put in 2 lists (names and values), then I just do plt.bar(names, values) and get something like this name1 189 name2 149 name3 23 name4 82 name5 245 name6 90 column I tried sorting them with zip but it didn't work. It works perfectly if I plot it as a pie chart but linear and bar graphs are broken. -
href in <a> tag not working inside <li> DJANGO
href in a tag inside li don't woriking. It does not redirect me to /sub1/. This is my code: body, html { margin: 0; font-family: Arial, sans-serif; font-size: 1em; } .navbar { width: 100%; background-color: #4682B4; height: 80px; color: #fff; } .navbar .nav { margin: 0; padding: 0; float: left; list-style-type: none; } .navbar .nav li.nav-item { float: left; margin: 0 95px; } .navbar .nav li.nav-item>a { display: inline-block; padding: 15px 20px; height: 50px; line-height: 50px; color: #fff; text-decoration: none; } .navbar .nav li.nav-item>a:hover { background-color: #B0C4DE; } .dropdown a:focus { background-color: #B0C4DE; } .dropdown a:focus~.dropdown-container { max-height: 500px; transition: max-height 0.5s ease-in; -webkit-transition: max-height 0.5s ease-in; -moz-transition: max-height 0.5s ease-in; } .dropdown-container { position: absolute; top: 80px; max-height: 0; overflow: hidden; background: #4682B4; color: #B0C4DE; } .dropdown-container a { color: #fff; text-decoration: none; } .dropdown-menu { margin: 0; padding: 0; list-style-type: none; } .dropdown-menu li a { display: inline-block; min-width: 250px; padding: 15px 20px; border-bottom: 1px solid #333; } .dropdown-menu li a:hover { text-decoration: none; background: #B0C4DE; } <body> <nav class="navbar"> <ul class="nav" id="primary-nav"> <li class="nav-item"><a href="/index/">Home</a></li> <li class="nav-item dropdown"> <a href="#">Servicios</a> <div class="dropdown-container"> <div class="dropdown-inner"> <ul class="dropdown-menu"> <li class="dropdown-menu-item"><a href="/sub1/">Submenu 1</a></li> <li class="dropdown-menu-item"><a href="#">Submenu2</a></li> </ul> </div> </div> </li> … -
update_or_create still creates duplicates after unique together
@require_http_methods(["POST"]) @login_required def edit_guided_answer(request): req = json.loads(request.body) question_no = req["question_no"] guided_answers = req["guided_answer"] for guided_answer in guided_answers: models.ModelAnswer.objects.filter(pk=question_no).update_or_create( question_id=models.Questions.objects.get(pk=question_no), answer_mark=guided_answer["answer_mark"], model_ans=guided_answer["model_ans"],, ) return success({"res": True}) class ModelAnswer(models.Model): question_id = models.ForeignKey( Questions, on_delete=models.CASCADE, db_column="question_id" ) answer_id= models.AutoField(primary_key=True) answer_mark = models.FloatField() model_ans = models.TextField(null=True) class Meta: unique_together = (('model_ans', 'answer_mark' ),) db_table = 'MODEL_ANSWER' Update_or_create still makes duplicate entries even after putting unique_together for model_ans and answer_mark is there something that i am missing and is there a way to set a condition so that i can check for duplicates -
Reload virtual enviroment In django
I'm at my first experience with django and I'm having already a little obstacle: I've menaged to create and use a virtual enviroment successufully yesterday, but today I can't seem to be able to reload it. This is how I'm doing it: cd /c/website python -m venv virt spurce virt/scripts/activate cd /c/website/project python manage.py runserver And this is the error I'm getting Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( 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? (virt) before doing some mistakes, do I need to reinstall django everytime or I'm just messing up the procedure to reload the ve I created? Thanks for your help! -
Django and Bootstrap columns
I want to create a row with 3 columns using Bootstrap and Django dynamic content that I want to get in those columns. However, with the code below, my content goes one below the other for some reason. Any help is appreciated. 🙏 {% extends 'base.html' %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-lg-4 col-sm-12"> {% for post in object_list %} {% if post.is_on_home_page is True %} <a href="{% url 'categories' post.category.slug %}"> {{ post.category }} </a> {% if post.home_or_category_image %} <img class="img-fluid" src="{{ post.home_or_category_image.url }}"> {% endif %} {{ post.author }} <a href="{% url 'article-detail' post.slug %}"> {{ post.title }} </a> {{ post.snippet }} {% endif %} {% endfor %} </div> </div> </div> {% endblock %} -
How to authenticate wordpress wp_remote_post() while sending data to django API view
I am sending some JSON data using wp_remote_post() in wordpress to another django API view, and I'm able to send the data but don't know how to build some security authentication during this wp_remote_post() and django communication. wp_remote_post( 'target url', data ); -
DRF How to use the same variables for multiple functions in test classes?
gal I need to use global variables (class instances) in order to implement them in suitable functions. class MyTests(APITestCase): my_data = 'xxx' User.objects.create(username='any',email='any@g.com',passowrd='pass',) lg_res = client.post('/users/login/', login_data, format='json') client.credentials( HTTP_AUTHORIZATION=f'Bearer {lg_res.data["access"]}') def test_one(self): self.client(bla bla bla) print('======================') print(self.my_data) ##this is fine it work print('======================') def test_two(self): # I need here to login the same user again self.client(bla bla bla2) problems When I when I create new user inside the functions it work very fine Also, I am not sure how to add client credentials outside the functions,I assume somthings like Class MyTests(APITestCase): client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: users_user.email -
How to add a second password to a Django user account for a secured area
I would like my users to have two passwords, the normal login password and one for accessing more secure areas of the site. I would like to rely on the existing Django authentication system as much as possible for this. I am picturing logging in to a secure area with this password would enable a "secure mode" with a fairly short timeout, similar to how sudo does not ask for a password for a while after use in some linux distros. So it would add a flag and a timestamp to the user session. I assume achieving this would involve replacing the default User model with a subclass with an extra password field and some kind of custom middleware, however I have not customised Django auth before and I'm not sure where to start. I am also open to alternate suggestions for how to manage the secure area. -
Django rest framework AttributeError after GET request
During a GET request, Django give me this error: Got AttributeError when attempting to get a value for field `name` on serializer `projectSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `ProjectTask` instance. Original exception text was: 'ProjectTask' object has no attribute 'name'. I'm pretty new to django and rest_framework, here's the code: models.py class Project(models.Model): name = models.CharField(max_length=50) class ProjectTask(models.Model): project = models.ForeignKey(Project,on_delete=models.CASCADE) description = models.CharField(max_length=200) status = models.IntegerField() serializers.py class projectTaskSerializer(serializers.ModelSerializer): class Meta: model = ProjectTask fields = ['description','status'] class projectSerializer(serializers.ModelSerializer): tasks = projectTaskSerializer(many=True) class Meta: model = Project fields = ['name','tasks'] views.py (I'm only mentioning the get function that is being called to avoid cluttering the question def get(self, request): projects = ProjectTask.objects.all() serialized_projects = projectSerializer(projects,many = True) return Response({'projects' : serialized_projects.data}) -
Django AllAuth Facebook: Cant login: Social Network Login Failure An error occurred while attempting to login via your social network account
I have been using Django AllAuth to login to my Django App on my localhost before. It had been working fine then suddenly today I started getting this message when trying to login via Facebook : Social Network Login Failure An error occurred while attempting to login via your social network account. These are the configs for my FB App: FB App Config FB App Config 2 FB App Config 3 FB App Config 4 FB App Config 5 FB App Config 6 My Django AllAuth Config: Django AllAuth Config Please suggest how I can fix this and get AllAuth working. If you have any other suggestions, or alternatives, its greatly appreciated. Thanks! -
Unable to render a template after using fetch in django
I have the following requirement: Send data to backend using fetch() receive the data in a view and render another template ( route to a different view) The following is my code snippet: JS: fetch("/addpost", { method: "POST", body: JSON.stringify({ value: selecteddict }), headers: { "Content-type": "application/json;", }, }) .then((res) => { return res.text(); }) .then((text) => { console.log(text); }); // the data is being sent successfully Django View1: @csrf_exempt def addpost(request): if request.method == 'POST': song = json.loads(request.body.decode('utf-8'))['value'] print(song) # I want to redirect to another view called createpost that renders a new page return JsonResponse({'status':201}) return render(request, 'addpost.html') Django createpost view: def createpost(request): return render(request, 'createpost.html') The view createpost is working fine when given the required path but it is not rendering when it's redirected from addpost Please suggest a solution to this. -
How to redirect to a url with parameters in django while using 'return redirect()' from inside a view?
I looked up this question on stack overflow and all the previous related answers are very old which seem to no longer work in newer versions of django . Basically I have a url : urlpatterns = [ .... path('proudct-settings/<int:product_id>',views.product_settings, name="product_settings"), .... ] How do I redirect to this url from this view : @login_required def remove_discount(request, product_id): product = Product.objects.get(id=product_id) product.discount_flag = False product.discount_amount = 0 product.price = product.original_amount product.save() # this return statement for redirecting to url isnt working when I pass the parameter like this return redirect('product_settings',product_id) How can I achieve this redirection to url with parameters using redirect from inside the view ? -
How to get the fields of a django model?
I am creating an API that takes the fields of a model. Say from django.db import models class Student(models.Model): name = models.CharField(max_length=24) age = models.IntegerField() address = models.CharField(blank=True) I want to make an API that takes argument something like this. from typing import Optional from dataclasses import dataclass from models import Student from django.forms.models import model_to_dict @dataclass class RequestStructure: name: str age: int address: Optional[str] def createStudent(req:StudentInfo) -> StudentInfo: data = Student.objects.create(name=req.name, age=req.age, address=req.address) return {"data": model_to_dict(data)} The above code will work fine, but there I have to define the same type for Student which I have already defined in the model. Can I use the model definition as the param type annotation instead of defining it again?