Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering objects based on many-to-many field in current object
I have a drinks recipe app I'm building that has tags in a many-to-many field that are part of each drink. The tags are a basic taste description. I now want to display 3 similar drinks based on the tag of the current drink. My view looks like this: def drinkdetail_view(request, slug=None): #Grab the correct drink try: obj = DrinkRecipe.objects.get(slug=slug) except: obj = None if obj is None: return HttpResponse("Not found.") context = { "drink": obj, } return render(request,'drinks/drinkdetail.html', context) The model looks like this: class Tag(models.Model): drinkTag = models.CharField(max_length=255, blank=False) def __str__(self): return f"{self.drinkTag}" class TagTaste(models.Model): drinkTagTaste = models.CharField(max_length=255, blank=False) def __str__(self): return f"{self.drinkTagTaste}" class Ingredient(models.Model): ingredientRum = models.ForeignKey('Bottle', on_delete=models.SET_NULL, null=True, blank=True) ingredientName = models.CharField(max_length=255, blank=True) ingredientAmount = models.DecimalField(decimal_places=1,max_digits=5) drink = models.ForeignKey('DrinkRecipe', on_delete=models.CASCADE) def __str__(self): if self.ingredientRum: return f"{self.ingredientRum}" else: return f"{self.ingredientName}" class DrinkRecipe(models.Model): drinkTag = models.ManyToManyField(Tag) drinkTagRum = models.ForeignKey(Bottle, on_delete=models.SET_NULL, null=True) drinkTagTaste = models.ManyToManyField(TagTaste) drinkName = models.CharField(max_length=255, blank=False) drinkDescription = HTMLField() drinkImage = models.ImageField(upload_to=image_upload_handler) drinkActive = models.BooleanField(default=True) slug = models.SlugField(unique=True, blank=True, null=True) imgLocation = 'drinks' def __str__(self): return f"{self.drinkName}" def get_ingredients(self): return self.ingredient_set.all() def get_absolute_url(self): return reverse ('rhumSite:drinkDetail', kwargs={'slug':self.slug}) How do I filter for drinkTag or drinkTagTaste in my view based on the current drink? Any help would … -
Django. How to make a sidebar with date sorted?
I'm currently creating a Journal application using Django. I want to make a sidebar that includes the Year, Month and Date. Whenever the user create a new journal, it will also updated on the sidebar. Look like this: However, the result is not what I want. I have created 10 journal entries, and it does have 10 on the sidebar, but it shows nothing. Code: sidebar.html {% for journal in journals %} <li> <a href="#year">{{ journal.year|date:"Y" }}</a> <ul class="submenu"> {% for month in journal.month|dictsort:"month" %} <li> <a href="#month">{{ month.0|date:"F" }}</a> <ul class="submenu"> {% for day in month.1|dictsort:"day" %} <li><a href="#day">{{ day.0|date:"j/n/Y" }} ({{ day.1.count }})</a></li> {% endfor %} </ul> </li> {% endfor %} </ul> </li> {% endfor %} models.py class Journal(models.Model): title = models.CharField(max_length=200, blank=True, default="No Entry") content = models.TextField(blank=True, default="No Entry") date_created = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) views.py def journal_sidebar(request): journals = Journal.objects.annotate( year=TruncYear('date_created'), month=TruncMonth('date_created'), day=TruncDay('date_created') ).values('year', 'month', 'day').annotate(count=Count('id')).order_by('-year', '-month', '-day') return render(request, 'navbar.html', {'journals': journals}) -
MultiValueDictKeyError on a Django form
I cant find the error in here when clicking the follow or unfollow button this message keeps coming. MultiValueDictKeyError at /unfollow 'userfollow' Request Method: POST Exception Type: MultiValueDictKeyError Exception Value:'userfollow' I tried request.POST.get() and got another error. views.py def follow(request): userfollow = request.POST['userfollow'] currentUser = User.objects.get(pk=request.user.id) userfollowData = User.objects.get(username=userfollow) f = Follow(user=currentUser, user_follower=userfollowData) f.save() user_id = userfollowData.id return HttpResponseRedirect(reverse(profile, kwargs={'user_id': user_id})) def unfollow(request): userfollow = request.POST['userfollow'] currentUser = User.objects.get(pk=request.user.id) userfollowData = User.objects.get(username=userfollow) f = Follow.objects.get(user=currentUser, user_follower=userfollowData) f.delete() user_id = userfollowData.id return HttpResponseRedirect(reverse(profile, kwargs={'user_id': user_id})) profile.html {% extends "network/layout.html" %} {% block body %} <h1>{{ profile.username }}</h1> <div class="container"> <div class="row d-flex justify-content-center"> <h3 class="col-4">Followers: {{ followers.count}} </h3> <h3 class="col-4">Following: {{ following.count}} </h3> {% if user.is_authenticated %} {% if user != user_profile %} {% if isFollowing %} <form action="{% url 'unfollow' %}" method="post"> {% csrf_token %} <input type="hidden" name"userfollow" value="{{ user_profile }}" /> <input type="submit" value="Unfollow" /> </form> {% else %} <form action="{% url 'follow' %}" method="post"> {% csrf_token %} <input type="hidden" name"userfollow" value="{{ user_profile }}" /> <input type="submit" value="Follow" /> </form> {% endif %} {% endif %} {% endif %} </div> </div> {% endblock %} Help would be appreciated! -
How to fix django error with redirection?
I recently started learning Django and while i tried to understand redirect function i face such problem: on the page 127.0.0.1/blog you can call /archive/ year must be 2020 <= year <= 2023. I tried this code(blog.views): from django.shortcuts import render, redirect from django.shortcuts import HttpResponse, Http404 def index(request): return HttpResponse('<title>Blog main page</title>' '<h1>Index page</h1>') def blog_page(request, page_number): return HttpResponse(f'<title>Blog page{page_number}</title>' f'<h1>Page {page_number}</h1>') def archive(request, year): if 2020 <= int(year) <= 2023: return HttpResponse(f'<title>{year}</title>' f'<h1>Archive from {year} year</h1>') else: return redirect(index, permanent=True) def error_404(request, exception): return HttpResponse('<h1 style="font-size: 9em;text-align: center;">404</h1>', status=404) this is blog.urls: from django.urls import path, re_path from .views import * urlpatterns = [ path('', index), path('<int:page_number>/', blog_page), path('archive/<int:year>/', archive) ] This is coolsite.urls from django.contrib import admin from django.urls import path, include import blog.views from blog.views import * from django.conf.urls import handler404 urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] handler404 = error_404 this is my project architecture: architecture I tried to go to page /blog/archive/2019 and i was redirected to index(it's fine) I tried to go to page /blog/archive/2023 and site return me archive page(it's fine) I tried to go to page /blog/archive/2025 and i was redirected to index(it's fine) BUT whe i tried to go … -
Django cant access S3 bucket unless policy completely open to public
I am attempting to use an AWS S3 bucket for static and media files. I am able to get files to the bucket with "python manage.py collectstatic" with the IAM user credentials set in the settings.py file. However, I am not able to access files in the bucket unless I set a bucket policy that is completely open to the public - as below: { "Version": "2012-10-17", "Statement": [ { "Sid": "AddPerm", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::bucketname/*" } ] } If I set the policy to only specifically allow an IAM user (below), I get "access forbidden errors." { "Version": "2012-10-17", "Id": "ExamplePolicy01", "Statement": [ { "Sid": "AddPerm", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::499213337707:user/bucketusername" }, "Action": [ "s3:GetObject", "s3:GetBucketLocation", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::bucketname/*" ] } ] } I have double checked to make sure my IAM access key and secret key are correct. How can I fix this so that only connections with the correct credentials can access the bucket? relevant settings.py: #S3 Bucket config AWS_ACCESS_KEY_ID = 'Key ID here' AWS_SECRET_ACCESS_KEY = 'secret key here' AWS_STORAGE_BUCKET_NAME = 'bucketname' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' #AWS S3 Settings AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' … -
Creating a routesheet with multiple models in one table
I'm trying to create a routesheet app for my logistics managing django app. Here are my models: class RouteSheet(models.Model): start_program = models.DateTimeField(auto_now_add=True, verbose_name='Start program') end_program = models.DateTimeField(auto_now=True, verbose_name='End program') start_km = models.PositiveSmallIntegerField(verbose_name='Starting kilometer') end_km = models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='Ending kilometer') truck = models.ForeignKey(Trucks, on_delete=models.CASCADE, verbose_name='Truck') trailer = models.ForeignKey(Trailers, on_delete=models.CASCADE, verbose_name='Trailer') created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='routesheet_created') class LoadingSheet(models.Model): loading_time = models.DateTimeField(auto_now_add=True, verbose_name='Loading time') loading_km = models.PositiveSmallIntegerField(verbose_name='Loading kilometer') loading_location = models.CharField(max_length=100, verbose_name='Loading location') route_sheet = models.ForeignKey(RouteSheet, on_delete=models.CASCADE, related_name='loading_sheet', verbose_name='Route sheet') loading_image = models.ImageField(null=True, blank=True, upload_to='media/routesheet/loading-images/', verbose_name='Loading image') class UnloadingSheet(models.Model): unloading_time = models.DateTimeField(auto_now_add=True, verbose_name='Unloading time') unloading_km = models.PositiveSmallIntegerField(verbose_name='Unloading kilometer') unloading_location = models.CharField(max_length=100, verbose_name='Unloading location') route_sheet = models.ForeignKey(RouteSheet, on_delete=models.CASCADE, related_name='unloading_sheet', verbose_name='Route sheet') unloading_image = models.ImageField(null=True, blank=True, upload_to='media/routesheet/unloading-images/', verbose_name='Unloading image') class FuelSupply(models.Model): supply_time = models.DateTimeField(auto_now_add=True, verbose_name='Supply time') supply_km = models.PositiveSmallIntegerField(verbose_name='Supply kilometer') supply_location = models.CharField(max_length=100, verbose_name='Supply location') supply_size = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='Supply size (in liters)') supply_cost = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Supply cost') supply_company = models.CharField(max_length=100, verbose_name='Supply company') supply_observations = models.CharField(max_length=300, verbose_name='Observations') route_sheet = models.ForeignKey(RouteSheet, on_delete=models.CASCADE, related_name='supply_sheet', verbose_name='Route sheet') supply_image = models.ImageField(null=True, blank=True, upload_to='media/routesheet/fuel-supply-images/', verbose_name='Supply image') What I'm trying to achieve is have a start_program where I start when creating a route sheet with a form for starting the program where I add the start_km, truck, trailer, and for … -
Django FULL JOIN
I'm experiencing some struggles with querying data with Django ORM. Database for a store. Each employee has a yearly goal for sold and reserved phone of different models. Diagram of my tables so far These tables can be matched by (seller, phone_model) combination My models so far class SoldReserved(models.Model): serial_number = models.CharField(max_length=255, unique=True) seller = models.ForeignKey(Employee, on_delete=models.CASCADE, blank=True, null=True) phone_model = models.ForeignKey( PhoneModel, on_delete=models.CASCADE, blank=True, null=True ) # this field will contain the status information E.g. "sold" or "reserved" status = models.CharField(max_length=32, blank=True, null=True) class SellGoal(models.Model): class Meta: unique_together = [["seller", "phone_model", "year"]] id = ShortUUIDField(length=16, max_length=40, primary_key=True) seller = models.ForeignKey(Employee, on_delete=models.CASCADE) phone_model = models.ForeignKey( PhoneModel, on_delete=models.CASCADE, blank=True, null=True ) year = models.SmallIntegerField() goal = models.IntegerField() class ReserveGoal(models.Model): class Meta: unique_together = [["seller", "phone_model", "year"]] id = ShortUUIDField(length=16, max_length=40, primary_key=True) seller = models.ForeignKey(Employee, on_delete=models.CASCADE) phone_model = models.ForeignKey( PhoneModel, on_delete=models.CASCADE, blank=True, null=True ) year = models.SmallIntegerField() goal = models.IntegerField() There can be some sold phones without any associated goals. And there can be goals, that don't have associated entries in SoldReserved table. My goal here is to fetch all for all goals and for all SoldReserved entries. After fetching I'm going to annotate the queryset and serialize it with serializer: class … -
Role based access control django like AWS IAM
Recntly I am working on a project where I need to apply role based access control(RBAC) something like AWS IAM. Django already have Groups & permission. I can create a group & add user on that group. Then the user on that group can access to resource. But I've got a problem on that solution. In AWS IAM user can log in to the same account not a different account. How can I implement same feature like aws. I don't want to use account id like aws, user can login with their email/phone & password. Some of my models I use a field created_by with a relation with user. On my views, my queryset something like this MyModel.objects.filter(created_by=request.user). The problem is suppose I give user1 permission to access MyModel. user1 doesn't have any objects created by himself. He need to view the objects that created by the root user. There is also another problem is that the root user isn't belong to any group. I tried using group & permission which provided by django. I also customize the django Group model add a field created_by to track the group owner. But what if the user1 create a group and the … -
Field 'id' expected a number but got <User: Aditya@123>
I am using nested serializer for Django user module and BookDetail where user is Foreign key in BookDetail model. For perform_create method I am getting this error. Instead of considering id, self.request.user is considering username class BookDetailsList(ListCreateAPIView): serializer_class = BookDetailsSerializer permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): serializer.save(user_id=self.request.user) def get_queryset(self): return Book_Detail.objects.filter(user_id=self.request.user) I tried different ways to get id but I am always getting <User: Aditya@123>. I am expecting to get User Model "id" in perform_create method models.py from django.db import models from django.contrib.auth.models import User class Book_Detail(models.Model): def nameFile(instance, filename): user = User.objects.get(username=instance.user_id) return '/'.join([str(user.username), filename]) book_isbn = models.CharField(max_length=15) book_name = models.CharField(max_length=255) book_page = models.IntegerField() book_medium = models.CharField(max_length=20) book_author = models.CharField(max_length=255) book_genre = models.CharField(max_length=20) book_cover_page = models.ImageField(upload_to=nameFile, blank=True) book_last_page = models.ImageField(upload_to=nameFile, blank=True) book_page1 = models.ImageField(upload_to=nameFile, blank=True) book_page2 = models.ImageField(upload_to=nameFile, blank=True) book_page3 = models.ImageField(upload_to=nameFile, blank=True) book_rental = models.CharField(max_length=20, null=True, blank=True) book_price = models.FloatField() book_description = models.TextField(null=True, blank=True) status = models.CharField(max_length=45) posted_date = models.DateField(null=True) user = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='user') serializers.py from authentication.serializers import UserSerializer class BookDetailsSerializer(ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Book_Detail fields = '__all__' view.py from .models import Book_Detail from .serializers import BookDetailsSerializer from rest_framework import permissions class BookDetailsList(ListCreateAPIView): serializer_class = BookDetailsSerializer permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): serializer.save(user_id=self.request.user) … -
Deploying Django in Local Environment
I've built a Django Web App which is running on my local system (127.0.0.1:8000) without any errors. I'm also able to run the same app in my system running "python manage.py runserver xxx.xxx.x.xxx:8000" where "xxx.xxx.x.xxx" is my static IP. Then I connected that IP with my domain (let say "www.some domain name.com"). But the problem is when I try to load the page "www.some domain name.com" I'm not getting anything but when I try to load the page "www.some domain name.com:8000" it's working perfectly. So my question is how to get rid of that port number (i.e., :8000) which is attached to my domain name so that whenever I load "www.some domain name.com" I get exactly same result as "www.some domain name.com:8000". -
Primary-replica architecture for Django testing: non deterministic synchronization issue
I'm using a primary-replica architecture for Django testing. The implementation is pretty straight-forward, as seen here. The thing is that some tests are passing non deterministically: for example, they fail when I run that specifiy TransactionTestCase, but they pass when I run all of them. Then maybe they pass when I run the TranstactionTestCase, but if I run them isolatedly, they fail. The failure reason always is that some object created in the primary database is not found on the replica one. It's hard to understand why, specially considering that both databases are actually just one, according to the documentation provided above. I believe that my setup is correct, and tests do pass sometimes, so sometimes the replication is performed correctly. I just followed the documentation, and expected correct replication between databases. Does any one know what the issue may be? Is there a way to force synchronous replication using Django testing? -
How to filter by Custom Filter and django-filter in views
I wonder if there`s way to combine 2 filters: my custom filter and django-filter I want to write custom input and send information from input to my backend and filter my queryset by that info of my custom input and by info from django-filter as well How can i combine 2 filters at the same time? views.py def get_queryset(self): current_user = self.request.user current_counters = CounterParty.objects.filter(counter_user=current_user) qs = PresenceDetailInfo.objects.all() my_custom_filter = self.request.GET['custom_input'] word = PresenceDateFilter(self.request.GET, queryset=qs, request=self.request) return word.qs -
Django ImageField shows wrong url
I developed an e-commerce project, and now I am in the production phase in my own domain. Everything works perfect in development server. I'm using white-noise for serving static files in production server. In my project, I have Product model and related ImageField, I am uploading pictures of the products in admin page and showing them in HTML templates. However, the problem I see in my project is {{ product.image.url }} in HTML template calls --> "my-domain/media/images/8720908160225-1.4bdc930ddb46.jpg" However, correct call is "my-domain/static/media/images/8720908160225-1.4bdc930ddb46.jpg" Since "static" tag is missing, I am unable to show my uploaded pictures in my website. Part of settings.py file: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', # Django app 'cart', # Django app 'account', # Django app 'payment', # Django app 'mathfilters', 'crispy_forms', ] STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static',] MEDIA_URL = '/media/' MEDIA_ROOT = '/home/deb142470/domains/my-domain.nl/public_html/static/media' STATIC_ROOT = '/home/deb142470/domains/my-domain.nl/public_html/static' 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', ] Product model: class Product(models.Model): title = models.CharField(max_length=250) brand = models.CharField(max_length=250, default='BaddiCO') description = models.TextField(blank=True) category = models.ForeignKey( Category, related_name="product", on_delete=models.CASCADE, … -
Is it possible to make a real-time clock with Django?
I know that Django have a function that can get current time. However, it cannot continuously updates the time to the user interface (Real-time clock). The code for getting the current time. views.py from datetime import datetime from django.shortcuts import render def clock(request): now = datetime.now() context = { 'current_time': now.strftime('%Y-%m-%d %H:%M:%S') } return render(request, 'clock.html', context) clock.html {% extends "base.html" %} {% block content %} <h1>Current Time:</h1> <p>{{ current_time }}</p> {% endblock %} -
Does mezzanine allow custom navigation items to be displayed according to a custom permission?
I have a system that uses mezzanine custom navigation items to display some navigation items. However, I want the navigation items to only be displayed if a user have a specific set of permissions which are custom and not really Model based. Does mezzanine support this? Sample code ADMIN_MENU_ORDER = ( ('Customer service'), ( ('Customer X OverX', 'summary_e'), summary_e is a URL. How can I ensure Customer service is only displayed if a user has certain permission? -
Django - Changes to related field listed on History
I have two models class Project(models.Model): # ... history = HistoricalRecords() class ProjectMember(models.Model): project = models.ForeignKey(Project) user = models.ForeignKey(User) # ... Using django-simple-history, how can I list creation/changes of ProjectMembers under the Project history? The documentation mentions HistoricForeignKey, but it is not clear how to use it. I've tried this class Project(models.Model): # ... history = HistoricalRecords() class ProjectMember(models.Model): project = HistoricForeignKey(Project) user = models.ForeignKey(User) # ... history = HistoricalRecords() but it didn't produce the results I wanted. Is it even possible? -
How to set up test db settings in a DRF project?
I'm running unit tests in a drf project with a mongo db and djongo connector. When I run tests one by one they compile successfully but when I run all of them with python3 manage.py test test.path they all fail except the first test. The following line from the logs indicates that there is an issue with dropping the test database. FAILED SQL: DROP DATABASE "test_my_project_name" Here's the database configuration. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'my_project_name', 'CLIENT': { 'host': os.environ[DB_HOST], } }, 'test': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_mytestdatabase', 'USER': 'mytestdatabaseuser', 'PASSWORD': 'mytestpassword', 'HOST': 'localhost', 'PORT': '5432', } } What do I need to do to make the test db be used during tests and not the main db. Also do I need to set up anything else for the testing? -
Options request throws AssertionError error in Django REST Framework
I have the following Viewset: class My_ViewSet(viewsets.ModelViewSet): serializer_class = My_Serializer queryset = My_Object.objects.all() def list(self, request): # The code here is irrelevant return Response() def retrieve(self, request, pk=None): # The code here is irrelevant my_object = get_object_or_404(My_Object, id=pk) return Response(my_object.id) urls.py sample: urlpatterns = [ path('api/my_object/', My_ViewSet.as_view({'get': 'list'})), path('api/my_object/<int:pk>/', My_ViewSet.as_view({'get': 'retrieve'})), ] When I try to make OPTIONS request on api/my_object/ I have the following error: AssertionError: Expected view My_ViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. -
TypeError at /follow/4 follow() got an unexpected keyword argument 'user_id'
I'm creating a follow/unfollow button where a user clicks on the button and follows the other user if they are not already following the user. I am getting a TypeError with the below code; MODESL.PY class User(AbstractUser): following = models.ManyToManyField( "self", blank=True, related_name="followers", symmetrical=False ) def __str__(self): return str(self.username) URL.PY path("profile/<int:user_id>", views.profile, name="profile"), path("follow/<int:user_id>", views.follow, name="follow"), PROFILE.HTML <div class="row"> <b> following : </b> <p class="text-muted"> {{ profile.following.count }} </p> &nbsp;&nbsp;&nbsp;&nbsp; <b> followers : </b> <p class="text-muted"> {{ profile.followers.count }} </p> </div> {% if user.is_authenticated %} {% if user in profile.following.all %} <a href="{% url 'follow' user.id %}" class="btn btn-primary">Unfollow</a> {% else %} <a href="{% url 'follow' user.id %}" class="btn btn-primary"> Follow </a> {% endif %} {% else %} <button class="btn btn-outline-primary">Message</button> <p class="text-muted"> please, login to follow </p> {% endif %} VIEWS.PY def profile(request, user_id): profile = User.objects.get(pk = user_id) context = { "profile": profile, } return render(request, "network/profile.html", context) def follow(request, user_id): authorObj = User.objects.get(pk=user_id) currentUserObj = User.objects.get(pk=request.user.pk) following = authorObj.following.all() if user_id != currentUserObj.pk: if currentUserObj in following: authorObj.following.remove(currentUserObj) else: authorObj.following.add(currentUserObj) return HttpResponseRedirect(reverse("index")) I suspect the error is coming from the views def follow(request, user_id): searching on the template for the argument 'user_id which I've checked and the … -
404: NOT FOUND Vercel
I depolyed a simple django app on vercel with github. The build was successful, but the site says 404: NOT FOUND I edited ALLOWED_HOSTS in my settings.py ALLOWED_HOSTS = ['vercel.app'] -
Non admin users can access a view that is supposed to be restricted to admin users in django rest framework and simplejwt
I have made a custom user model inside my django backend and I have created a view that register a new user, but I have set the view only for admin users. When I tried to register a new user using a non admin account, it has also worked!! so the view is correct but there is something wrong with the permissions! could someone please tell me what did I do wrong? this is the models.py that has the custom user model: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_admin', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password=password, **extra_fields) class User(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def __str__(self): return self.first_name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): … -
How to create DateTImeFromToRangeFilter only with 1 field and DateRangePicker
Im looking for way to do something like that: I use package django-filter and i choose DateTimeFromToRangeFilter and it creates 2 input fields with different date pickers I wonder if there`s way to connect them into 1 field, use date range picker and make them work filters.py: import django_filters from django_filters import DateTimeFromToRangeFilter class MyFilter(django_filters.Filterset): work_date = DateTimeFromToRangeFilter() class Meta: Model = MyModel fields = ('__all__',) -
CommonMiddleware is not working in custom middlewares
CommonMiddleware not working in custom middlewares I have a custom middleware like below: class PageNotFoundMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) sura_pattern = r"/sura/[1-9]\d*-[1-9]\d*/$" print(f'\n\n{request.path_info}: {response.status_code}\n\n') # <-- if response.status_code == 404: if re.match(sura_pattern, request.path_info): return response return render(request, '404.html') elif response.status_code == 400: return render(request, '400.html') elif response.status_code == 500: return render(request, '500.html') elif response.status_code == 200 or response.status_code == 301: return response In the line I marked with arrow: "<--", the request.path_ifo, has no ending "/". example: If the inputted url is: /sura/10, then it shows me /sura/10, but it must append and ending "/" to it. this url is valid, here is the urls.py: urlpatterns = [ path("", home, name="home"), path('sura/<int:sura>/', sura_handler, name='sura_handler'), # <-- path which should get the url path('sura/<str:sura_aya>/', index, name='index'), path('page/<str:page>/', page_handler, name='page_handler'), path('juz/<str:juz>/', juz_handler, name='juz_handler'), path('api/', include('quran.api.urls')), path('sw/', sw, name="sw"), path('manifest/', manifest, name="manifest"), ] Note: Before regex executed, the response.status_code is 404. While if I correctly input the url, (like this: /sura/10/) then the response.status_code in not 404. can someone help me please find out why CommonMiddleware doesn't work in custom middlewares? Middlewares in django: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'quran.middleware.PageNotFoundMiddleware' … -
Setting the column fields for a laravel model
In another mvc framework like django,we can define the column fields by defining the attributes in the corresponding model clas. How to do that in laravel? class Model { name : string; address:string; } In the model class we can declare the column for the database and its data type ? How to do that in laravel? -
Django : Currently there is no database set to DATABASE_URL
I am working on a Django project for my client and I have to refactor the custom middleware to django authentication ( login ) and Django views. In the case of middleware, I put a passphrase which acts like a password and then it authorizes the users and everything works fine. now I changed the code from middleware to Django authentication to let the users login and then do the other logic. I was searching for the question on SO and I found this problem Django settings: DATABASE_URL is not working I tried to do the same but it is not fixing the issue. This is the code that tells me why my database url is not set: def message_check_db(request, **kwargs): try: DB_Found = False DB_Connected = False result = run_command() print("\n RESULT :", result) for (env, url) in os.environ.items(): if env.startswith('HEROKU_POSTGRESQL'): DB_Found = True print("\n FOUND DB :", DB_Found) formatted_Data = [] for formatted_String in str(result.stdout).split('=== '): start_DbName = formatted_String.find("HEROKU_POSTGRESQL_") end_DbName = formatted_String.find("\\nPlan") DbName = formatted_String[start_DbName:end_DbName] start_AddOn = formatted_String.find("Add-on:") end_AddOn = formatted_String.find("\\n\\n") AddOn = formatted_String[start_AddOn:end_AddOn].replace('Add-on: ', "") formatted_Data.append({ "name": DbName.replace(", DATABASE_URL", ""), "addon": AddOn }) color_DB = getDbName(env) current_DB = getDbName('DATABASE_URL') for data in formatted_Data: if env == data['name'] …