Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best practice for validating a date in url in django?
I have a logging system, where users can log several symptoms for any given day. Im getting the date as slug in my url, but I need to validate it. Which one is best practice, and why? make a validator function in the class view and use it there add a hidden form field, and write a custom DateValidator for it? -
Relation "auth_user" does not exist error when running a GitHub action
I have the following GitHub CI configuration for the Django app. The action fails on error relation "auth_user" does not exist. The project has a custom authorization model AUTH_USER_MODEL = "uzivatel.User", which is developed in the uzivatel app. Here is the ci.yml file. The project configuration can be found here: https://github.com/ARUP-CAS/aiscr-webamcr/blob/dev/webclient/webclient/settings/base.py. name: Django Tests on: push: branches: - dev jobs: build: runs-on: ubuntu-20.04 services: postgres: # we need a postgres docker image to be booted a side car service to run the tests that needs a db image: postgis/postgis env: # the environment variable must match with app/settings.py if block of DATBASES variable otherwise test will fail due to connectivity issue. POSTGRES_USER: test_user POSTGRES_PASSWORD: test_secretpass POSTGRES_DB: test_db ports: - 5432:5432 # exposing 5432 port for application to use # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | python -m pip install --upgrade pip pip install wheel pip install -r webclient/webclient/requirements/dev.txt - name: Install gdal dependencies run: | sudo apt-get update sudo apt-get install -y libgdal-dev locales gdal-config --version … -
Error when adding a warning before deleting a django model record
I am looking to popup a model warning about the deletion of a model record, however when looping into a table, all links lead to delete the very first record in the table, what I am doing wrong? Here is my code: #models: class Company(models.Model): teamname = models.CharField(max_length=100,unique=True) address = models.CharField(max_length=300) office = models.CharField(max_length=100) def __str__(self): return self.teamname class Meta: ordering = ['teamname'] class Contact(models.Model): teamname = models.ForeignKey(Company,on_delete=CASCADE) firstname = models.CharField(blank=True,null=True,max_length=20) lastname = models.CharField(blank=True,null=True,max_length=20) position = models.CharField(max_length=30,choices=( ('Option1','Option1'), ('Option2','Option2'), )) cellphone = models.CharField(max_length=30,null=True,blank=True) email = models.EmailField(blank=True,null=True) birthday = models.DateField(blank=True,null=True) def __str__(self): return str('%s, %s' % (self.lastname, self.firstname)) class Meta: ordering = ['id','position','lastname','firstname'] html/bootstrap code: <table id="datatable" class="table table-bordered dt-responsive nowrap w-100"> <thead> <div style="text-align: center;" class="card-body"> <h4>Contact list</h4> </div> <tr> <th style="text-align: center;">First name</th> <th style="text-align: center;">Last Name</th> <th style="text-align: center;">Position</th> <th style="text-align: center;">Cellphone</th> <th style="text-align: center;">Email</th> <th style="text-align: center;">Birthday</th> <th style="text-align: center;">Edit</th> <th style="text-align: center;">Delete</th> </tr> </thead> {% for j in obj2 %} <tbody> <tr> <td style="text-align: center;">{{j.firstname}}</td> <td style="text-align: center;">{{j.lastname}}</td> <td style="text-align: center;">{{j.position}}</td> <td style="text-align: center;">{{j.cellphone}}</td> <td style="text-align: center;"><a href="mailto:{{j.email}}">{{j.email}}</a></td> <td style="text-align: center;">{{j.birthday}}</td> <td style="text-align: center;"><a href="/clients/edit/contact/{{j.id}}" class="text-success"><i class="mdi mdi-pencil font-size-18"></i></a></td> <td style="text-align: center;"> <i style="color: red; font-size: 16px; cursor: pointer;" data-bs-toggle="modal" data-bs-target="#deleteRecord" class="bx bx-trash"></i> </td> <div class="modal … -
Django DurationField and 00:00:00 versus NULL
Using Django 3.2.7, python 3.9.x and Mysql 8.x. With models like this: class Object(models.Model): period = models.DurationField('Period', null=False, blank=False, default=timedelta(days=1)) class Subobject(models.Model): object = models.ForeignKey(Object, null=False, blank=False, on_delete=models.CASCASE) period = models.DurationField('Period', null=True, blank=True) and the following query: sub_objs = Subobject.objects.select_related( 'object' ).annotate( actual_period=Case( When( period__isnull=False, then=F('period') ), default=F('object__period'), output_fields=models.DurationField() ) ).filter( actual_period__gte=timedelta(seconds=3600) ) Which could be humanly translated as: "for each subobject, assign a variable named actual_period, whose value is period when found 'locally' in each object, with a fallback to the parent object.period property when not; then filter, etc." This works, but let us imagine a case where a subobject has to have a period property set to "no time at all", i.e., a timedelta == 0 seconds. I tried setting a subobject.period field to 00:00:00 in the admin, or to timedelta(seconds=0) programmatically, and it seems django (Mysql?) always considers such a timedelta as being null. The consequence being that, in the above query, the parent object's period property is applied in the annotation. Is this working as intended? Is there a way to have django/mysql consider that a "zero-time timedelta" is not a null value? -
Django sudden error: "AuthMissingParameter at /complete/google-oauth2/", when using GoogleOAuth2 from social-auth-app-django package
I have a running Django application (runs for already 2 years+). I'm using the social-auth-app-django to manage my users authentication with Google. Suddenly today i got errors from users that can not get inside my app. I also get the same error on my local and production environment: My settings.py related params are: AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) ## Google Credentials SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('GOOGLE_AUTH_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get('GOOGLE_AUTH_SECRET') print("TESTING") print("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY:\n", SOCIAL_AUTH_GOOGLE_OAUTH2_KEY) print("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET:\n", SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'http://MyAppHost/complete/google-oauth2/' # Login URL LOGIN_URL = '/login/google-oauth2/' # Where user is directed after login/logout LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' I double verified that the SOCIAL_AUTH_GOOGLE_OAUTH2_KEY and SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET really match what i see in the google API-credentials page Moreover, i verified that my Authorized redirect URIs configured properly. When i try to enter the URL presented in the redirect_uri (http://localhost:5000/complete/google-oauth2/) i get the error: AuthMissingParameter at /complete/google-oauth2/ Missing needed parameter state Request Method: GET Request URL: http://localhost:8000/complete/google-oauth2/ Django Version: 2.2.3 Exception Type: AuthMissingParameter Exception Value: Missing needed parameter state Exception Location: /Volumes/dev/venv/lib/python3.6/site-packages/social_core/backends/oauth.py in validate_state, line 85 Python Executable: /Volumes/dev/venv/bin/python3 Python Version: 3.6.2 -
Getting commanderror although i set debug is true in django settings
I am using django 3.2.8. I set DEBUG = True and ALLOWED_HOSTS = ['*'] in my project settings.py file. When i try to "python3 manage.py runserver" it gives below error. I is strange, because DEBUG is set to True in settings.py. But it says debug is false. Also i have this setting in my other project and it is working with Debug=True. -
Django view get() takes 1 positional argument but 2 were given
I am making API with Django. Crawled data is saved well in DB, but I have a problem with making API. views.py from django.shortcuts import render from rest_framework.response import Response from .models import ReviewData from .models import BuildingData from rest_framework.views import APIView from .serializers import ReviewSerializer from .serializers import BuildingSerializer from django.shortcuts import render, get_object_or_404 class BuildingInfoAPI(APIView): def get(request): queryset = BuildingData.objects.all() serializer = BuildingSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(request): queryset = ReviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<slug:slug>/', ReviewListAPI.as_view()) ] serializers.py from rest_framework import serializers from .models import ReviewData from .models import BuildingData class BuildingSerializer(serializers.ModelSerializer) : class Meta : model = BuildingData fields = '__all__' class ReviewSerializer(serializers.ModelSerializer) : class Meta : model = ReviewData fields = '__all__' models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify def generate_unique_slug(klass, field): origin_slug = slugify(field, allow_unicode=True) unique_slug = origin_slug numb = 1 while klass.objects.filter(slug=unique_slug).exists(): unique_slug = '%s-%d' % (origin_slug, numb) numb += 1 return unique_slug class BuildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) building_loc … -
Django model organization issue
I'm developing recipe and ingredient models. models.py: class Recipe(models.Model): """Recipe structure""" author = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField(max_length=40, unique=True) picture = models.ImageField(blank=True, null=True) text = models.TextField(max_length=100, blank=True, null=True) components = models.ManyToManyField('Component') tag = MultiSelectField(max_length=10, choices=tags) cooking_time = models.IntegerField( validators=[MinValueValidator(1, 'Value cannot be lower than 1')] ) slug = models.SlugField() def __str__(self): return self.title class Meta: db_table = 'recipes' verbose_name = 'Рецепт' verbose_name_plural = 'Рецепты' class Component(models.Model): """Component structure""" title = models.CharField(max_length=50, unique=True) unit = models.CharField(max_length=10, choices=units) def __str__(self): return self.title class Meta: db_table = 'components' verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class Component_quantity(models.Model): """Table linking quantity with recipe and component together""" recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) component = models.ForeignKey(Component, on_delete=models.CASCADE) quantity = models.DecimalField( max_digits=5, decimal_places=1, verbose_name='Количество', validators=[MinValueValidator(1)] ) class Meta: db_table = 'quantity_and_recipe_linking_table' unique_together = ('recipe', 'component') verbose_name = 'Ингредиент в рецепте' verbose_name_plural = 'Ингредиенты в рецепте' The problem is to link the recipe and the component in the Component_quantity model so that in the component field it is possible to select only those entities that are specified in the recipe itself. Is it possible to do this? -
CSS in Django template works partially
Imagine I have a base.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>sometitle</title> <link href="{% static 'ptoject/styles.css' %}" rel="stylesheet" type="text/css" /> </head> <body> {% block one %} {% enblock %} {% block two %} {% enblock %} </body> and I have fully finished styles.css and html code in template blocks The problem is: rules in styless.css are fully applyed only to html code inside that two template blocks but partially to parrent (base.html) template. (There's no any .css static loads in those {% blocks %}) It all works great if i open my monolit (not separated in blocks) html in browser manually, but not if I run it in django Things I've already done: checked STATIC_URL in settings.py -
JavaScript send value to the backend (hidden html input or all means)
I have two really simple form that looks like this: <form name='a' id='a'> // form a <input type="text" name="x" id="x"> //input 1 <input type="text" name="y" id="y"> //input 2 <button>submit</button> </form> when the form a is submitted, the URL query string will look like example.com/?x=1&y=2 <form name='b' id='b' method="POST"> //form b <input type="hidden" name="sum" id="sum"> // hidden input sum </form> I have a computation script code that calculates the sum of input 1 and input 2 then stores the sum to hidden "input sum" inside "form b" <script> window.addEventListener("DOMContentLoaded", function(){ function calculate(){ // I want it also to work when someone paste the url example.com/?x=1&y=2 const urlParams = new URLSearchParams(window.location.search); x = urlParams.get('x') y = urlParams.get('y') sum = x+y document.getElementById('sum').value = sum //store sum to hidden input } }); calculate() </script> How do I send value of hidden "input sum" to the backend(Django) when someone submits form a or paste the URL? Also: document.getElementById('b').submit(); // will refresh page indefinitely, tried ajax e.prevetdefault(), didn't work, open to all ideas. -
Find the type of visible field from visible_fields()
I've the following code inside my forms.py. I'm using ModelForm to generate the form view def __init__(self, *args, **kwargs): super(NewPlayerForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): print(visible) visible.field.widget.attrs['class'] = 'form-control' The aim is to not put the form-control class on a field of type boolen/checkbox. But I'm having a hard time in figuring out how to get the field type from the above lines. print(visible) shows the following in the console I tried using field.type or field.getType(), nothing seems to work. -
Create several objects at once Django Rest Framework Generic Views
I'm using Django Rest Framework. I'm trying to create a listcreateapiview to create several objects at once but nothing I've found so far seems to work and not sure why. #My view class MyListCreateView(ListCreateAPIView): serializer_class = MySerializer def get_queryset(self): return Mymodel.objects.filter(user=self.request.user.id) # tried this with no luck def get_serializer(self, instance=None, data=None, many=False, partial=False): if data is not None: data.is_valid(raise_exception=True) return super(MyListCreateView, self).get_serializer(instance=instance, data=data, many=True, partial=partial) else: return super(MyListCreateView, self).get_serializer(instance=instance, many=True, partial=partial) def perform_create(self, serializer): user_obj = self.request.user serializer.save(user=user_obj) #my serializer class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__'``` -
'ascii' codec can't encode character '\u2019' in position 609: ordinal not in range(128). Django
I try to make reset password system in django python. so i make this url.py from django.urls import path from app import views from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from .forms import LoginForm, MyPasswordChangeForm, MyPasswordResetForm urlpatterns = [ path('passwordchange/', auth_views.PasswordChangeView.as_view(template_name='app/passwordchange.html', success_url="/passwordchangedone/", form_class=MyPasswordChangeForm), name='passwordchange'), path('passwordchangedone/', auth_views.PasswordChangeView.as_view(template_name='app/passwordchangedone.html'), name='passwordchangedone'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='app/password_reset.html',form_class=MyPasswordResetForm), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='app/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='app/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='app/password_reset_complete.html'), name='password_reset_complete'), ] and this is my settings.py class MyPasswordResetForm(PasswordResetForm): email = forms.EmailField(label=_("Email"), max_length=254,widget=forms.EmailInput(attrs={'autocomplete':'email','class':'form-control'})) i try to import whatever that this system need, but still not working, i try to copy and paste the code from my another project but still not working, i try to match my script and another project script i added that miss in my script but not working. anybody can help -
Django REST Framework: How to use prefetched queriesets in child serializers in nested serializers
I want to call a queryset prefetched from a View from a nested serializer child. I tried the following but it did not work the way I intended. How can I call a prefetched queryset from a child serializer? #views.py class PlaylistListView(generics.ListAPIView): serializer_class = PlaylistSerializer def get_queryset(self): return ( Playlist.objects.all() .prefetch_related("user", "user__emailaddress_set") ) #serializers.py class UserDetailSerializer(serializers.ModelSerializer): is_verified = serializers.SerializerMethodField() class Meta: model = User fields = ("is_verified",) def get_is_verified(self, user): return user.emailaddress_set.filter(verified=1).count() > 0 class PlaylistSerializer(serializers.ModelSerializer): user = UserDetailSerializer(read_only=True) class Meta: model = Playlist fields = ("user",) -
Channels Layers: InMemoryChannelLayer or RedisChannelLayer DRF
I am a channels beginner and I want to know when should I use the channels.layers.InMemoryChannelLayer and channels_redis.core.RedisChannelLayer? I've read that channels.layers.InMemoryChannelLayer should be used when testing applications and channels_redis.core.RedisChannelLayer should be use in the production phase, but what is the reason? What are the advantages of using redis in this case and what role it plays? I would like a reasonably detailed explanation. -
I have a Django project where users can authorize through Github. How can I add github users avatar as well?
My project is a Django blog. Users already can authorize using Github, but avatar does not save. -
Where is the order stored?
I am watching a youtube tutorial, he created a function for placing order, but where is it stored? function order(){ var msg = note.value; var orders = localStorage.getItem('orders'); var ur = '/cart/'; var orderData = {}; orderData['orders'] = orders; orderData['note'] = msg; $.ajax({ url:ur, type: "POST", data: orderData, success: function(data){ window.location.replace('/success') localStorage.setItem('orders', JSON.stringify([])); localStorage.setItem('total', 0); } }) } -
Outlook blocks emails
Something a little strange is happening to me. I created a google email for password-reset, account-activation etc.... On the @outlook emails I can't get the password-reset one while the others arrive. I tried to change the EMAIL_HOST_USER with my personal google email and everything works. Also in the mailbox all the emails are sent but not received. Can someone help me? This is my urls.py: path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password/password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password/password_reset_complete.html"), name="password_reset_complete"), and my settings: #SMTP CONFIGURATION EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypsw' -
Server Error (500) after deploying django app
I have to deploy a PyTorch model using Django and I have static files which include images, CSS, and javascript files. After deploying by using whitenoise and disabling COLLECTSTATIC I am getting server errors after deploying using Heroku. need help. I have attached my settings.py file code below for reference from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-2e(@-ilm2ph7sx34c-0^!o4bcjt2#fx^j=l(m$ey@aqe823q62' DEBUG = False ALLOWED_HOSTS = ['labwebsitetest.herokuapp.com','127.0.0.1:8000'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'lab.apps.LabConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'website.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' -
how to pass data in array to post method in angular and django?
I am trying to pass a list of student IDs but it is not working. from angular I am passing dataas follows let noticeData = this.announceForm.value; if (noticeData.students.includes('all')){ noticeData.students = noticeData.students.filter((s) => s != 'all') } noticeData.students = JSON.stringify(noticeData.students); from django i am reading and trying to store data as Below is the to_internal_value method which I have overridden. def to_internal_value(self, data): tempdict = data.copy() tempdict['students'] = json.loads(data['students']) data = tempdict return super(NoticesSerializer, self).to_internal_value(data) but it always returns the same error {students: [“Incorrect type. Expected pk value, received list.”]} -
How to create multiple types of users in Django without using forms
I want to create 2 types of users - Customer and Company, both having different parameters. I've searched nearly everything but everyone uses OneToOne Field relationship and uses django forms. I'm new to django and just want to create an API and not any HTML. These are my models - class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=100) email = models.EmailField(_('email address'), unique=True) class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company_name = models.CharField(max_length=100) company_email = models.EmailField(_('email address'), unique=True) I've created a serializer for my custom user named UserSerializer and used it in my model serializer. class CustomerSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Customer fields="__all__" class CompanySerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Company fields="__all__" Below is my views.py file for Customer - class register(APIView): def post(self, request, format=None): user_serializer = UserSerializer(data=request.data) if user_serializer.is_valid(): user = User.objects.create_user(email=request.POST.get('email'), contact=request.POST.get('contact'), is_staff=request.POST.get('is_staff'), is_superuser=request.POST.get('is_superuser')) customer_serializer = CustomerSerializer(data=request.data) if customer_serializer.is_valid(): customer_serializer.save() return Response(customer_serializer.data, status=status.HTTP_200_OK) else: return Response(customer_serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) In this code, I'm getting an error - "Column 'user_id' cannot be null". user_id is the foreign key in Customer related to users. But while registering, user is created and it is assigned a random id. I … -
Second Session ENGINE without expiry date
I have Product model: class Product(models.Model): title = models.CharField(max_length = 25) description = models.TextField(blank = True, null = True) price = models.IntegerField(default = 0) image = models.ImageField(upload_to = 'products/images', null = True, blank = True) image_url = models.URLField(null = True, blank = True) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) product_views = models.IntegerField(default = 0) def __str__(self): return self.title class Meta: ordering = ['title'] In each user view, I add one to product_views. views.py: def product_detail_view(request, id): if 'views' not in request.session: request.session['views'] = [] arr = request.session['views'] # obj = Product.objects.get(id = id) obj = get_object_or_404(Product, id = id) if id not in arr: arr.append(id) request.session['views'] = arr obj.product_views = obj.product_views + 1 obj.save() context = { 'object': obj, } return render(request, 'home/detail.html', context) I set SESSION_COOKIE_AGE = 86400 in settings.py. It works great. But there's one problem. In my app user can log in and after a day, he has to log in again. I wanted to add Remember me checkbox to my log in, but here's problem. I can't set specific expire time for specific key. So I have to make my own 2nd Session Engine. I wrote this: class ProductViews(models.Model): product = models.ForeignKey(Product, … -
Django Rest Framework - Cookies disappear after redirect/refresh
I am first time working with jwt tokens for loggin in and storing that token by backend in http only cookies with one more cookie. The problem is, In login page when i logs in..cookies are setting properly but when page redirects to profile page cookies are lost and login becomes logout. I trid refresh and found same issue. Please help me.. Its only happening in production not in development. My domains are -- In development frontend - 127.0.0.1:5501 backend - 127.0.0.1:8000 In Production frontend - https://xyz.netlify.app backend - https://xyz-web.herokuapp.com My cors setting CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SAMESITE = 'None' ACCESS_CONTROL_ALLOW_HEADERS = True CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Access-Control-Allow-Origin' ] # CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:5501", "https://xyz.netlify.app" ] My login view setting the cookies after login def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } class LoginView(APIView): def post(self,request,format=None): data = request.data response = Response() username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure … -
How to setup a frontend pipeline embedded into Django app
I am following a guide online but I am having an issue with getting my front-end pipeline embedded in my Django app. The steps I took were... create a folder (I called it test-project) create virtual environment python -m venv venv Installed Django while in my virtual environment started Django Project django-admin startproject myapp inside /test-project/myapp/ create folders assets, static, templates inside /test-project/myapp/ ran in command line npm init -y inside /test-project/myapp/ ran in command line yarn add webpack webpack-cli --save-dev inside /test-project/myapp/assets/ created file index.js and added the following code function component() { const element = document.createElement('div'); element.innerHTML = 'Hello webpack'; return element; } document.body.appendChild(component()); created in /test-project/myapp/ file webpack.config.js and added the following const path = require('path'); module.exports = { entry: './assets/index.js', // path to our input file output: { filename: 'index-bundle.js', // output bundle file name path: path.resolve(__dirname, './static'), }, }; added to package.json file in /test-project/myapp/ to the "scripts" key "dev": "webpack --mode development --watch" Ran yarn run dev and /test-project/myapp/static/index-bundle.js file got created in /test-project/myapp/templates/ created file hello_webpack.html and added the following {% load static %} <!doctype html> <html> <head> <title>Getting Started with Django and Webpack</title> </head> <body> <script src="{% static 'index-bundle.js' %}"></script> </body> </html> … -
why filter doesn't change value in iteration in django template
I have custome filter in to_and.py file for getting verbose name from django import template register = template.Library() @register.filter def verbose_name(objects): return objects._meta.verbose_name but when I get the value in view it only give me the first model name in iteration my code queryset has two indivial model {% load to_and %} {{links}} {% for link in links %} {% if link|verbose_name == "Unit" %} {{link|verbose_name}} {{link.id}} {% endif %} {% endfor %} see the out put of this code