Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is another way to implement apple sign-in in a django API project without creating an apple developer profile?
Apple bills $99 to create a developer profile. Is there a way to override that step in implementing apple sign-in in my django project ? I tried implementing apple sign in and was expecting to create a free developer profile but unfortunately, I was asked to pay the sum of $99 -
Django numerical RangeField (for SQLite)
After reading the docs for custom model fields of Django 5.0 I'm not sure if or how it's possible to create a ModelField that resembles a range between two numerical (integer) values, since I can only serialize into a single db_column, not into two (min of range, max of range column). Am I wrong? Is there a possibility I don't see? I know for PostgreSQL there are different RangeFields available. -
Dj-rest-auth "CSRF Failed: CSRF token missing"
When I am trying to post data using my dj-rest-auth api http://localhost:8000/dj-rest-auth/login/ it gives this error CSRF Failed: CSRF token missing. How do I fix this as I am unable to find the CSRF value to put into headers. Where can I actually find this value. This is my settings for dj-rest-auth in views.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ), } REST_AUTH = { 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'jwt-auth', } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_VERIFICATION = 'optional' AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by email 'allauth.account.auth_backends.AuthenticationBackend', ] Tried sending a get request to this api but the method isn't allowed Tried putting the csrf value of localhost:8000 in my headers which I got from mozilla firefox in the storage/cookies section. But it said the csrf value is incorrect. -
How to handle - Error in save method in Django Model
This is my model: class Sale2021(models.Model): Id = models.AutoField(primary_key=True) cust_name = models.CharField(max_length=120) class= models.CharField(max_length=120) cust_id = models.CharField(max_length=120) branch_desc = models.CharField(max_length=120) cust_desc = models.CharField(max_length=120) month_year = models.CharField(max_length=120) distance_in_kms = models.CharField(max_length=120) def save(self, *args, **kwargs): # Use the get_or_create method with your unique identifier(s) obj, created = Sale2021.objects.get_or_create( cust_id=self.cust_id, month_year=self.month_year, defaults={ 'cust_name ':self.cust_name, 'class':self.class, 'cust_id ':self.cust_id, 'branch_desc':self.branch_desc, 'cust_desc':self.cust_desc, 'distance_in_kms':self.distance_in_kms, }) if created: # If the object is newly created, save it as usual super(Sale2021, self).save(*args, **kwargs) else: # If the object already exists, update its fields obj.cust_name=self.cust_name obj.class=self.class obj.cust_id=self.cust_id obj.branch_desc=self.branch_desc obj.cust_desc=self.cust_desc obj.month_year=self.month_year obj.distance_in_kms=self.distance_in_kms obj.save() I want if the customer adds a new row in the database, I want to check where there is a row with same cust_id and month_year fields. If yes, then update the existing row, else create one. When I trying to add a new row, I'm getting this error: RecursionError at /admin/home/sale2021/add/ maximum recursion depth exceeded Request Method: POST Request URL: http://127.0.0.1:8000/admin/home/sale2021/add/ Django Version: 5.0 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: C:\Users\Dell\AppData\Local\Programs\Python\Python312\Lib\copyreg.py, line 99, in __newobj__ Raised during: django.contrib.admin.options.add_view Python Executable: C:\Users\Dell\AppData\Local\Programs\Python\Python312\python.exe Python Version: 3.12.1 Python Path: ['C:\\Users\\Dell\\Desktop\\KESORAM\\12-01-2024\\dj_web\\dj_web', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages'] Server time: Fri, 12 Jan 2024 06:44:58 +0000 This line … -
Does not log in to the account through the socialaccount in Django allauth
Does not log in to the account through the socialaccount, although the message appears 'Successfully signed in as ' ({% if user.is_authenticated %} is False, user is AnonymousUser). Everything is configured according to the instructions in the documentation. Simple accounts (via login and password) are logged in ({% if user.is_authenticated %} is True). I've tried different providers, different ways to add keys, and used settings that could have an impact. But nothing helped. Please help me understand how to set up allauth so that logging in only through the social account is carried out. -
How to align each new post next to each other?
I am working on this blog and I want to whenever a user makes a new post it gets displayed next to the others not under them but I don't know what should I do so far I have these cards but they keeps being displayed under each other if I need to post another part of my code please let me know I appreciate the help I want it to be something like this post.html {% extends "online_shop/base.html" %} {% load static %} {% block content %} {% for post in posts %} <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div style="margin-top: 35px;"></div> <div class="card-deck" style="max-width: 300px;"> <div class="card row"> <img class="card-img-top" src="{% static 'online_shop/unicorn-cake-14.jpg'%}" alt="Card image cap" width="300" height="310"> <div class="card-body"> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="card-text">{{ post.content }}</p> {{ post.content|truncatewords_html:15 }} </div> <div class="card-footer"> <small class="text-muted"><a href="#">{{ post.author }}</a></small> <small class="text-muted" style="margin-left: 5px;">{{ post.date_posted|date:"F d, Y" }}</small> </div> </div> </div> </body> {% endfor %} {% endblock content %} -
is there a way to upload multiple large image files to GCS in django admin?
I'm attempting to upload multiple image files to a Google Cloud Storage bucket simultaneously through the django admin interface, 14 image files totaling up to 175mb. They are contained in one model with multiple imagefields. I'm using django-storages to connect django to gcs. I'm not able to increase the upload timeout past the 10 minute mark, and I have to stay inside the django admin interface. My project lead suggested that there might be a way to split the POST request into multiple smaller requests to circumnavigate the timeout, but I can't find any documentation on how to do such a thing inside django admin. Clicking 'save' creates a POST request that takes over 10 minutes, which is long enough to give me a 413 error. I'm using google app engine as a back-end. When I use the local test server, it all uploads as intended. It takes a little while but not ten minutes. If I save after changing one or two images at a time it uploads successfully. -
Inapp mail service django and reactjs
I am making some school management system in django and reactjs ,I want help in making inmail system so that teacher can send notice/attachment to the student of his/her class at once and it will be oneway communication. I wanted to build this but don't have any idea what technology to be use in django . If anyone know the approach than please reply Thanks -
Not able to display image uploaded using django
I was able to upload image using views and templates in django but was not able to display those images. I could only display images stored in static folder but not from the media folder or any other location. I have done all the steps mentioned in docs and in other solution but this is not working for me. I created a model which looks like class Product(models.Model): image = models.ImageField(upload_to='product_images/') description = models.TextField(null=True) quantity = models.IntegerField(null=True) and my forms.py is class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['image', 'description', 'quantity'] my views.py is like this @login_required def display_products(request): products = Product.objects.all() return render(request, 'farmer/display_products.html', {'products': products}) @login_required def upload(request): if request.method == "GET": form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('display_products') return render(request, 'farmer/my_products.html', {'form': form}) my file is like this {% load static %} {% for product in products %} <div class=""> <h2>{{ product.name }}</h2> {{product.image.url}} image: <img src="static/dry.jpeg" alt="sample"> <p>description: {{ product.description }} quantity: {{ product.quantity }} </p> </div> settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static/css', ] LOGIN_URL = 'login' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') DEBUG = True urls.py if settings.DEBUG: urlpatterns … -
loops in Django template
on my template, i have 3 pictures from products in my database i'm trying to loop through. the goal is to display in one div, the pictures of products that are marked available, and in another div, pictures of products that are not marked available. using the code below does not show any items that do not have the same availability as product1. but it shows the pictures of product1 in its appropriate div, as i switch it's availability. i don't know why this is happening, please help. ''' my model looks like class Product(ModelMeta, models.Model): user = models.ForeignKey(User, default=1, null=True,on_delete=models.SET_NULL) title = models.CharField(max_length=120) available = models.BooleanField(default=True) class SiteImage(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to='image/', blank=True, null=True) caption = models.CharField(max_length=50, blank=True) my view looks like def home_page(request): pictures = SiteImage.objects.filter(content_type__model='product') testimonials = Testimonials.objects.all() context = {'pictures': pictures,} return render(request, 'home.html', context) my template looks like {% for picture in pictures %} {% if picture.content_object.available %} {{ picture.product.title }} {{ picture.caption }} {% endif %} {% endfor %} {% for picture in pictures %} {% if not picture.content_object.available %} {{ picture.product.title }} {{ picture.caption }} {% endif %} {% endfor %} ''' -
Django annotate method with when clouse using query key as a Value
I need to add ordering_datetime column when field=field matches. And for a Value I want to get it from "date_time_value" field. queryset = queryset.annotate( ordering_datetime=Case( When( field=field, then=Value("date_time_value") ), output_field=DateTimeField(), ) ).order_by("pk", f"{order_lookup}ordering_datetime").distinct("pk") how to get value from column that matches field=field rows. when I tried to give the column name directly as a value doesn't work. It expects a static value, not a query key -
Angular CLI Proxy + Django Backend not working with Docker
I have an Angular + Django project where I am providing an api to angular with django. When I run the two services separately everything works as expected. When I run both services together using docker compose, angular is suddenly unable to connect to the backend api service. I have seen a similar post on stack but the difference is I am using a single compose file to include two different compose files so I'm not sure how to "link" the backend services to the frontend service like the answers suggest in this post. So what can I do to make this work within docker? Error: [webpack-dev-server] [HPM] Error occurred while proxying request localhost:4200/api/project_types/ to http://api:8000/ [ENOTFOUND] (https://nodejs.org/api/errors.html#errors_common_system_errors) Project Layout: Note: I've dockerized the two services and am using one compose file in the root folder to include both the backend and frontend compose files. - root - backend - backend-compose.yml - frontend - frontend-compose.yml - docker-compose.yml Root Compose: version: '3.7' include: - ./frontend/compose.yml - ./backend/local.yml Frontend Compose: services: web: build: context: . target: builder ports: - 4200:4200 volumes: - ./angular:/app - /project/node_modules Backend Compose: (Note: built with cookiecutter django) version: '3' volumes: backend_local_postgres_data: {} backend_local_postgres_data_backups: {} services: django: build: … -
pytest-django : Invalid choice in client.post
If I print theme_1 in the begining or at the end of the test i get the theme_1 object. But theme_1 in client.post is... None ! I don't understand.. :s Can you help me ? Thank you :) @pytest.fixture def theme_1(db): return Theme.objects.create(name="dev") @pytest.mark.django_db def test_create_forum_view_post(client: Client, theme_1, user_1): client.login(username=user_1.username, password="12345678") response = client.post(reverse("forum:create-forum"), data={"name": "devforum", "theme": theme_1, "description": "Forum des devs"}) form = response.context["form"] print(form.errors) print(response) -
Choosing between Polymorphic Associations and Separate Tables
I'm working on a Django project where I need to manage generic attachments across different entities in my system. Currently, I'm using a polymorphic model as follows: class AttachmentGenericModel(BaseModel): content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True, blank=True) object_id = models.UUIDField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') file = models.FileField(upload_to=upload_to_path) class ProblemStatement(BaseModel): context = models.TextField() files = GenericRelation(AttachmentGenericModel) class Proposal(BaseModel): files = GenericRelation(AttachmentGenericModel) However, I'm wondering if it's preferable to use separate tables for each entity, like ProposalFile, ProblemStatementFile, etc. My concern is that the main table AttachmentGenericModel may become complex over time as the number of entities involved grows. I'm curious if anyone has experiences or advice on which approach is more advantageous in terms of performance, maintainability, and scalability. Additionally, what considerations should be taken into account when deciding between polymorphic associations and separate tables for handling generic attachments in Django? As an illustrative example, here's an example with separate tables: class ProblemStatementFile(BaseModel): problem_statement = models.ForeignKey(ProblemStatement, on_delete=models.CASCADE) file = models.FileField(upload_to=upload_to_path) class ProposalFile(BaseModel): proposal = models.ForeignKey(Proposal, on_delete=models.CASCADE) file = models.FileField(upload_to=upload_to_path) What are the pros and cons of each approach, particularly in a future scenario where numerous new tables with file relationships may be needed? Thank you in advance for your valuable insights! -
Making a Highest Rated Albums List Based on Ratings Averages from Two Models
I have an Album model (shortened for space): class Album(models.Model): creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) artist = models.CharField(max_length=255) title = models.CharField(max_length=255) rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) comment = models.TextField(null=True, blank=True) And a Review model (again, shortened for space): class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, null=True) album = models.ForeignKey(Album, on_delete=models.CASCADE) rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) comment = models.TextField() The Album model is for users to create an Album and add their initial review and rating. The Review model is for users to be able to add a review to an existing album, and also a rating. I have this model method attached to the Album in order to create an average rating to display in templates: def avg_rating(self): review_ratings = 0 orig_rating = self.rating review_ratings_count = self.review_set.count() if review_ratings_count > 0: for review in self.review_set.all(): review_ratings += review.rating ratings_sum = review_ratings + orig_rating ratings_count = review_ratings_count + 1 ratings_avg = ratings_sum / ratings_count avg_return = round(ratings_avg, 1) if avg_return == 10.0: avg_return = 10 else: avg_return = avg_return return avg_return else: return self.rating Sadly, avg_rating cannot be used (to my knowledge) in … -
raise ValueError, "No frame marked with %s." % fname. SyntaxError: invalid syntax at import environ in settings.py file
When building a docker container with the --platform=linux/amd64 python:3.9 image, I encounter an error: Traceback (most recent call last): File "/var/www/myapp/manage.py", line 22, in <module> main() File "/var/www/myapp/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/var/www/newapp/myapp/settings.py", line 2, in <module> import environ File "/usr/local/lib/python3.9/site-packages/environ.py", line 114 raise ValueError, "No frame marked with %s." % fname ^ SyntaxError: invalid syntax I tried the recommended change to python3 -m pip install requirements.txt/pip3 install requirements.txt in the Dockerfile but nothing worked. The build of my container still exited with an error. What I realised is that the django-environ package as included in the requirements.txt file was either not installed or the absence of … -
Not able to retrive data from database in Django
I'm new to django. I am trying to obtain data from a profile page that I've created which exists in a app called users and I am trying to use the data in a HTML file called home that exists in an app called blog within in a templates directory within a blog directory This is how my users\model.py file looks like class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default='default.jpg', upload_to="profile_pics") height = models.PositiveIntegerField( null=True, blank=True) weight = models.PositiveIntegerField( null=True, blank=True) age = models.PositiveIntegerField( null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' def save(self,*args,**kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width >300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) This is how my users\views.py file looks like def profile(request): u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated successfully!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) profile_instance = request.user.profile context = { 'u_form': u_form, 'p_form': p_form, 'height': profile_instance.height, 'weight': profile_instance.weight, 'age': profile_instance.age, } return render(request,'users/profile.html',context) Just to be sure that my Profile Page works, I checked the admin page, and it shows the data in the profile section. This is how my blog\views.py … -
Media Exposure Vulnerability
Currently, we have a configuration in Django to serve media files (these are the files uploaded by users in the system). We have a URL for this where we capture all the files in the media directory and redirect them to the serve_media view. re_path(r"^media/(?P<path>.*)$", cms.views.serve_media), This is the serve_media view: def serve_media(request, path=""): if request.user.is_authenticated: user = request.user else: return redirect("/%s?next=%s" % (settings.LOGIN_URL, "/media/" + path)) usuario = Usuario.objects.get(usuario=user) # Search for the file by its path in the media folder and check if the user # has permission to access it allowed_to_serve = False try: arquivo = Arquivo.objects.get(arquivo__contains=path) # Public image of a project on the website for projeto in Projeto.objects.exclude(id_imagem_publica=None): if projeto.arquivo_in_id_imagem_publica(arquivo.id) is True: allowed_to_serve = True break if user == arquivo.criado_por or usuario.permissao == Usuario.SUPER: allowed_to_serve = True # Entidade file if arquivo.entidade is not None and allowed_to_serve is False: if ( usuario.permissao == Usuario.ENTIDADE and user == arquivo.entidade.usuario.usuario ): allowed_to_serve = True elif ( usuario.permissao == Usuario.AGENCIA and arquivo.entidade.projeto_set.all() .filter(cidade_atuacao=usuario.cidade_atuacao) .count() > 0 ): allowed_to_serve = True # Projeto file if arquivo.projeto is not None and allowed_to_serve is False: if ( usuario.permissao == Usuario.ENTIDADE and user == arquivo.projeto.entidade.usuario.usuario ): allowed_to_serve = True elif ( usuario.permissao … -
VS Code (Python) uses wrong version of Python interpreter even after activation virtual env (Poetry)
I have two Python interpreters on my machine (3.11.6 and 3.12). My project runs with Poetry venv (3.11.6). Whenever I open a project the status bar indicates correct venv like 3.11.6("project-fd1143fd-py3.11":Poetry). When I run a project (Django) I get an import error says there is no Django package installed. I suspect there is no actual activation of venv. When I enter command python --version I always get Python 3.12.0 (tags/v3.12.0:0fb18b0, Oct 2 2023, 13:03:39) There is no any indication of activated venv near the command line (do it has to be there as I remember). The Poetry venv itself works fine as I use it in PyCharm without any issues. -
Django Auth Query
I have a django backend project for e-commerce site where I have created authentication class which is used by all the view classes for incoming requests. In one of the classes I have get_queryset, put and post functions overridden. I want the authentication class to be applied for both put and post functions but not to get_queryset. following are the code snippets, Authentication Class class JWTAuthentication(BaseAuthentication): def authenticate(self, request): print('authenticating') auth = get_authorization_header(request).split() print(auth) if auth and len(auth) == 2: token = auth[1].decode('utf-8') print('Decoded Token') print(token) id = decode_access_token(token) print(id) print(id) customer = models.Customer.objects.get(id=id) return (customer, None) raise exceptions.AuthenticationFailed('unauthenticated2') Product View class class ProductList(generics.ListCreateAPIView): ... authentication_classes = [ JWTAuthentication ] ... def get_queryset(self): ... def post(self, request): ... def put... Is there a way just to apply the authentication on put and post function but not on get_queryset function? -
Authentication logout
error screenguys i have a big problem. Now im working for tweet website with python django. Authentication steps are good runnig but logout is dont working please help me guys.... my base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <title>Tweet App</title> <link rel="stylesheet" href="{% static 'tweetapp/customform.css' %}"> </head> <body> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'tweetapp:listtweet' %}">Tweet App</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'tweetapp:listtweet' %}">List</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweet' %}">Add Tweet</a> </li> <!-- <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweetbyform' %}">Add Tweet By Form</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'tweetapp:addtweetbymodelform' %}">Add Tweet By Model Form</a> </li> --> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}?next=/">Logout</a> </li> </ul> </div> </div> </nav> {%block content%} {%endblock%} </body> </html> my urls.py """ URL configuration for djangotweet project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.0/topics/http/urls/ Examples: Function … -
"invalid_client" Error in Django OAuth Toolkit Despite Following Documentation
I'm encountering an "invalid_client" error when attempting to obtain an OAuth token using Django OAuth Toolkit. I've been meticulously following the official documentation (https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html#step-4-get-your-token-and-use-your-api) but am unable to resolve the issue. Error Details: Error Response: {"error": "invalid_client"} Server Log: Unauthorized: /o/token/ [11/Jan/2024 20:13:37] "POST /o/token/ HTTP/1.1" 401 27 Steps Taken: Repeated Documentation Steps: I've carefully followed the documentation's instructions from scratch multiple times. Verified Credentials: I've double-checked the client ID, client secret, username, and password for accuracy and typos. Inspected Request Details: I've examined the cURL command and request details to ensure they align with the server's expectations. Specific Context: OAuth Server/Library: Django OAuth Toolkit Relevant Code Snippet: Bash curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ Request for Assistance: I'm kindly seeking guidance on potential causes and troubleshooting steps. Specific Questions: Common Pitfalls: Are there any common mistakes or configuration issues that might lead to this error in Django OAuth Toolkit? Troubleshooting Suggestions: What additional diagnostic steps can I take to pinpoint the root cause? Server-Side Considerations: Are there any server-side settings or logs I should examine? Any insights or assistance would be greatly appreciated. -
IntegrityError FOREIGN KEY constraint failed
I am trying to add a new "Eveniment" through the admin page in my app, but I get the error from the title and I don't know how to solve the issue. Only and "Utilizator" who has the "Organizator" role should be able to add one. class Utilizator(AbstractUser): ORGANIZATOR=1 CUMPARATOR=2 data_inregistrare = models.DateTimeField(auto_now_add=True) ROLE_CHOICES =( (ORGANIZATOR, 'Organizator'), (CUMPARATOR, 'Cumparator'), ) role=models.PositiveSmallIntegerField(choices=ROLE_CHOICES,blank=True,null=True) evenimente=models.ManyToManyField(to='Eveniment', blank=True) groups = models.ManyToManyField( 'auth.Group', related_name='utilizatori', verbose_name='groups', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='user', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='utilizatori', verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_query_name='user', ) def to_dict(self): return{ 'id': self.id, 'data_inregistrare': self.data_inregistrare, 'role': self.role, } class Eveniment(models.Model): nume = models.CharField(max_length=255) data = models.DateField() locatie = models.CharField(max_length=255) descriere = models.TextField() organizator = models.ForeignKey(Utilizator, on_delete=models.CASCADE, related_name='evenimente_organizate', null=True) def __str__(self): return self.nume def to_dict(self): organizator_id = self.organizator.id if self.organizator else None return{ 'id': self.id, 'nume': self.nume, 'data': self.data, 'locatie': self.locatie, 'descriere': self.descriere, 'organizator': self.organizator.id, } For now, I am just trying to add a new "Eveniment" through the admin page, but the error keeps showing up no matter the changes I've made. -
django sender to django receiver api data exchange
I have built two web applications, django_one and django_two. I would like django_one to send data (From a web form) to django_two via RESTful_framework api any other method. Please guide me on how to go about this. -
The database needs something to populate existing rows...but the table doesn't exist yet and there are no rows
I'm getting this running python3 manage.py makemigrations You are trying to add the field 'created_at' with 'auto_now_add=True' to sitemetadata without a default; the database needs something to populate existing rows. But the table doesn't exist yet, and there are no rows. How can I use makemigrations here properly?