Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a ban on entering by url, if it was not made by the item "name"
I have a small function that controls the checkbox. When the user clicks on the checkbox, this link is triggered by {% url 'done' task.pk %}. But if you try to open this link in another tab, the checkbox also switches. How to make the user be able to follow the link by the value "name", but when he manually enters the url, there would be an error. Well, or some alternative solution to this problem. Code template <div class="is__done__checkbox"> <form method="post" action="{% url 'done' task.pk %}"> {% csrf_token %} <input type="checkbox" name="is_done" onchange="this.form.submit()" {% if task.is_done %} checked {% endif %}> </form> </div> url path('profile/<int:pk>/done/', done, name='done'), view def done(request, pk): task = Tasks.objects.get(pk=pk) is_done = request.POST.get('is_done', False) if is_done == 'on': is_done = True task.is_done = is_done task.save() return redirect(request.META.get('HTTP_REFERER')) I tried it def login_excluded(redirect_to): def _method_wrapper(view_method): def _arguments_wrapper(request, *args, **kwargs): if request.user: return HttpResponse(status=404) return view_method(request, *args, **kwargs) return _arguments_wrapper return _method_wrapper @login_excluded('/profile/<int:pk>/done/') def done(request, pk): task = Tasks.objects.get(pk=pk) is_done = request.POST.get('is_done', False) if is_done == 'on': is_done = True task.is_done = is_done task.save() return redirect(request.META.get('HTTP_REFERER')) But when clicking on the checkbox and for the user there was an error -
Upgrading AWS elastic beanstalk from python 3.6 to python 3.8
I have been tasked with upgrading this elastic beanstalk instance. Originally it was running Python 3.6 on Amazon Linux 1. Now I am upgrading to Python 3.8 to Amazon Linux 2. It is a Django application. Originally in the .ebextensions there was a file to install packages. packages: yum: python34-devel: [] postgresql93: [] postgresql93-devel: [] gcc-c++: [] I remember the gcc package was needed in order for us to add pandas and numpy as dependencies for the application. However when I upgraded to Amazon Linux 2 it could not find any of these packages. I removed them all and the application seems to be working fine through my testing. In the new Amazon Linux 2 do I need to specifically download any of these packages or are they automatically included? Or do I just not need them anymore? Also, the code base and application were already created before I started working on it. That is why I am currently unfamiliar with what the purpose of most of those packages are besides the gcc one. I have tried researching the different packages and seeing if I need them for my current application. I have read a lot of AWS docs, but … -
Django Search Bar Autocomplete is not populating at all
I'm looking to use autocomplete to show the items already populated in the 'ComicInputs' model filed named 'Title'. It will not work after trying a few different options. I'm using a JsonResponse in this version. Models.py class ComicInput(models.Model): Title = models.CharField(max_length=50,default='', blank=False, help_text="Comic Book title") Views.py from django.http import JsonResponse @require_GET def get_titles(request): if 'term' in request.GET: qs = ComicInput.objects.filter(Title__icontains=request.GET.get('term')) titles = list(qs.values_list('Title', flat=True)) return JsonResponse(titles, safe=False) return render(request, 'app/layout.html') Urls.py path('layout/get_titles/', views.get_titles, name='get_titles') layout.html <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script> <script src="{% static 'app/scripts/modernizr-2.6.2.js' %}"></script> <script> $(function () { $("#search").autocomplete({ source: '{% url 'get_titles' %}', minLength: 2 }); }); </script> </head> <form action="{% url 'search_page' %}" method="get" class="search-bar" style="width: 200px; height: 30px;font-size: small; align: top;" > <input type="search" id ="search" name="search" pattern=".*\S.*" value="Search Collections by Title" onFocus="this.value=''" required> <button class="search-btn" type="submit" style="background-color: #FFFFFF;"> <span>&#x1F50D;</span> </button> </form> -
Django declaring a read-only field on serializer
I have an endpoint that needs to expose the fields to the user, but under a different name. The user should -not- be able to set the PK (called orderId here) when creating the object, since that should be done automatically with a randomly set value when the object is created. Here is my serializer. class OrderSerializer(serializers.ModelSerializer): orderId = serializers.UUIDField(source="id") orderName = serializers.CharField(source="name") class Meta: model = Order fields = ( "orderId", "orderName", ) read_only_fields = ("orderId",) Here is my model: class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=48) Note that id in the model is exposed to the user under the name orderId. The problem is this set up seems to make it a required field when when a user creates an order. With the above set up, a POST request setting just orderName in the body to create an order gives this error: { "orderId": [ "This field is required." ] } Unless of course the user sends a value for orderId, which they should not do. I had hoped including the "orderId" as a ready only field would make it not required in a POST request, but that does not seem to be the case. … -
Using username for password in Django
When registering a user, the password should be the same as the username, and the user should change the password later ` def save(self): self.password(self.username) super().save() ` -
How to make if statements on postgresql json field elements inside a django template
I am having a hard time checking if a json field contains certain variable value in django template language. This is my model: from django.db.models import JSONField class Widget(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) endpoint = models.CharField(max_length=512) # "/data/id" type = models.CharField(max_length=64, default="line-graph") settings = JSONField(default=dict) This is how I insert data to this model: widget, created = Widget.objects.get_or_create( user=request.user, endpoint=endpoint, ) widget.type = type_ widget.settings = { "code": "", "dashboard": dashboard.id, "position": "top", "params": "per=m&len=1" } However, when I do this in the template it fails: {% if widget.setttings.position == "top" %} This does not fail, on the other hand: {% with widget.settings.position as pos %} {% if pos == "top" %} and by "fail" I mean it doesn't pass the condition. Am I doing something wrong? Django version: 3.2 Python version: 3.8 PostgreSQL version: 12.10 -
how custom management work in django and can fill database with csv?
I am learning Django with the book web development with django In the second chapter of the book, the author fills the database with a csv file. Can anyone explain this file and how the django custom command works? python code address: https://github.com/PacktPublishing/Web-Development-with-Django/blob/master/Chapter02/final/bookr/reviews/management/commands/loadcsv.py csv address: https://github.com/PacktPublishing/Web-Development-with-Django/blob/master/Chapter02/final/bookr/reviews/management/commands/WebDevWithDjangoData.csv i just know how it work -
Can you easily deploy a django website to IONOS (1&1)
I'm currently working on a website using the django framework and I found a good price for a domain on IONOS. I was wondering whether you can deploy a django website to IONOS in a simple way. I haven't been able to find good solutions online and I don't really want to switch to a different web hosting provider. In case I have to, could you recommend any good services (I need the website to use https and to be relatively scaleable). I've tried looking for alternatives that are 'Django friendly' but they don't really meet my needs. -
How to fetch the id of an item in Django when using JSON to fetch from the database
I have a Django template whereby I am looping through several items in the homepage. When an item is clicked, a modal which I have included by importing it should be shown and data related to the clicked item displayed. I am using JSONResponse to prepopulate the modal. Once the modal is shown, I want to create a checkout session which will require the id of the item being referred to in the modal. I am stuck at how to get the id. Here is the script for showing the modal and prepopulating it: let modal = document.getElementById("modal"); modal.style.display = "none"; function modalHandler(val, content_id) { if (val) { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { let data = JSON.parse(this.responseText); document.getElementById("subtotal").innerHTML = data.subtotal; document.getElementById("taxes").innerHTML = data.taxes; document.getElementById("website_fee").innerHTML = data.website_fee; document.getElementById("total").innerHTML = data.total; fadeIn(modal); } }; xhr.open("GET", "/modal-content/" + content_id + "/", true); xhr.send(); } else { fadeOut(modal); } } Here is the views.py which returns the JSON data: def modal_content_view(request, content_id): my_model = get_object_or_404(MyModels, content_id=content_id) print(f"the model is {my_model.username}") data = { 'subtotal': my_model.username, 'taxes': '2.60', 'website_fee': '0.87', 'total': '23.47', 'content_id':my_model.content_id } return JsonResponse(data) Here is the script that … -
Django development server not started?
Why does this happen? When i start the sever happen this, i don't kwon why happen this, the project contain package like: tensorflow, opencv etc. The project worked, but I left it for a few days and ran it again and this happens: this is the first time this has happened to me. info: python: 3.10.4 django: 4.1 conda: 4.9.2 start the server development, the server not working previously if it worked -
How to set NPM_BIN_PATH in django settings on cPanel?
I have been trying to deploy my django project with django-tailwind on cPanel [Shared Hosting]. django-tailwind needs to have set NPM_BIN_PATH in settings.py. But in cPanel there is no npm path. -
Failing to set up a log formatter class instance using Faust
Im trying to add a class of log formatter to the faust logging_config but getting an error with not mush exlained: CANNOT SETUP LOGGING: ValueError("Unable to configure formatter 'exp_formatter'") from File "det_to_events/main.py", line 246, in <module> app.main() File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/faust/app/base.py", line 761, in main cli(app=self) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/click/core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/faust/cli/base.py", line 539, in _inner cmd() File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/faust/cli/base.py", line 620, in __call__ self.run_using_worker(*args, **kwargs) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/faust/cli/base.py", line 630, in run_using_worker raise worker.execute_from_commandline() File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/mode/worker.py", line 279, in execute_from_commandline self.loop.run_until_complete(self._starting_fut) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/nest_asyncio.py", line 84, in run_until_complete self._run_once() File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/nest_asyncio.py", line 120, in _run_once handle._run() File "/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/events.py", line 81, in _run self._context.run(self._callback, *self._args) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/nest_asyncio.py", line 196, in step step_orig(task, exc) File "/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/tasks.py", line 280, in __step result = coro.send(None) File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/mode/services.py", line 800, in start await self._default_start() File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/mode/services.py", line 807, in _default_start await self._actually_start() File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/mode/services.py", line 815, in _actually_start await self.on_first_start() File "/Users/matany/Library/Caches/pypoetry/virtualenvs/det-to-events-S0HiGbUI-py3.8/lib/python3.8/site-packages/faust/worker.py", line 334, in on_first_start await self.default_on_first_start() File … -
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, …