Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Storing a Generic Table (with rows, columns) fields are not explicit as objects in Database Django
In my Django Project im trying to map out generic tables the number and column definitions would be different for each table Table 1 | Col1 | Col2 | | ----- | -----| Table 2 | Col A | Col B | Col C | | ----- | ----- | ------| These are the proposed models that I thought, not sure if this is the best way to do this or even if storing these tables in my psql database class GenericColumn(models.Model): given_name = models.CharField(max_length=128, verbose_name='Given Column Name') class GenericTable(models.Model): table_name = models.CharField(max_length=128, verbose_name='Table Name') columns = models.ManyToManyField(GenericColumn, blank=True, verbose_name='Columns') class GenericRow(models.Model): table = models.ForeignKey(GenericTable, on_delete=models.CASCADE) data = models.JSONField(null=True) # data being {colName: "Value"} as a JSON object I did initially have a model for an individual cell but I aborted that idea as there would loads of entries in the database might get too big I wanted to ask what would be the best way to go about this as its a bit of unusual use case as none of the fields are specified it depends on what the table is. But on the front end you would be able to edit these thats why i stored it as … -
Cannot authenticate a django user using his token
I am creating a django rest framework api to interact with an Android app. I have opened the following endpoints: from django.urls import path, include from .views import UserViewSet, UserProfileViewSet, CurrentUserView,LoginView urlpatterns = [ path('usuarios/', UserViewSet.as_view(), name='usuarios'), path('usuarios-perfil/', UserProfileViewSet.as_view(), name='usuarios-perfil'), path('usuario-actual/', CurrentUserView.as_view(), name='usuario-actual'), path('login/', LoginView.as_view(), name='login'), ] My views are this ones: from rest_framework import generics from django.contrib.auth.models import User from .models import UserProfile from .serializers import UserSerializer, UserProfileSerializer from rest_framework.permissions import IsAuthenticated from django.contrib.auth import get_user_model from django.contrib.auth import authenticate from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authtoken.models import Token import logging logger = logging.getLogger(__name__) class UserViewSet(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserProfileViewSet(generics.ListCreateAPIView): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer class CurrentUserView(generics.RetrieveAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get_object(self): logger.info(self.request.META) logger.debug(f"CurrentUserView.get_object called for user {self.request.user}") return self.request.user def authenticate(email=None, password=None): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None if user.check_password(password): return user # En tu LoginView class LoginView(APIView): def post(self, request, format=None): user = authenticate(email=request.data.get('email'), password=request.data.get('password')) if user is not None: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) else: return Response(status=401) My models: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_premium = models.BooleanField(default=False) def __str__(self): … -
styling conflicts/incoherence between daisUI and Tailwindcss in a django project
I'm trying to apply daisyUI styling in my django web-app project, and I'm note sure to understand well what's happening with the styling : in my case, I try to add some padding and border to an input text field generated dynamically by a django form : #forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'title': forms.TextInput(attrs={'class': 'py-4 border w-full max-w-xs', 'placeholder':'Title'}), ... in my template I added {{form.title}} inside a form. Here is what it looks like vs what I expect : what I get vs. what I want The styling seems to be overridden somewhere but I'm unable to determine where that comes from... I got the screenshot of "what I want" using my lines of code with this tailwind-play tool More informations that could be useful : Locally on my computer, I installed django-browser-reload. My tailwind.config.js file looks like this : /** @type {import('tailwindcss').Config} */ module.exports = { content: ["../**/templates/**/*.html"], theme: { extend: {}, }, daisyui: { themes: ['light', 'dark', 'bumblebee', 'black', 'luxury', 'night', 'business'], }, plugins: [require("@tailwindcss/typography"), require("daisyui")], } I did try to rerun npm run tailwind-watch, refresh the web page using cmd+shift+R and rerun 'python manage.py runserver` every time … -
how to override a class method in Django Oscar
Currently I can already overwrite the class, but I can't overwrite the method get() what am i missing? I need to do this because if there is only 1 shipping method it does not load the 'Shipping-Method' page and it redirects to the payment page, but I want the customer to see the shipping value before going to the payment page. apps.py import oscar.apps.checkout.apps as apps from oscar.core.loading import get_class from django.urls import path class CheckoutConfig(apps.CheckoutConfig): name = 'apps.checkout' def ready(self): self.shipping_method_view = get_class('checkout.views', 'ShippingMethodViewOverwritten') super().ready() def get_urls(self): urls = super(CheckoutConfig, self).get_urls() urls += [ path('shipping-method/', self.shipping_method_view.as_view(), name='shipping-method'), ] return urls views.py from oscar.apps.checkout import views from oscar.core.loading import get_class ShippingAddressForm, ShippingMethodForm, GatewayForm \ = get_classes('checkout.forms', ['ShippingAddressForm', 'ShippingMethodForm', 'GatewayForm']) from django.contrib import messages Repository = get_class('shipping.repository', 'Repository') class ShippingMethodViewOverwritten(views.ShippingMethodView): template_name = 'oscar/checkout/shipping_methods.html' form_class = ShippingMethodForm pre_conditions = ['check_basket_is_not_empty', 'check_basket_is_valid', 'check_user_email_is_captured'] success_url = reverse_lazy('checkout:payment-method') def get(self, request, *args, **kwargs): if not request.basket.is_shipping_required(): self.checkout_session.use_shipping_method( NoShippingRequired().code) return self.get_success_response() if not self.checkout_session.is_shipping_address_set(): messages.error(request, _("Please choose a shipping address")) return redirect('checkout:shipping-address') self._methods = self.get_available_shipping_methods() if len(self._methods) == 0: # No shipping methods available for given address messages.warning(request, _( "Shipping is unavailable for your chosen address - please " "choose another")) return redirect('checkout:shipping-address') elif len(self._methods) == … -
Django Get a variable from one application view to another application view
i have two different apps in django project where i have views:auths/views.py on this path i have def home(request): users = CustomUser.objects.all() events = Event.objects.all() tags = Tag.objects.all() event_categorys = EventCategory.objects.all() tickets = Ticket.objects.all() if request.user.is_authenticated: email = request.user.email else: email = 'AnonymousUser' if request.method == "GET": url = request.get_full_path() code_index = url.find('code=') if code_index != -1: code = url[code_index + 5:] print("Code is :", code) request.session['code'] = code session_code = code else: session_code = request.session.get('code') get_bearer_token(request) print("ssssssssssssssssssssssssssssssssssss: ", session_code) return render(request, 'home.html', context={'events': events, 'tags': tags, 'event_categorys': event_categorys, 'tickets': tickets, 'session_code': session_code}) and on this path BogID/views.py I have this code : def get_bearer_token(request): # Define the authentication endpoint URL auth_url = "https://account-test.bog.ge/auth/realms/bog-id/protocol/openid-connect/token" session_code = request.session.get('session_code') if session_code: print("Session Code:", session_code) else: print("Session Code not found") payload = { "grant_type": session_code, "client_id": "your_client_id", "client_secret": "your_client_secret" } response = requests.post(auth_url,data=payload) return HttpResponse("asdasd") I am getting the token from the url in the home view,and giving this code to session_code variable,and i am trying to get this variable value with the get_bearer_token view.But It cant see this code in session,Is it because of that they are not in the same app?How can I solve this problem? It is giving me "Session … -
Property Object is not callable with python 3.10 and django 4.1
I am deploying a django application on apache using mod_wsgi. However, I'm getting the following error when wsgi.py is running: File "/home/ubuntu/release/innovate-backend/src/rest_apis/rest_apis/apache/wsgi.py", line 7, in <module> from django.core.wsgi import get_wsgi_application File "/home/ubuntu/miniconda3/envs/py310/lib/python3.10/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/ubuntu/miniconda3/envs/py310/lib/python3.10/site-packages/django/utils/version.py", line 7, in <module> from django.utils.regex_helper import _lazy_re_compile File "/home/ubuntu/miniconda3/envs/py310/lib/python3.10/site-packages/django/utils/regex_helper.py", line 10, in <module> from django.utils.functional import SimpleLazyObject File "/home/ubuntu/miniconda3/envs/py310/lib/python3.10/site-packages/django/utils/functional.py", line 399, in <module> class SimpleLazyObject(LazyObject): TypeError: Error when calling the metaclass bases 'property' object is not callable Following is my wsgi.py file: import os, sys import time import traceback import signal from django.core.wsgi import get_wsgi_application # Calculate the path based on the location of the WSGI script. apache_configuration= os.path.dirname(__file__) project = os.path.dirname(apache_configuration) workspace = os.path.dirname(project) parent = os.path.dirname(workspace) sys.path.append(workspace) sys.path.append(project) sys.path.append(parent) os.environ['DJANGO_SETTINGS_MODULE'] = 'rest_apis.apache.override' application = get_wsgi_application() Any idea what I might be doing wrong ? -
Django Project Questions
I have mac with frontend (react JS based) and backend (Django based). I am seeing error saying, null value in column "customer_id" of relation "main_order" violates not-null constraint DETAIL: Failing row contains (58, 2023-07-20 09:32:15.565247+00, null). Following are the code details: views.py class OrdersList(generics.ListCreateAPIView): queryset = models.Order.objects.all() serializer_class = serializers.OrderSerializer **def post(self, request, *args, **kwargs): print(request.POST) return super().post(request, *args, **kwargs)** class OrderDetails(generics.ListAPIView): queryset = models.OrderItems.objects.all() serializer_class = serializers.OrderDetailsSerializer def get_queryset(self): order_id = self.kwargs['pk'] order = models.Order.objects.get(id=order_id) order_items=models.OrderItems.objects.filter(order=order) return order_items models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_orders') order_time = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.order_time) class OrderItems(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return self.product.title serializers.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = models.Order fields = ['id', 'customer'] def __init__(self, *args, **kwargs): super(OrderSerializer, self).__init__(*args, **kwargs) self.Meta.depth = 1 I am printing the request in post function of OrderList view class and I see <QueryDict: {'customer': ['7']}> <QueryDict: {'customer': ['7']}> I am seeing following error: Internal Server Error: /api/orders/ Traceback (most recent call last): File "/opt/homebrew/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/opt/homebrew/lib/python3.10/site-packages/psycopg/cursor.py", line 723, in execute raise ex.with_traceback(None) psycopg.errors.NotNullViolation: null value in column "customer_id" of relation "main_order" violates not-null constraint DETAIL: Failing row … -
send email with django
I'm trying to configure my email to send an automatic email but whenever I do with my non-google email it gives an error. But when I set up email google accept send I tried to contact my domain hosting team but so far I have no solution for the problem EMAIL_HOST = 'mail.visaogis.co.mz' EMAIL_PORT = 587 EMAIL_HOST_USER = 'baptista@visaogis.co.mz' EMAIL_HOST_PASSWORD = '*******************' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587'`enter code here` EMAIL_HOST_USER = 'baptistaguivala@gmail.com' EMAIL_HOST_PASSWORD = '*************' EMAIL_USE_TLS = True -
How to create a minimal standalone WEB application with Django
Using Pyramid framework a minimal standalone (i.e. not using external WEB server) WEB application can be created as follows: from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def hello_world(request): return Response('Hello World!') if __name__ == '__main__': with Configurator() as config: config.add_route('hello', '/') config.add_view(hello_world, route_name='hello') app = config.make_wsgi_app() server = make_server('0.0.0.0', 1234, app) server.serve_forever() How to achieve this with Django framework? -
Is there a way to create a oauth2 discord link that will automatically add somebody to the server?
Is there a way to create a oauth2 discord link that will automatically add somebody to a server ? Right now I'm just using normal link for authorization https://discord.com/api/oauth2/authorize? -
Not able to connect between Celery and Minio containers?
In my Django app, I'm offloading resizing of uploaded videos to a celery worker. I'm also storing all media files in Minio S3 buckets. The resizing goes well without any errors, however Celery can't connect to the Minio container. This is the logs from Celery: celery-worker_1 | [2023-07-19 20:51:46,076: INFO/MainProcess] Task common.tasks.resize_video[c38a90eb-793e-4190-a681-94b69eafadc8] received celery-worker_1 | ffmpeg version 4.3.6-0+deb11u1 Copyright (c) 2000-2023 the FFmpeg developers celery-worker_1 | built with gcc 10 (Debian 10.2.1-6) celery-worker_1 | ffmpeg version 4.3.6-0+deb11u1[tcp @ 0x55c7500727c0] Copyright (c) 2000-2023 the FFmpeg developers Connection to tcp://localhost:9000 failed: Cannot assign requested address celery-worker_1 | http://localhost:9000/event_media/test_video.mp4: Cannot assign requested address Question is: how do I make the Celery container to connect to http://minio:9000/ rather than to localhost? This is the docker-compose.yml file I'm using: postgres: image: "postgres:14" environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password volumes: - .:/opt/myapp ports: - "5432:5432" redis: image: redis:6 ports: - "6379:6379" minio: image: minio/minio command: minio server /export ports: - "9000:9000" environment: - MINIO_ACCESS_KEY=dev_access - MINIO_SECRET_KEY=dev_secret celery-worker: build: context: . dockerfile: ./Dockerfile.celery env_file: - ./docker.dev.env environment: - CELERY_BROKER_URL=redis://redis:6379 - CELERY_RESULT_BACKEND=redis://redis:6379 depends_on: - redis - postgres command: celery -A myapp worker --loglevel INFO This is contents of the docker.dev.env file: MINIO_STORAGE_ENDPOINT=minio:9000 MINIO_STORAGE_ACCESS_KEY=dev_access MINIO_STORAGE_SECRET_KEY=dev_secret MINIO_STORAGE_USE_HTTPS=False MINIO_STORAGE_MEDIA_BUCKET_NAME=media-dev MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=True MINIO_STORAGE_MEDIA_URL=http://localhost:9000/ DEFAULT_FILE_STORAGE=minio_storage.storage.MinioMediaStorage -
HTTPS Implementation for a Web Application
Hello StackOverflow Community, As a stagiaire working on an IT asset management web application using Python and Django, I'm seeking assistance with implementing HTTPS for our project. If you have experience with HTTPS in Python/Django applications, I'd greatly appreciate your guidance or any code examples you can share to help me secure our web app. Thank you for your support! Best regards, (https://i.stack.imgur.com/fVUnU.png)enter image description hereenter image description here -
Codeigniter like url() helper in django [closed]
I ahve some assets that i want to load in my page and i would like to use codeigniter like url helper https://codeigniter.com/userguide3/helpers/url_helper.html I am loading my logo this way <img src="{% static 'assets/images/logo-white.png' %}?version=4" width="111" height="44" alt="Logo"> but i would like to load it this way <img src="static('assets/images/logo-white.png')" width="111" height="44" alt="Logo"> and this is how i would do it in codeigniter <img src="echo base_url('assets/images/logo-white.png')" width="111" height="44" alt="Logo"> In my view this is possible from django.contrib.staticfiles.templatetags.staticfiles import static static_asset_url = static('assets/images/logo-white.png') but then i would have to pass a lot of assets from view to template. Is there a way i can achieve this <img src="static('assets/images/logo-white.png')" width="111" height="44" alt="Logo">? -
Get mean value for price in dict (Django JSONField)
I need to extract some products from orders with the same SKU number. orders=Order.objects.filter(products__contains=[{"sku":"002-2-1"}]) for e in orders: print(e.products) >>> [{'sku': 002-2-1, 'price': '366.00'}, {'sku': 002-2-1, 'price': '300.00'}] # 2 products in 1 order >>> [{'sku': 002-2-1, 'price': '400.00'}] # 1 product in the order I need to find the mean value of "price" I tried to get a one list with dicts: a = sum(list(orders.values_list("products", flat=True)), []) [{'sku': 002-2-1, 'price': '366.00'}, {'sku': 002-2-1, 'price': '300.00'}, {'sku': 002-2-1, 'price': '400.00'}] How can I find the mean value of price? [mean(e.get("price")) for e in a] May be there is a better way to find it via F? -
React jwt when token expires user doesn't log out
I am doing an app with django rest framework and react, and I found jwt as a way to set authorization. To do it when the user logins I am setting in localStorage the tokens. My problem is that when token expires user doesn't log out. frontend let loginUser = async (e )=> { e.preventDefault() try { const res = await axios.post('http://127.0.0.1:8000/api/token/', { headers: { 'Content-type': 'application/json' }, username: e.target.username.value, password: e.target.password.value }) setAuthTokens(res.data) setUser(jwt_decode(res.data.access)) localStorage.setItem('authTokens', JSON.stringify(res.data)) navigate('/') } catch { alert('Something went wrong') } } django SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(seconds=4), "REFRESH_TOKEN_LIFETIME": timedelta(days=90), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "UPDATE_LAST_LOGIN": False, -
wanted to install face_recogination
Building wheel for dlib (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for dlib (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [78 lines of output] running bdist_wheel running build running build_ext <string>:125: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. Building extension for Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] Invoking CMake setup: 'cmake C:\Users\aakas\AppData\Local\Temp\pip-install-1rhspvxa\dlib_5ca8c32667e347dba6c125d560c25827\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\aakas\AppData\Local\Temp\pip-install-1rhspvxa\dlib_5ca8c32667e347dba6c125d560c25827\build\lib.win-amd64-cpython-311 -DPYTHON_EXECUTABLE=F:\codeClause\faceAuth\env\Scripts\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\aakas\AppData\Local\Temp\pip-install-1rhspvxa\dlib_5ca8c32667e347dba6c125d560c25827\build\lib.win-amd64-cpython-311 -A x64' -- Building for: NMake Makefiles CMake Error at CMakeLists.txt:5 (message): !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! You must use Visual Studio to build a python extension on windows. If you are getting this error it means you have not installed Visual C++. Note that there are many flavors of Visual Studio, like Visual Studio for C# development. You need to install Visual Studio for C++. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -- Configuring incomplete, errors occurred! Traceback (most recent call last): File "F:\codeClause\faceAuth\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module> main() File "F:\codeClause\faceAuth\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\codeClause\faceAuth\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 251, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\aakas\AppData\Local\Temp\pip-build-env-9jngamvo\overlay\Lib\site-packages\setuptools\build_meta.py", line 416, in build_wheel return self._build_with_temp_dir(['bdist_wheel'], '.whl', ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\aakas\AppData\Local\Temp\pip-build-env-9jngamvo\overlay\Lib\site-packages\setuptools\build_meta.py", line 401, in _build_with_temp_dir self.run_setup() File "C:\Users\aakas\AppData\Local\Temp\pip-build-env-9jngamvo\overlay\Lib\site-packages\setuptools\build_meta.py", line 338, in run_setup exec(code, locals()) File "<string>", line 218, in <module> File "C:\Users\aakas\AppData\Local\Temp\pip-build-env-9jngamvo\overlay\Lib\site-packages\setuptools\__init__.py", … -
Getting rain data and rain forecast using openweather map api
Am having a hard time to call rain data from openweather map api. Have anyone ever tried calling the rain data of current weather and it's amount. Also, I have not been able to make predictions like it will rain. Like making the forecasts about rainfall probability. I tried using rain = data['weather'][0]['rain'] I used the same way to call the temperature, description and humidity but on rain it does not work. Am on free plan -
Heroku Migrate not Applying Migrations(Django)
From the first image heroku run python/python3 manage.py migrate is running successfully and applying the migrations. From the second image while trying to create a superuser, I get the error 'unapplied migrations' I have been debugging for almost an hour and it's getting into my nerves. A solution will be helpful. -
Cannot get session data inside a template
I have a Django app with pages as a website. I have a separate Vue app that uses Django Rest Framework for providing the data. I log in on the Vue app and not on the Django app but I would like to show on the Django app that I am logged in also. I have this view for loggin a user in and it works perfectly and I can see the session entry is created in the database. @api_view(["POST"]) def LoginUser(request, *args, **kwargs): email = request.data.get("email") username = request.data.get("username") password = request.data.get("password") if email is None: exists = User.objects.filter(username=username).exists() else: exists = User.objects.filter(email=email).exists() if exists: if email is None: user = User.objects.get(username=username) else: user = User.objects.get(email=email) if user.is_active and user.email_verified_at is not None and user.password != "": if email is None: user = authenticate(username=username, password=password) else: user = authenticate(email=email, password=password) if user: session = SessionStore() session['loggedin'] = True session.save() serializer = LoginSerializer(user) token, created = Token.objects.get_or_create(user=user) response_data = { "Authorization": token.key, "verified": user.verified, "upgraded": user.upgraded, "user": serializer.data } return Response(response_data, status=HTTP_200_OK) else: return Response("Wrong email and/or password", status=HTTP_401_UNAUTHORIZED) else: return Response("Account not active! Changed your email or password?") else: return Response("Email is not registered, please register") On the normal … -
How can i make sure an object wont be added twice
i want to add a movie to watchlist, this is the Movie model from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User from Crew.models import * # from Movies.models import Audience_Review from Details.models import * # Create your models here. # Foreign keys are bookmarked class Movie(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,default=True) name=models.CharField(max_length=100,unique=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) release=models.CharField(max_length=100,blank=True) rating=models.CharField(max_length=20,blank=True) audience_score=models.CharField(max_length=20,blank=True,null=True) poster=models.ImageField(upload_to='movies/poster',blank=True) cover=models.ImageField(upload_to='movies/cover',null=True,blank=True) duration=models.CharField(max_length=50,default=None,blank=True) streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True) ott=models.TextField(max_length=50,blank=True,null=True) starring= models.ForeignKey(Actor,on_delete=models.CASCADE,related_name='actors',blank=True,null=True) actors=models.ManyToManyField(Actor,related_name='actor',blank=True) Characters=models.ManyToManyField(Character,related_name='character',blank=True) director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True) writers=models.ManyToManyField(Writer,related_name='writer',blank=True) cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True) based =models.CharField(max_length=100,blank=True,null=True) genres=models.ManyToManyField(Genre,blank=True) certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True) synopsis=models.TextField(max_length=1000,blank=True) trailer=models.CharField(max_length=500,blank=True) def __str__(self): return self.name this is my Watchlist model, the movie is taken as a foreignkey from django.db import models from django.contrib.auth.models import User from Movies.models import Movie # Create your models here. class Watchlist(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) movie=models.ForeignKey(Movie,on_delete=models.CASCADE) quantity=models.IntegerField(default=1) date=models.DateField(auto_now_add=True) def __str__(self): return self.movie.name this is the url i use to add it to watchlist: href="{% url 'Watchlist:add_watchlist' mov.id %}" this is the path from django.urls import path from Watchlist import views app_name='Watchlist' urlpatterns = [ path('view_watchlist',views.view_watchlist,name='view_watchlist'), path('add_watchlist/<int:p>',views.add_watchlist,name='add_watchlist'), path('delete_watchlist/<int:p>',views.delete_watchlist,name='delete_watchlist') ] this is the views.py type herefrom django.shortcuts import render,redirect from Movies.models import Movie from Movies.views import * from Watchlist.models import Watchlist from django.contrib import messages # from django.contrib.auth.decorators import login_required # Create your views here. def view_watchlist(request): user=request.user watchlist=Watchlist.objects.filter(user=user) #filter … -
How to delete message.info in python django after refreshing the page?
views.py def index(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('register:index') else: messages.info(request, "Username or password incorrect.") return render(request, 'login/login.html') login.html <form action="" method="POST" class="poster"> {% csrf_token %} <div class="input-group mb-4"> <span class="input-group-text"><i class="fas fa-user-alt"></i></span> <input class="form-control" placeholder="Username" required="" type="text" name="username"> </div> <div class="input-group mb-4"> <span class="input-group-text"><i class="fas fa-user-alt"></i></span> <input type="password" id="myInput" placeholder="Password" name="password" class="form-control" data-toggle="password"> </div> <div class="input-group mb-4 d-grid"> <input type="button" class="btn btn-primary" onclick="myFunction()" value="Show password" style="color: aliceblue;" id="show"> </div> <div class="d-grid"> <button type="submit" class="btn btn-success">Sign in</button> <br> <p class="text-center"> Don't have an account? <a href="{% url 'register:index' %}">Sign up</a> </p> </div> </form> {% if messages %} <ul class="messages"> {% for message in messages %} <li style="list-style-type: none; color:rgb(195, 67, 67);"> {{ message }} </li> {% endfor %} </ul> {% endif %} I don't know how to make clear page after refreshing. The message "Username or password incorrect." is always displaying after inputs was incorrect. I've gooogled this problem but it seems to be that everyone pass this problem somehow :/ -
Django Test Client Session expiry
from django.test import Client is not taking expiry I'm setting in my view def form_valid(self, form): remember_me = form.cleaned_data["remember_me"] print("Remember me:", remember_me) # Debug print if not remember_me: self.request.session.set_expiry(1) self.request.session.modified = True return super().form_valid(form) When calling it in testcase def test_form_valid(self): self.client.session.create() # Create a new session for this test case response = self.client.post(reverse('user:login'), {'username': 'testuser', 'password': 'testpassword', 'remember_me': False}, follow=True) expiry_age = self.client.session.get_expiry_age() self.assertRedirects(response, reverse('guarantee:guarantee_list'), fetch_redirect_response=False) print('Session Expiry:', expiry_age) # Since it's not setting to 0 or 1, let's check if it's default (2 weeks) two_weeks_in_secs = 2 * 7 * 24 * 60 * 60 self.assertNotEqual(expiry_age, two_weeks_in_secs) getting Session Expiry: 1209600 -
need help about add function in python django [closed]
the Problem is, that i can not add a new entry. nothing happens when i klick the button! i have checked everything but find no error. i found the project on youtube and wanted to build these to my needs. to do this I watched the video and enter the code. this is my first python code project with django - can someone help me . . . ? here´s my data from the project views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from App.models import Customer from django.contrib import messages from django.http import HttpResponseRedirect # function to insert customer @login_required(login_url = "login") def add_customer(request): if request.method == "POST": if request.POST.get('plantname') and request.POST.get('last_name') and request.POST.get('first_name') and request.POST.get('address') and request.POST.get('zip_code') and request.POST.get('place') and request.POST.get('phone') and request.POST.get('phone2') and request.POST.get('email') and request.POST.get('startup') and request.POST.get('plant_power') and request.POST.get('grid_operator') and request.POST.get('feedintariff') and request.POST.get('own_consumption') and request.POST.get('effect_limit') and request.POST.get('specific_annuayl_yield') and request.POST.get('portal') and request.POST.get('sn_homemanager') and request.POST.get('sn_wifi_modul') and request.POST.get('passwort_portal') and request.POST.get('inverter1') and request.POST.get('inverter1_sn') and request.POST.get('inverter2') and request.POST.get('inverter2_sn') and request.POST.get('batterieinverter') and request.POST.get('batterieinverter_sn') and request.POST.get('batteriemodul') and request.POST.get('plant_password') or request.POST.get('description') and request.POST.get('appointment') and request.POST.get('appointment_done'): customer = Customer() customer.plantname = request.POST.get('plantname') customer.last_name = request.POST.get('last_name') customer.first_name = request.POST.get('first_name') ....... customer.appointment_done = request.POST.get('appointment_done') customer.save() messages.success(request, "Customer added successfully") return HttpResponseRedirect('/backend') else: return render(request, "add.html") urls.py … -
Which is the better django workflows?
Which django-workflow is easy to implement for a project? Iam trying in viewflows and some of the errors are not yet fixed.And is this a good workflow to implement or not?.Iam trying in many ways and not able to get a final result. -
How to send a mail for Mandatory fields if user is updating and non mandatory fields should save in DB in django
If user the is having SPOC role and if user Updating any Mandatory fields in frontend , in back end a mail should trigger to PL with user entered data and existing data of that filed in DB. But data should not save in DB(Data we got in front end by json format) if user is updating any non mandatory fields it should directly save in DB i am implanted this code in django using Curd operation Result which i got : if passed mandatory filed mail is not trigging it saving as new record in DB My code is : @api_view(['PUT']) @csrf_exempt @transaction.atomic def UpdateOnboarding(request): if request.method == 'PUT': data = { "id": 4, "EmpID" : 22470200, } records = Onboarding.objects.filter(id=data['id']) mandatory_fields = ['EmpID ', 'EMP_Name','LAN_Request_Number'] if any(field in data for field in mandatory_fields): if NewUser.UserRole == "SPOC": records = Onboarding.objects.first() send_mail(data,records) # sending mail part return JsonResponse({'message': 'Mail Sent to PL.'}) else: return JsonResponse({'message': 'Invalid'}) instance = Onboarding(**data) instance.save() else: return JsonResponse({'message': 'Not a Put Method'}) data which we got from front in json format for testing purpose i have given data in code data = json.loads(request.body) can anyone please help me