Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending emails with Django, not receiving email
I am trying to implement a contact form in Django. It works locally in the terminal if i change EMAIL_BACKEND to console rather than smtp. I have set up 2FA in Gmail and using this as the password, I am also deploying to Heroku where I have set up the correct config vars. Can anyone see why this might not be working? setting.py file # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER') SERVER_EMAIL = os.environ.get('EMAIL_HOST_USER') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = False EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASS = os.environ.get('EMAIL_HOST_PASS') views.py from django.shortcuts import render, redirect from django.core.mail import EmailMessage, get_connection from django.conf import settings # Create your views here. # https://opensource.com/article/22/12/django-send-emails-smtp def send_email(request): if request.method == "POST": with get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=settings.EMAIL_HOST_USER, password=settings.EMAIL_HOST_PASS, use_tls=settings.EMAIL_USE_TLS ) as connection: name = request.POST.get("name") email_from = settings.EMAIL_HOST_USER recipient_list = [request.POST.get("email"), ] message = request.POST.get("message") EmailMessage(name, message, email_from, recipient_list, connection=connection).send() return render(request, 'contact.html') contact.html <section class="container"> <div class="row justify-content-md-center"> <div class="col-sm-6 center-form"> <h1>Contact Us:</h1> <form method="POST" action="{% url 'mail' %}" id="contact-form"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" name="name" id="name" placeholder="Name" required> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" name="email" id="email" placeholder="Email" required> </div> … -
Add multiple category for one post (drf+React)
I have a blog website built with Django and React. I'm currently working on adding a new blog post feature, and I want to allow users to select one or multiple categories for their blog post. Here's what I have done so far: Fetched all the categories from the database and displayed them in a dropdown/select field. Users can select one or multiple categories from the dropdown. Now, I need help with the next steps. How can I send the selected categories to the database and save them for the new blog post? Any guidance or code examples would be greatly appreciated. import React, { useEffect, useState } from 'react'; import Dashboard from './Dashboard'; import useAxios from '../../utils/useAxios'; function AuthorCreateBlogs() { const baseurl = "http://127.0.0.1:8000/api/posts/v1"; const [selectedCategories, setSelectedCategories] = useState([]); const api = useAxios(); const [categoriesData, setCategoriesData] = useState([]); const [blogData, setBlogData] = useState({ "title": "", "slug": "", "body": "", "tags": "", "categories": [], "img": "", }) const handelInputChange = (event) => { const { name, value } = event.target; setBlogData((blogData) => ({ ...blogData, [name]: value })); }; const handleFileChange = (event) => { setBlogData((blogData) => ({ ...blogData, ['img']: event.target.files[0] // Match the key used in FormData })); }; const … -
Sitemaps in Django
I'm trying to get the dynamic sitemap generator working in my Django blog. I've followed the directions given here, I even went so far as to create a new "recipes" project and worked through the tutorial. I got the sitemap to work in the tutorial, but I can't get it to work in my blog. Can anyone help? Here's the project-level urls.py: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static from django.views.generic.base import TemplateView from django.contrib.sitemaps import GenericSitemap from django.contrib.sitemaps.views import sitemap from blog.models import Post # from blog.sitemaps import BlogSitemap info_dict = { "queryset": Post.objects.all(), "date_field": "date_posted", } urlpatterns = [ path('admin/', admin.site.urls), # path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetView.as_view( template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('', include('blog.urls')), path('summernote/', include('django_summernote.urls')), # Robots.txt path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), # Sitemap # path('sitemap.xml', sitemap, {'sitemaps': {'blog': BlogSitemap}},), path("sitemap.xml", sitemap, {"sitemaps": {"blog": GenericSitemap(info_dict)}},), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's the blog app's urls.py: from django.urls import path from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, … -
"Origin checking failed - null does not match any trusted origins"
I run two servers with two different PORTs on localhost. (localhost:3000 and localhost:4000) I have a post form in localhost:3000 and want to send to localhost:4000 <form action = "http://localhost:4000/print" method = POST> {% csrf_token %} <input type="file" id="myFile" name="filename"> <input type="submit"> </form> in my views.py of localhost:4000 if request.method == "POST": data = request.POST file = data.get("filename") return render(request,"print_success.html",{"form":file}) Error occurs: Origin checking failed - null does not match any trusted origins I don't know why there is origin:null Already tried cors-headers set up -
Django : IsAuthenticated and TokenAuthentication decorated views getting accessed without any Authentication Token
I have used simple-jwt for JWT authentication in a simple To-Do app. For OTP based authentication i have created a custom user model and also overridden the TokenObtainPairSerializer from simple-jwt. My token urls are working fine but my get-todos view getting accessed without any authentication. Github Repo: https://github.com/ShouravAhmed/django-react-practice-code/tree/main/Django/djtodo following is my code snippets. //urls path('get-todos/', get_todos, name='get_todos'), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), //views.py @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) @api_view(['GET']) def get_todos(request): resp = {'status': 200, 'message': 'success'} try: todos = Todo.objects.all() serializer = TodoSerializer(todos, many=True) resp['count'] = len(serializer.data) resp['data'] = serializer.data except Exception as e: resp['status'] = 400 resp['message'] = 'Exception Occered' resp['exception'] = str(e) return Response(resp) // models.py class User(AbstractUser): id = models.CharField(max_length=15, default="") phone_number = models.CharField( max_length=15, unique=True, primary_key=True) full_name = models.CharField(max_length=73, blank=True, null=True) address = models.TextField(blank=True, null=True) total_purchase = models.IntegerField(default=0) points = models.IntegerField(default=0) visit_count = models.IntegerField(default=0) staff_level = models.IntegerField( choices=StaffLevel.choices, default=StaffLevel.USER) created_at = models.DateField(auto_now_add=True, editable=False) updated_at = models.DateField(auto_now=True, editable=False) is_phone_verified = models.BooleanField(default=False) username = models.CharField(max_length=30, null=True, blank=True) def save(self, *args, **kwargs): self.id = self.phone_number super(User, self).save(*args, **kwargs) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['full_name', 'email'] objects = UserManager() // manager.py class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError('phone number is required') user = … -
Django first() for every item
Suppose I have a model EventParticipant, which stores participant data for a given Event. Now I want to retrieve the next event participance for a list of users. The following: EventParticipance.objects.filter(user__in=userlist, start__gte=timezone.now()).order_by(start) would give me all event participances for all users in userlist that start in the future. However, I only want the first one for each user. In Postgres, this could be achieved (I think) by this: EventParticipance.objects.filter(user__in=userlist, start__gte=timezone.now()).order_by(start).distinct('user'). However, this does not work for sqlite or mysql. Obviously, as shown here, this would work, but I suppose it'd be very slow: next_occurrence_ids = [] for user in userlist: id = EventParticipant.objects.filter(user=user, .....).order_by(start).values('id').first() next_occurrence_ids.append(id) return EventParticipant.objects.filter(id__in=next_occurrence_ids Is there any other strategy I could employ? -
ValueError in django python [closed]
ValueError: not enough values to unpack (expected 2, got 1) I'm getting this value error. Even i tried running server/make migrations by removing models also im getting same value error. Anyone help me to solve this error. -
Recover Bulk Deleted items in django framework
Is it possible to recover multiple deleted files in one go using django framework. If so, what are the ways? I tried latest file recovery, it worked. but not sure on multiple files recovery . I am using IDE as pycharm and django admin view. -
Timezone conversion failed due to winter hour change pytz
in my code I am trying to convert a date with pytz timezone, but due to the change to winter hour at 3 am, my code crash. I have two questions : one, why does changing hours makes the timezone conversion crash ? Two, how to avoid this bug ? Here is my code : purchase_date = make_aware( datetime.strptime( sale.findtext('n:purchasedate', namespaces={'n': ns}), '%d/%m/%Y-%H:%M' ), timezone('Europe/Paris') ) Error returned : Traceback (most recent call last): File "/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ purchase_date = make_aware( ^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/timezone.py", line 287, in make_aware return timezone.localize(value, is_dst=is_dst) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pytz/tzinfo.py", line 366, in localize raise AmbiguousTimeError(dt) pytz.exceptions.AmbiguousTimeError: 2023-10-29 02:08:00 Knowing that my code was executed at 3:02 am and the change of hour happened at 3:00 am. Thanks in advance for any response ! -
Assert when ObjectDoesNotExitst is raise
I have this function which raises the ObjectDoesNotExist def is_user_login(self,id): try: u = m.CustomUser.objects.get(id=id) except ObjectDoesNotExist as e: raise e Now I am writing the test script. try: CommonFunc.is_user_login(4) except Exception as e: print(e) self.assertEqual(ObjectDoesNotExist,e) It doesn't work. It shows error like this below , AssertionError: <class 'django.core.exceptions.ObjectDoesNotExist'> != DoesNotExist('CustomUser matching query does not exist.') How can I assert for ObjectDoesNotEqual? -
Django models: have foreign keys in a class return different things
I have following in my django models file : class Category(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='uploads/cats', null=True, blank=True) def __str__(self): return self.name and I want to have foreign key to its name and its image separately like this : class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) category_image = models.ForeignKey(Category.image, on_delete=models.CASCADE, blank=True, null=True) how should I achieve this ? -
unable to access object's property despite it being present
My serializer: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = "__all__" def create(self, validated_data): try: print(validated_data) print(validated_data.author) task = Task.objects.create(**validated_data) return task except BaseException as e: print(e) raise HTTP_400_BAD_REQUEST my view: class TaskCreateApiView(generics.CreateAPIView): serializer_class = TaskSerializer my model: from django.db import models from django.contrib.auth.models import User class Task(models.Model): content = models.CharField( default="", max_length=255, ) author = models.ForeignKey( User, on_delete=models.CASCADE, null=True, ) category = models.CharField( default="", max_length=255, ) def __str__(self): return str(self.id) + self.content My log from serializer: {'content': 'test2', 'category': 'test', 'author': <User: zaq1>} 'dict' object has no attribute 'author' print(validated_data.author) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'dict' object has no attribute 'author' How can I access author? I see it exists as <User:zaq1> but can't seem to access it -
Modifying DJANGO_SETTINGS_MODULE in environment variables
I've come across a very dumb yet irritating problem when running my Django server. When running the server it says: ModuleNotFoundError: No module named 'apolo_client.setting' I don't know where in hell I've set this variable to apolo_client.setting. Obviously it's supposed to be "settings" with as s at the end. I tried manually setting the variable in windows and even in python itself, but it doesn't work. I tried retrieving the variable in init.py file in django's conf folder and it says apolo_client.setting! However running os.environ anywhere else in windows gives the current output. Is there a way I could reset the value or maybe search for the bit where it's being set the wrong valule? -
Failure to display the output despite entering the codes
Despite entering the codes, no output is displayed in this field. What is the reason? in views.py: def category(request, category_id): category = get_object_or_404(Category, pk=category_id) products = category.product_set.all() return render(request, 'category.html', {'category': category, 'products': products}) in urls.py: path("category<int:category_id>", views.category, name="category") in category.html: {% extends "auctions/layout.html" %} {% block body %} <h2>{{ category.name }}</h2> <ul> {% for product in products %} <li>{{ product.category }}</li> {% endfor %} </ul> {% endblock %} in layout.html: <li class="nav-item"> {% for category in categories %} <a class="nav-link" href="{% url 'category' category.id %}">Category</a> {% endfor %} </li> -
Failure to register comments without login
Comments are registered on the desired page, and for people who aren't logged in, if they want to leave a comment, it says to enter the site first, but later the comments are registered under the name AnonymousUser. I don't want this registration to happen. Which part and how should be edited? in views.py: comments = Comment.objects.filter(product=product) if request.method == 'POST': # comment if 'comment' in request.POST: author = request.user content = request.POST.get('content') comment = Comment(product=product, author=author, content=content) comment.save() context = { 'comments': comments, } return render(request, 'auctions/product_detail.html', context) in product_detail.html: <h3 id="h3">Comments</h3> {% if user.is_authenticated %} <ul> {% for comment in comments %} <li><a>{{ comment.author }} : {{comment.content}}</a></li> {% endfor %} </ul> {% else %} Not signed in. {% endif %} ` Thanks in advance for your help -
how to store checkboxes in database?
i want to make a website which can save the seats of the plane for a user but i am facing trouble storing these checkboxes in database and have no idea how to make it so that the checkboxes remain when i revisit the webpage with logged used this is my models.py from django.db import models # Create your models here. class Logs(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=200) email=models.EmailField(max_length=200,unique=True) password=models.CharField(max_length=200) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def get_special_combination_value(self): return '{}{}'.format(self.name,self.password) this is my views.py from django.db import models # Create your models here. class Logs(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=200) email=models.EmailField(max_length=200,unique=True) password=models.CharField(max_length=200) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def get_special_combination_value(self): return '{}{}'.format(self.name,self.password) this is my plane.html(shortened version) <!DOCTYPE html> <html> <head> <style> .container { display: flex; justify-content: center; align-items: center; height: 100vh; } .a, .b { transform: scale(2.5); } .b { margin-left: 200px; /* Add margin between the two divs */ } /* Additional CSS to adjust the layout */ .a, .b { display: inline-block; } #sub { margin-bottom: -200px; } </style> </head> <body> <div class="container"> <form method="POST" action=""> {% csrf_token %} <div class="a"> <table> <tr> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> </tr> <tr> <td> <input type="checkbox" name="seat"> </td> <td> <input type="checkbox" name="seat"> </td> <td> … -
How to get the "overall" counter of an object in a group in a Django template?
I'm using Django's regroup template tag to group a series of objects. Let's say these are the objects: cities = [ {"name": "Mumbai", "population": "19,000,000", "country": "India"}, {"name": "Calcutta", "population": "15,000,000", "country": "India"}, {"name": "New York", "population": "20,000,000", "country": "USA"}, {"name": "Chicago", "population": "7,000,000", "country": "USA"}, {"name": "Tokyo", "population": "33,000,000", "country": "Japan"}, ] In my template, I'm grouping them like this: {% regroup cities by country as country_list %} <ul> {% for country in country_list %} <li>{{ country.grouper }} <ul> {% for city in country.list %} <li>{{ city.name }}: {{ city.population }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> Which results in India Mumbai: 19,000,000 Calcutta: 15,000,000 USA New York: 20,000,000 Chicago: 7,000,000 Japan Tokyo: 33,000,000 I would like to show an "overall" index for each object, so that it looks like this: India 1: Mumbai: 19,000,000 2: Calcutta: 15,000,000 USA 3: New York: 20,000,000 4: Chicago: 7,000,000 Japan 5: Tokyo: 33,000,000 I'm not asking for an HTML solution; my use case is a series of grouped questions and I would like to add a question counter. Is there a way to do this in the template, or should I write the necessary code in my view? -
IntegrityError at /todo NOT NULL constraint failed: todo_todo.name i don't have a Foreign key only a name charfield
models.py from django.db import models # Create your models here. class ToDo(models.Model): name = models.CharField(max_length=200, default=" ") views.py from django.shortcuts import render, HttpResponse from .models import ToDo # Create your views here. def home(request): # temp = ToDo.objects.all() # context = {'temp':temp} data = request.POST.get('name') print(data) context = {'data':data} return render(request, "todo/home.html", context) def todo(request): # temp = ToDo.objects.all() # context = {'temp':temp} name = request.POST.get('name') todo = ToDo(name=name) todo.save() context = {'names' : todo} return render(request, "todo/todo.html", context) todo.html <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <h1>TO DO LIST</h1> <form method="post" action="/todo"> {% csrf_token %} <label for="name"> </label> <input type="text" name="name" id="name"> <br> <button type="submit">Add Task</button> </form> {% for x in names %} <h4>{{ x.name }}</h4> {% endfor %} </body> </html> I have tried changing name's and id's everything that was there in youtube but no solution I don't know where the error is occuring in the error page it shows todo.save() has the error but i don't know where the error is occuring at please help :( -
Django ORM, How to join a dropped table, with multiple conditions
class Post(Common): author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() class Comment(Common): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() class Test(Common): post = models.ForeignKey(Post, on_delete=models.CASCADE) tester = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category) class Category(Common): pass I want to find a query (Inner JOIN test ON Test.post _id = Comment.post _id AND Test.tester_id = Comment.author_id) to specify two conditions for the join syntax when executing the query based on the following Comment table, but I leave a question because it is hard to find. -
How to solve jquery datatables repeated search and pagination rows?
I am using HTMX (for Ajax requests) and JQuery Datables in a django project, but I am experiencing a weird issue. Indeed the datatables work fine, but repeat search and pagination rows when I navigate history using the browser forward or back buttons. I assume it has to do with htmx given that when issuing Ajax requests the new content will replace the old one and the tables will probably be reinitialized with no page refresh I'd be happy if you could help. Thanks -
Django - Running pip as the 'root' user can result in broken permissions
I'm deploying my Django backend utilizing the AWS app runner service. The contents of my files are as follows. apprunner.yaml version: 1.0 runtime: python3 build: commands: build: - pip install -r requirements.txt run: runtime-version: 3.8.16 command: sh startup.sh network: port: 8000 requirements.txt asttokens==2.2.1 backcall==0.2.0 category-encoders==2.6.0 certifi==2023.7.22 charset-normalizer==3.3.0 colorama>=0.2.5, <0.4.5 comm==0.1.3 contourpy==1.0.7 cycler==0.11.0 debugpy==1.6.7 decorator==5.1.1 distlib==0.3.7 executing==1.2.0 filelock==3.13.0 fonttools==4.40.0 gunicorn==20.1.0 idna==3.4 ipykernel==6.23.2 ipython>=7.0.0, <8.0.0 jedi==0.18.2 joblib==1.2.0 jupyter_client==8.2.0 jupyter_core==5.3.0 kiwisolver==1.4.4 matplotlib==3.7.1 matplotlib-inline==0.1.6 nest-asyncio==1.5.6 numpy==1.24.2 opencv-python==4.7.0.68 packaging==23.0 pandas==1.5.3 parso==0.8.3 patsy==0.5.3 pickleshare==0.7.5 Pillow==9.5.0 pipenv==2023.10.24 platformdirs==3.11.0 prompt-toolkit==3.0.38 psutil==5.9.5 pure-eval==0.2.2 pycodestyle==2.10.0 pygame==2.1.3 Pygments==2.15.1 pyparsing==3.0.9 python-dateutil==2.8.2 pytz==2022.7.1 pyzmq==25.1.0 scikit-learn==1.2.1 scipy==1.10.0 seaborn==0.12.2 six==1.16.0 stack-data==0.6.2 statsmodels==0.13.5 threadpoolctl==3.1.0 tornado==6.3.2 traitlets==5.9.0 urllib3>=1.25.4, <1.27 virtualenv==20.24.6 wcwidth==0.2.6 whitenoise==6.4.0 startup.sh #!/bin/bash python manage.py collectstatic && gunicorn --workers 2 backend.wsgi By the way all the packages are installed successfully in the AWS app runner, finally it gives 10-29-2023 02:39:34 AM [Build] [91mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv 10-29-2023 02:39:34 AM [Build] [0mRemoving intermediate container 4a0110123b9d 10-29-2023 02:39:34 AM [Build] ---> fca9ca934529 10-29-2023 02:39:34 AM [Build] Step 5/5 : EXPOSE 8000 10-29-2023 02:39:34 AM [Build] ---> Running in c8a4669398b0 10-29-2023 02:39:34 AM … -
Python Django OAuth toolkit postman works fine but unsupported_grant_type using expo with axios
So this is a little strange of a problem. I'm using Python Django 4.2.5 as my back-end while my front-end is React Native with Expo and Axios 1.6 for all HTTP requests. For authentication, I'm using django-oauth-toolkit version 2.3.0. Now the problem is that Postman does fine with the /o/token/ request to fetch an OAuth2 token, however I keep getting the unsupported_grant_type error with Axios. Here is my configurations on Postman (disclaimer: I know this password looks somewhat realistic. I do not use this for anything else. I'm only using a somewhat complex one in a dev environment because Django Admin is smart about minimum password complexity): What the response to this Postman request is, is this: I try the same thing in Axios: axios .post(DEV_DOMAIN, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br' }, client_id: CLIENT_ID, client_secret: CLIENT_SECRET grant_type: 'password', username: username, password: password }) , but I get this: (I redacted the host, client ID and client secret, I quadruple-checked and they're the same as in Postman) {"message":"Request failed with status code 400","name":"AxiosError","stack":"AxiosError: Request failed with status code 400\n at settle (http://192.168.1.222:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&lazy=true:147573:37)\n at onloadend (http://192.168.1.222:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&lazy=true:147469:29)\n at call (native)\n at dispatchEvent (http://192.168.1.222:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&lazy=true:31756:31)\n at setReadyState (http://192.168.1.222:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&lazy=true:30386:29)\n at … -
Use of django-modeltranslation with django-filter
I'm constructing Django-based 4-language website for a real estate agency. I'm using django-modeltranslation for translation and django-filter package to filter property objects by certain parameters, such as type (house, apartment, etc.), city and some others. The 'type' of a property is a foreign key of the related model 'Type'. It uses ModelChoiceFilter to select all available types from the database, and render them as a select element with options, which is and is displayed as a drop list with options, which is good so far. class SalePropertyFilter(FilterSet): ... type = ModelChoiceFilter( queryset=Type.objects.all(), empty_label=_("Any type"), label="", widget=forms.Select(attrs={'class': 'form-control'}), ) However, the drop-down list looks ugly, since the field label is not translated, and the options are displayed as slug names of the related model. What I want is that options are displayed as common names of types (which are in the field 'name') instead of slug names, and they should be translated. That means, in the English version of the site options should be rendered from the field 'name_en', in the Spanish version - from 'name_es', etc. There should be a proper way to do it. Please, help, I'm stuck! -
django.db.utils.OperationalError: no such table: auth_user; but works with django admin
i am beginner to django and learn how to create custom user model using abstractuser in my accounts app. But while creating registration system I got this issue: django.db.utils.OperationalError: no such table: auth_user Request URL: http://localhost:8000/accounts/register/ Django Version: 4.2.6 Python Version: 3.11.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig'] Installed 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'] Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: auth_user) was the direct cause of the following exception: File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/home/qrkeeper/accounts/views.py", line 55, in post user.save() ^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/contrib/auth/base_user.py", line 76, in save super().save(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 814, in save self.save_base( ^ File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 877, in save_base updated = self._save_table( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 1020, in _save_table results = self._do_insert( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/base.py", line 1061, in _do_insert return manager._insert( File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in … -
Django profile update comes out as an error
I have been developing a blog and facing the same issue again and again. "" p_form = ProfileUpdateForm(instance=request.user.profile) "" This part of the code is showing an error and I have no idea what to do. I have tried everything. The error is ""Exception Value: User has no profile."" I tried manually creating a profile. No use. Please help