Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm getting a "AttributeError: module 'django.views' has no attribute 'my_form'" even though I have defined the function
I'm very new to django and python and I was making a form to accept values from the user to store in the database and I keep running into a ModuleNoFoundError, even though I have written the module in views.py which I am importing. I am creating my own module and the html for the form and not using django form formats at all. This is my views.py: `from django.shortcuts import render # Create your views here. from .models import My_Model from .forms import MyForm def my_form(request): if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): form.save() else: form = MyForm() return render(request, 'form.html', {'form': form}) This is my urls.py: `from django import urls from django import views from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), urls(r'form', views.my_form , name='form') ] ` This is the models.py: `from django.db import models # Create your models here. class My_Model(models.Model): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) PRN = models.CharField(max_length=8) Phone = models.IntegerField(max_length=10) Email = models.EmailField() Department = models.CharField(max_length=50) S_Year = models.CharField(max_length=2) def __str__(self): return self.name` This is the forms.py: `from django import forms from .models import My_Model class MyForm(forms.ModelForm): firstname = forms.CharField(widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "firstname" })) lastname … -
How to combine objects in a full outer join with Django?
Let's use Django's standard users and groups. I have a couple of users and groups and each user can be assigned to several groups via a M2M relation. Now, I want to construct a single query which cross joins users x groups. The purpose is a view that shows all groups with it's members, when users are members of several groups then I want them to be shown in each group. I currently have this query, which appears to give me a cross join: groups = list(Group.objects.all()) queryset = User.objects.filter(groups__in=groups) However, the query only contains data about the users. How can I include the data for each group into the queryset? -
How to host / deploy a Django Project Online Free Version?
i have been trying to host a django web app online but it has not been successfuly deployed online. I want a help from you guys to give me the best opsions and step by step guide how to host / deploy a django web app (not static project) -
How to Custom User model inherit and serialize them in Django
Got AttributeError when attempting to get a value for field ProDetails on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the CustomUser instance. Original exception text was: CustomUser object has no attribute ProDetails. Models.py class CustomUser(AbstractBaseUser, PermissionsMixin): username=None email = models.EmailField(unique=True) password = models.CharField(max_length=128, null=True) first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_shopCreated = models.BooleanField(default=False) last_login = models.DateTimeField(null=True, blank=True) last_logout = models.DateTimeField(null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_module_perms(self, app_label): return True def has_perm(self, perm, obj=None): return True class ProDetails(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) mobile = models.CharField(max_length=14) address = models.CharField(max_length=500, null=True, blank=True) pincode = models.CharField(max_length=10, null=True, blank=True) profileimage = models.ImageField( upload_to='photos', max_length=100, null=True, blank=True) coverImg = models.ImageField( upload_to='photos', max_length=100, null=True, blank=True) Serializer.py class ProDetailsSerializer(ModelSerializer): class Meta: model = ProDetails fields = ['id','pincode'] class UserSerializer(ModelSerializer): ProDetails = ProDetailsSerializer(required=True) class Meta: model = CustomUser fields = ['email', 'first_name', 'created_at', 'ProDetails'] View.py class profiledata(mixins.RetrieveModelMixin, mixins.ListModelMixin, generics.GenericAPIView): serializer_class = UserSerializer lookup_field = 'id' authentication_classes = [ JWTAuthentication, TokenAuthentication, SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated, ] def get_queryset(self): user = CustomUser.objects.all() return user … -
Django doesn't show yellow page
So I have initialized a django project (v4.2.5) and every thing works fine and debug is set to True, but I never get the yellow page when errors occur, instead I always get this: A server error occurred. Please contact the administrator. I do have django.middleware.common.CommonMiddleware and DEBUG_PROPAGATE_EXCEPTIONS is set to true as well and I have to check what is the problem in terminal all the time, any idea what could be the problem? -
Why does it give an error even though I created the template filter according to the Django documentation?
from django import template register = template.library() # in here, pycharm say : 'library' is not callable @register.filter(name='LIM') def limited_index(val, arg): return val[:arg] terminal : Cannot find reference 'assignment_tag' in 'library.py' -
Django linkedIn Social authentication
Someone please help, Please read it fully(I have tried a lot of methods lately from different sources) its been more than 30 days I'm trying to get 'Sign in with LinkedIn' button, but no good.. ill just show you my code: My LinkedIn id n key(have tried without REDIRECT_URL line as well) #MY LINKEDIN APP SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'ID' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'KEY' REDIRECT_URI = 'http://localhost:8000/oauth/complete/linkedin-oauth2/'` URLS `urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('oauth/', include('social_django.urls', namespace='social')), ]` LinkedIn Button `<!--LINKEDIN BUTTON--> <li class="linkedin"> <a href="{% url "social:begin" backend="linkedin-oauth2" %}"> Sign in with Linkedin </a> </li>` Nothing's wrong with the coding.. `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'home', 'social_django', ] LOGIN_REDIRECT_URL = 'dashboard' LOGOUT_REDIRECT_URL = 'login' LOGIN_URL = 'login' LOGOUT_URL = 'logout' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.github.GithubOAuth2', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.linkedin.LinkedinOAuth2', ) LinkedIn app is okay, Redicrect URI mathces as well` `Error after Clicking Sign in with LinkedIn Bummer, something went wrong. In five seconds, you will be redirected to: localhost Django error AuthFailed at /oauth/complete/linkedin-oauth2/ Authentication failed: Scope &quot;r_liteprofile&quot; is not authorized for your application I understand it needs the "r_liteprofile" scope, But I cant see that anywhere, neither inside OAuth 2.0 tools . HELP Appreciated. solution to this … -
Static and Media files are not shown in django website - nginx & gunicorn
I'm trying to deploy a django website on a vps and it's now up and running(after a lot of trouble!), but now my media and static files are not shown in my website and I really tried a lot of ways but none of them worked. My nginx configuration: server { listen 80; server_name domain_name; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/real_estate/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=shahriar Group=www-data WorkingDirectory=/home/shahriar/Amlak/real_estate ExecStart=/home/shahriar/Amlak/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ real_estate.wsgi:application [Install] WantedBy=multi-user.target settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/var/www/real_estate/static/' STATIC_ROOT = '/var/www/real_estate/static/assets' STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/', '/var/www/real_estate/static/' ] # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Media Settings MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR.joinpath('media') And eventually I restarted every service possible but not a single static file was shown. I tried changing settings.py from this: STATIC_URL = 'static/' STATIC_ROOT = 'assets/' STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/' ] to this: STATIC_URL = '/var/www/real_estate/static/' STATIC_ROOT = '/var/www/real_estate/static/assets' STATICFILES_DIRS = [ 'static/', BASE_DIR/'static/', '/var/www/real_estate/static/' ] I tried changing from this : server … -
how to Prevent Automatic Disconnection from Django Channels Server After a Period of Inactivity
I'm working on a Django project where I'm using AsyncWebsocketConsumer on the server side to manage python build-in WebSockets connections. but unfortunately, after sending first message, in my python websockets app(client side) i should send message each 50 second to my connection don't close. To prevent this, I've tried adjusting the arguments when connecting using websockets.connect as follows: import json import asyncio import websockets async def connect_to_server(): url = 'ws://localhost:8000/ws/socket-server/' async with websockets.connect(url, open_timeout=None, ping_interval=1, ping_timeout=120, close_timeout=1) as websocket: try: while True: # My code here... except KeyboardInterrupt: pass asyncio.get_event_loop().run_until_complete(connect_to_server()) Despite these, I'm still facing disconnection after a period of inactivity. Am I missing something in my approach? Specifically, how can I ensure that the connection remains active and prevent it from disconnecting due to inactivity? Any guidance on this would be greatly appreciated. Thanks in advance for your help! -
Problem using dj rest auth: dj-rest-auth/registration return http 204 no content
I am having the same problem as in this question (dj-rest-auth/registration return http 204 no content) but it still hasnt been answered so I wanted to post a new one to update it so maybe someone can give a solution. I were following the book Django for APIs by William.S.Vincent. In Chapter 8: User Authentication, I make Implementing token authentication and use dj-rest-auth and django-allauth to make registration. In the book after register the http return 201 created, it created new account and return API auth key token, save that in db. enter image description here With my it return http 204 no content( not return API auth key token ), it still created a new account but don't create key token for account. My url.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include("posts.urls")), # v1 for api version 1. (Name for each api route) path('api-auth/', include('rest_framework.urls')), # build-in log in/out rest path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")), #url for dj_rest_auth path("api/v1/dj-rest-auth/registration/", include("dj_rest_auth.registration.urls")), ] My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #3party "rest_framework", "corsheaders", "rest_framework.authtoken", "allauth", "allauth.account", "allauth.socialaccount", "dj_rest_auth", "dj_rest_auth.registration", #local 'accounts.apps.AccountsConfig', 'posts.apps.PostsConfig',] REST_FRAMEWORK = { # new "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ],} I compared with … -
django cookiecutter project generating error
I am following the quickstart of django cookiecutter tutorial. I've installed cookiecutter's latest version and pulled the cookiecutter django repo and the promts were properly filled. But after the last prompt, I always get this error: "ERROR: Stopping generation because pre_gen_project hook script didn't exit successfully Hook script failed (exit status: 1)" Honestly, I have no idea what is wrong. Please help :( -
How to combine multiple querysets in a Django view?
I am developing an exam page, where the user can take an exam several times and the results will be saved in the Score model. Currently I can store the results of the logged in user, but I need it to show me the entire list of scores they have achieved when I enter the details of each user. I have access to the list of users with the userList view, and I can access the details of each user with the userDetail view, but I want to know if there is a way to show all the scores of the selected user in the same details view. Here's de Score model: MODELS class Score(models.Model): #The user field is a foreign key from User(AbstractUser) user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.IntegerField(default=0) evaluation_date = models.DateTimeField() These are the views I'm using for the user list, user detail and saving the new score: VIEWS class userList(LoginRequiredMixin, ListView): template_name = "users/list.html" queryset = User.objects.all() context_object_name = "users" class userDetail(LoginRequiredMixin, DetailView): template_name = "users/detail.html" queryset = User.objects.all() context_object_name = "user" @csrf_protect def send(request): if request.method == 'POST': if 'answers' in request.POST: answers = request.POST['answers'] time = datetime.datetime.now() current_user = request.user Note.objects.create( user = current_user, … -
When trying to deploy Django project on Azure through GitHub Repository, I'm getting "ModuleNotFoundError: No module named 'django'"
After I tried to deploy my Django website on Azure through GitHub, Deployment got successful and I'm not able to see the output, I'm getting Application Error. I'm using CONDA environment to run my project so I do not have requirements.txt file but I do have environment.yml file. I tried checking in diagnostics it says Application crashed and the error is Application Crashed 2023-10-15T00:05:56.422910225Z from django.core.wsgi import get_wsgi_application2023-10-15T00:05:56.422913932Z ModuleNotFoundError: No module named 'django'2023-10-15T00:05:56.423461446Z [2023-10-15 00:05:56 +0000] [76] [INFO] Worker exiting (pid: 76) and the it says that "This error is due to the missing package 'django' in the requirements.txt file. To resolve this, add the missing package in the requirements.txt file and redeploy the application." I've attached image for application logs.Application Logs my environment.yml file is name: SERVIR_AppTemplate channels: defaults conda-forge dependencies: python=3.9 django=4.1 django-allauth django-import-export netcdf4 shapely earthengine-api beautifulsoup4 whitenoise aiohttp pip=23.2.1 pip: climateserv==0.0.24 prefix: C:\ProgramData\Anaconda3\envs\SERVIR_AppTemplate -
How to prevent duplicate requests in apache2
I am having an issue with an Apache2 web server. I had a site working for a while, but now every request that is sent to the server has a duplicate and the first request isn't visible to the user at all. I am able to temporarily patch this by using database transactions to only return a response on the second request, with Django middleware, but the software still shows duplicate requests in the logs, each GET and POST request sent to the server has a duplicate counterpart. I have tried a suggestion I found, using modsecurity2, but it doesn't seem to work, it still lets duplicate requests through. The solution is below. SecRule USER:duplicaterequest "@gt 1" "id:'40000',phase:2,deny,status:409,msg:'Duplicate Request!'" The requests are about 2 seconds apart, and this causes all sorts of issues with duplicate objects and also seems to make the pages take longer to load. This happened overnight several weeks ago without any changes to the code. Any idea what this could be, or a way to fix it? -
Django GraphQL Endpoint Not Found When Requested via Krakend API Gateway
Hello StackOverflow Community, I am currently experiencing an issue with a Django project using GraphQL, specifically when attempting to access the GraphQL endpoint through the Krakend API Gateway. Environment: Django: 4.2.6 GraphQL Krakend API Gateway Dockerized environment Problem: When I send a request directly to the Django backend's /graphql endpoint, it works as expected. However, when I attempt to access the same endpoint via the Krakend API Gateway, I receive a 404 Not Found error. Error Log: Here is the error message received in the Docker logs: backend_1 | Not Found: /graphql backend_1 | [14/Oct/2023 23:32:52] "POST /graphql HTTP/1.1" 404 2961 This indicates that when the request is routed through Krakend to the Django backend, the /graphql endpoint cannot be found. Code: In my urls.py, I have the /graphql endpoint defined as: from django.urls import path, re_path from graphene_django.views import GraphQLView from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True, name='graphql'))), # ... other paths ... ] My settings (pertinent to the URLs and middleware) in settings.py include: ALLOWED_HOSTS = ['backend', 'frontend', 'localhost', ...] INSTALLED_APPS = ['graphene_django', ...] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = ["http://localhost:3000"] Attempted Solutions: Verified the /graphql endpoint is … -
Handing foreign keys relations with Django's rest framework?
Description: I am creating a Django application for the first time and using the rest framework. My goal is to use the rest framework to test a post request for creating a new "Artwork" and adding it to my database. An artwork contains columns such as title, width, height, and etc. It also contains a column for a foreign key called "artist_id". This foreign key is linked to the primary key of my "Artist" table. In my artist table, I have the an artist_name column. My "Artwork" and "Artist" tables in Models.py: class Artwork(models.Model): idartwork = models.AutoField( db_column="idArtwork", primary_key=True ) # Field name made lowercase. title = models.CharField(max_length=50, blank=True, null=True) date_created_month = models.IntegerField(blank=True, null=True) date_created_year = models.TextField( blank=True, null=True ) # This field type is a guess. comments = models.CharField(max_length=255, blank=True, null=True) width = models.DecimalField(max_digits=10, decimal_places=3, blank=True, null=True) height = models.DecimalField(max_digits=10, decimal_places=3, blank=True, null=True) artist = models.ForeignKey(Artist, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = "artwork" class Artist(models.Model): idartist = models.AutoField( db_column="idArtist", primary_key=True ) # Field name made lowercase. artist_name = models.CharField( max_length=40, db_collation="utf8_general_ci", blank=True, null=True ) class Meta: managed = False db_table = "artist" My problem: In order to test the post request described in my description, … -
Django Rest Framework Djoser - saving JWT tokens in httpOnly cookies
Hey I'm looking for the correct way to implement saving JWT tokens in httpOnly cookies using JWT I'm not sure if thing I did is right. Changed Default authentication class in setting.py and added cookies settings REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "authorization.authentication.JWTCookiesAuthentication", ), } SIMPLE_JWT = { ... "AUTH_COOKIE": "access_token", # Cookie name. Enables cookies if value is set. "AUTH_COOKIE_DOMAIN": None, # A string like "example.com", or None for standard domain cookie. "AUTH_COOKIE_SECURE": False, # Whether the auth cookies should be secure (https:// only). "AUTH_COOKIE_HTTP_ONLY": True, # Http only cookie flag.It's not fetch by javascript. "AUTH_COOKIE_PATH": "/", # The path of the auth cookie. "AUTH_COOKIE_SAMESITE": "Lax", } Created custom authentication backend in authentication.py class JWTCookiesAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) return self.get_user(validated_token), validated_token and added cookies in response in my view class EmailTokenObtainPairView(TokenViewBase): serializer_class = CustomTokenObtainPairSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except AuthenticationFailed: raise InActiveUser() except TokenError: raise InvalidToken() response = Response(serializer.validated_data, status=status.HTTP_200_OK) response.set_cookie( key=settings.SIMPLE_JWT["AUTH_COOKIE"], value=serializer.validated_data["access"], expires=settings.SIMPLE_JWT["ACCESS_TOKEN_LIFETIME"], secure=settings.SIMPLE_JWT["AUTH_COOKIE_SECURE"], httponly=settings.SIMPLE_JWT["AUTH_COOKIE_HTTP_ONLY"], samesite=settings.SIMPLE_JWT["AUTH_COOKIE_SAMESITE"], ) return response But what about refresh token and will that handle … -
Django channels - propagate exceptions to the client
I was wondering what is the best practice to propagate exceptions to the client using django-channels. My client is a Swift iOS app using URLSessionWebSocketTask. I got 3 main scenarios for example where exception is thrown and I want to notify the client. Authentication, using custom middleware. from api.jwt_handler import jwt_websocket_decode, get_device_id, get_auth_token from inbox.exceptions import WebSocketErrors class WebsocketAuthMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): headers = scope["headers"] token = get_auth_token(headers) device_id = get_device_id(headers) if token is None or device_id is None: raise WebSocketErrors.invalid_bearer_token <--- Notify client user = await jwt_websocket_decode(token, device_id) if user is None: raise WebSocketErrors.invalid_bearer_token <--- Notify client scope['user'] = user return await self.app(scope, receive, send) I've tried wrapping __call__ in try statement, but I'm not sure how to propagate the error to the http transport layer, The client gets 1011 - There was a bad response from the server Connection rejection - handshake. class ConversationConsumer(AsyncWebsocketConsumer): async def connect(self): self.ws_conversation_id = self.scope["url_route"]["kwargs"]["conversation_id"] self.room_group_name = self.ws_conversation_id self.user = self.scope["user"] if user.can_participate_in_conversation(self.ws_conversation_id) is False: raise WebSocketErrors.not_authorized <--- Notify client await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() Here I want to reject connection if user is not part of a given conversation id, to prevent abuse. … -
MultiValueDictKeyError when sending POST requests
I'm making an expense tracker web app, but when I want to send POST requests, it fails. models.py from django.db import models from django.contrib.auth.models import User class Token(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) token = models.CharField(max_length=48) def __str__(self): return "{}_token".format(self.user) class Expense(models.Model): text = models.CharField(max_length=225) date = models.DateTimeField() amount = models.BigIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "{} -{}".format(self.date, self.amount) class Income(models.Model): text = models.CharField(max_length=255) date = models.DateTimeField() amount = models.BigIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "{} +{}".format(self.date, self.amount) views.py from django.shortcuts import render from django.http import JsonResponse from json import JSONEncoder from django.views.decorators.csrf import csrf_exempt from web.models import User, Token, Expense, Income from datetime import datetime @csrf_exempt def submit_expense(request): this_token = request.POST['token'] this_user = User.objects.filter(token__token = this_token).get() now = datetime.now() Expense.objects.create( user = this_user, amount=request.POST['amount'], text=request.POST['text'], date=now ) return JsonResponse({ 'status': 'ok', }, encoder=JSONEncoder) I assume this way of sending POST requests are expired, but can't find a way to do it. -
How to render data from model to view?
I have this model called Coach and I want it to be accessible in the lesson_detail.html, because when I use the template {{ coach.first_name }}, nothing is showing up. I'm trying to pull the data from the model using get_object_or_404 but I'm not sure what I need to put in the argument for that. I tried a few things like id=pk or in the code below, first_name=first_name, but I got an error that the variable is not defined. views.py from django.shortcuts import render, get_object_or_404, reverse from django.views import generic, View from django.http import HttpResponseRedirect from .models import Lesson, Coach, Feedback from .forms import FeedbackForm class LessonDetail(View): def get(self, request, slug, *args, **kwargs): queryset = Lesson.objects.filter(status=1) lesson = get_object_or_404(queryset, slug=slug) coach = get_object_or_404(Coach, first_name=first_name) feedbacks = lesson.feedbacks.filter(approved=True).order_by('-created_on') liked = False if lesson.likes.filter(id=self.request.user.id).exists(): liked = True return render( request, "lesson_detail.html", { "lesson": lesson, "feedbacks": feedbacks, "coach": coach, "submitted_feedback": False, "liked": liked, "feedback_form": FeedbackForm(), }, ) models.py class Coach(models.Model): RECREATIONAL = 'recreational' FREESTYLE = 'freestyle' DANCE = 'dance' PAIRS = 'pairs' SPECIALIZATION_CHOICES = [ (RECREATIONAL, 'Recreational'), (FREESTYLE, 'Freestyle'), (DANCE, 'Dance'), (PAIRS, 'Pairs'), ] first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.EmailField(max_length=100) bio = models.CharField(max_length=140, help_text="Enter a brief bio") image = CloudinaryField('image', default='placeholder') … -
I am building a product review app in my Django eCommerce project. I can't get my review form to display on a template from the main shop app
Here is my set up: using Django 3.2.21. bootstrap4 reviews/views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from shop.models import Product from .models import Reviews from .forms import ReviewForm def review(request, product_id): product = get_object_or_404(Product, pk=product_id) if request.method == 'POST': review_form = ReviewForm(request.POST) if review_form.is_valid(): review_form.save() messages.success(request, 'Successfully reviewed product') return redirect(reverse('product_detail', args=[product.id])) else: messages.error(request, 'Failed to add product. \ Please check the form data is correct') else: form = ProductForm() template = 'shop/product_detail.html' context = { 'review_form': review_form, } return render(request, template, context) shop/product_detail.html <h3>Leave a Review</h3> <form method="post" action="{% url 'review' product.id %}"> {% csrf_token %} {{ review_form|crispy }} <input type="submit" value="Submit review"> </form> reviews/urls.py from django.urls import path from . import views urlpatterns = [ path('review/<int:product_id>/', views.review, name='review'), ] The model and form file to me look ok they are also set up in the revies app. The main project level urls.py path looks ok. I have other apps in the project all set up ok. On the product_detail template there is another form for adding item to cart which is working. I have tried changing around urls and rewriting the view differently but nothing working. The title and submit button are displaying with … -
django.db.utils.ProgrammingError: relation "iptoc" does not exist
I have seen all of the similarly titled questions. Case is different: The problem arises when running the unittest. I had to import some foreign tables because they already had data in them (country region city ) data. So I had to create the Model as managed = false class Iptoc(models.Model): id_ip = models.IntegerField(primary_key=True) ip_from = models.IntegerField() ip_to = models.IntegerField() country_code2 = models.CharField(max_length=2) threecode = models.CharField(max_length=3) country_name = models.CharField(max_length=40) class Meta: managed = False db_table = 'iptoc' When I do a query in a view it works 100% correct that is, it does use the table. def index_country(request): # getting the hostname by socket.gethostname() method hostname = socket.gethostname() ## getting the IP address using socket.gethostbyname() method ip_address = socket.gethostbyname(hostname) ## printing the hostname and ip_address print(f"Hostname: {hostname}") print(f"IP Address: {ip_address}") x = 18874378 record = Iptoc.objects.get(ip_to__gte=x,ip_from__lte=x) pais = record.country_name print(pais) The table in my postgresql is called iptoc (no capital letters) When I run this test: class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('country') response = self.client.get(url) self.assertEquals(response.status_code, 200) I get: File "/home/alvar/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "iptoc" does not exist LINE 1: ... "iptoc"."threecode", "iptoc"."country_name" FROM "iptoc" WH... -
How to resolve missing 1 required positional argument: 'get_response' in Django
I am new to Django and I want to add a Middleware for JWT Authentication. I am using Django version 4.2.6 My Middleware code is as follows: import jwt from django.http import JsonResponse from django.conf import settings from django.utils.deprecation import MiddlewareMixin class TokenMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Check if the request has an "Authorization" header authorization = request.META.get('HTTP_AUTHORIZATION') if authorization and authorization.startswith('Bearer '): token = authorization.split(' ')[1] jwks_client = jwt.PyJWKClient(settings.JWT_VERIFY_URL) header = jwt.get_unverified_header(token) key = jwks_client.get_signing_key(header["kid"]).key try: jwt.decode(token, key, [header["alg"]]) except jwt.ExpiredSignatureError: return JsonResponse({'error': 'Token has expired'}, status=401) except jwt.DecodeError: return JsonResponse({'error': 'Token is invalid'}, status=401) else: return JsonResponse({'message': 'Authentication Bearer Token is required.'}) response = self.get_response(request) return response I have registered my Middleware in settings.py. I have been trying to fix this error but nothing really helped. It triggers when get_response is called. For this code I am getting the following error: Traceback (most recent call last): File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/abdulai/projects/abdulai/holden/nyc-transactions/nyc-transactions-backend/venv/lib/python3.10/site-packages/rest_framework/views.py", line 492, in dispatch request … -
Problems with Summernote and crispy-forms in Django
I have 2 problems: (1) I got Summernote working in the admin create-a-post section, but I can't figure out how to incorporate it into the publicly-facing HTML form (at https://example.com/post/new/), and (2) I'm using crispy_forms, and when I make a post in Summernote in admin with a picture and/or some HTML formatting tags, the post renders as plain-text, including the HTML tags, which is ugly. I've tried removing the crispy tag and replacing it with the "safe" keyword, but the HTML still renders in plain-text. How do I get Summernote to render properly with crispy_forms? Here's my code: post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} the main 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 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( … -
Paypal Payment gateway integration code=NO_BUSINESS
I am trying to integrate paypal payment gateway to my html page and its always returning "Things don't appear to be working at the moment. Please try again later." in paypal sandbox page paypal_dict = { 'buisness':"sb-xxxxxxxxxxx.business.example.com", 'amount': cart_total_amount , 'currency': 'INR', 'receipt': 'order-item-number-' + str(order.id), 'invoice_number': 'INVOICE_NO-' + str(order.id), 'notify_url': 'http://{}{}'.format(host, reverse("uwapp:paypal-ipn")), 'return_url': 'http://{}{}'.format(host, reverse("uwapp:payment_completed")), 'cancel_url': 'http://{}{}'.format(host, reverse("uwapp:payment_failed")), } # Generate the Razorpay payment button payment_button = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'uwapp/checkout.html', { 'payment_button': payment_button })