Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Quickstart: Compose and Django" documentation explanation. What does version refer to?
Hi I'm doing this documentation for docker. and I have to add this code to docker-compose file(step 9) version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db My question is, this is docker-compose version or docker? My instructor said it must be your docker version but 2.13.0 is the latest docker-compose version and Version 20.10.21 is latest docker version. My docker version is 20.10.17 and my docker-compose version is v2.6.1 what is 3? python version?! -
if number inputted is between 0 - 20000 update products prices [closed]
my company needs dev work and although I am not a dev I can read and write code a bit and have created an awesome capture form to load clients into our database. However I am currently stuck on a requirement. (Some Back ground) I built a django app which has some js functions in the html. We have products which I have made a dropdown in the form with set prices depending on the product selected it will update the field with the prices. ` if (Product.value == "certain cover"){ $('#Do_Premium').val('49'); $('#Premium').val('49');} ` Now there is a requirement to add tiering , say you are a silver member the prices will be lower (silver instead of 49 you will get "39") (Gold instead of 39 you will get "29") and so on. Now the QUESTION when the form loads a client is to put a number in that needs to be linked to a tier ie. 0-20000 Silver 20001 - 400000 Gold and so on . How would I code it so that when the user puts the number in it does a check to see which tier it needs to go use and then update field with that … -
Django xhtml2pdf error - SuspiciousFileOperation
I am implementing xhtml2pdf module for my django app. I have been able to print reports, however I am not getting my static configuration to work. I am getting error SuspiciousFileOperation at /moc-content/165/print-report The joined path (/moc/static/moc/main.css) is located outside of the base path component (/Users/xxx/Documents/django-projects/MOC/env/lib/python3.10/site-packages/django/contrib/admin/static) I have implemented link_callback function as xhtml doc is suggesting, but could not figure it out whats wrong with my settings: # settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'moc/static') STATIC_URL = 'moc/static/' # Media files (uploads) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'moc/media/' My xhtml functions are as per official docs My vs code directory tree https://i.stack.imgur.com/FWGuv.png -
Django Template: How to check if a variable is in another variable?
Beginner in Django here , I want to check if a particular string variable is in another variable inside the for loop. a = 'abc' b = 'abcd' I have tried below codes:- {% if a in b %} {% if '{{a}}' in b %} {% if '{{a}}' in '{{b}}' %} But none of them seem to work , can anybody guide me here please ? -
Django Raw SQL not returning expected results
I have the below function - it takes orgid, journalid and pid as url parameters. It SHOULD apply those filters to the journal.objects before running the query. However, it returns everything, even when there is only one record meeting the criteria passed in the URL params, Is there anything obvious that would cause that to happen? Thanks a lot @login_required(login_url='/login/') def viewjournal(request, orgid, journalid, pid): user = request.user journals = journal.objects.filter(orgid=org.objects.get(orgid=orgid), updateid=journalid, projectid=project.objects.get(projectid=pid)).raw(''' SELECT 1 as id, updateid, app_journal.orgid, app_journal.projectid, actions, datetime, epoch, app_project.projeectname FROM app_journal left join app_project on app_project.projectid = app_journal.projectid and app_project.orgid = app_journal.orgid''') return render(request, 'pmjournal.html', {'journals': journals}) -
How to attach foreign key associated with the multiple models to submit one form
How can in create inline formset which share the same foreign key using function base views. I don't want to keep selecting product title(which is the FK to other forms) because am using two forms with linked to one Foreign key# i want to implement this https://www.letscodemore.com/blog/django-inline-formset-factory-with-examples/ in function base views I have these 3 models #product model class Product(models.Model): title = models.CharField(max_length=150) short_description = models.TextField(max_length=100) def __str__(self): return self.title *Image model* class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) image = models.ImageField(blank=True, upload_to='images') def __str__(self): return self.product.title *variant model* class Variant(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE) size = models.CharField(max_length=100) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=12, decimal_places=2) def __str__(self): return self.product.title Forms **Forms** from django import forms from django.forms import inlineformset_factory from .models import ( Product, Image, Variant) class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'title': forms.TextInput( attrs={ 'class': 'form-control'} ), 'short_description': forms.TextInput( attrs={'class': 'form-control'}), } class ImageForm(forms.ModelForm): class Meta: model = Image fields = '__all__' class VariantForm(forms.ModelForm): class Meta: model = Variant fields = '__all__' widgets = { 'size': forms.TextInput(attrs={'class': 'form-control'} ), 'quantity': forms.NumberInput(attrs={'class': 'form-control'}), 'price': forms.NumberInput(attrs={ 'class': 'form-control'}), } VariantFormSet = inlineformset_factory( Product, Variant, form=VariantForm, extra=1, can_delete=True, can_delete_extra=True ) ImageFormSet = inlineformset_factory( Product, … -
Django ImportError: cannot import name 'Post' from partially initialized module (most likely due to a circular import)
So I have an app tentacle that has a processor.py file which imports some Models. The models.py also imports that function as it is used on a model's save method. Now when migrating I get a circular import error. I already tried these and changed the import from relative to an absolute alike version which didnt help. So how to "mutually" share the models and function inside processor.py and models.py which are located in sibling apps? -
Django Rest Framework Cannot save a model it tells me the date must be a str
I have this Profile model that also has location attached to it but not trying to save the location now only trying to save the Profile but get an error: class Profile(models.Model): # Gender M = 'M' F = 'F' O = 'O' GENDER = [ (M, "male"), (F, "female"), (O, "Other") ] # Basic information background = models.FileField(upload_to=background_to, null=True, blank=True) photo = models.FileField(upload_to=image_to, null=True, blank=True) slug = AutoSlugField(populate_from=['first_name', 'last_name', 'gender']) first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100) birthdate = models.DateField() gender = models.CharField(max_length=1, choices=GENDER, default=None) bio = models.TextField(max_length=5000, null=True, blank=True) languages = ArrayField(models.CharField(max_length=30, null=True, blank=True), null=True, blank=True) # Location information website = models.URLField(max_length=256, null=True, blank=True) # owner information user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "profile" verbose_name_plural = "profiles" db_table = "user_profiles" def __str__(self): return self.first_name + ' ' + self.last_name def get_absolute_url(self): return self.slug and this is the view I am using to save the Profile with. I tried sending the data to a serializer first and saving that but the serializer was invalid every time: class CreateProfileView(APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request): data = dict(request.data) location = {} location.update(street=data.pop('street')) location.update(additional=data.pop('additional')) location.update(country=data.pop('country')) … -
Django call function to save file cannot work
I am create Django project and create function for download file, But my project cannot work view.py from django.http.response import HttpResponse from django.conf import settings from django.http import HttpResponse, Http404 def index(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'my_file.json' filepath = BASE_DIR + '/filedownload/' + filename download(request,filepath) return HttpResponse('Download File') def download(request, path): file_path = path if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/x-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 How can I solve this? -
Get the first three human readable elements in a queryset
I'm trying to render elements in a Django view. Every clinic object has many specialities, but for estetic reasons I only want the first three of them to be displayed in the template. I've tried: def clinics_index(request): clinics = Clinic.objects.all() for clinic in clinics: speciality = clinic.get_speciality_display context = { 'clinics' : clinics, 'speciality' : speciality.first, } return render(request, 'guide/clinic/clinic_directory.html', context) This now renders the human-readable name of the speciality field (which is a multiple choice field in the model). However, I can't use substraction to only get 3 elements like here: speciality = clinic.get_speciality_display[:3] As I get the following error: TypeError at /guide/clinics/ 'method' object is not subscriptable How can I render it? -
No module named 'graphql.type' in Django
I am New in Django and GraphQL, following the the article, I am using python 3.8 in virtual env and 3.10 in windows, but same error occurs on both side, also tried the this Question, i also heard that GraphQL generate queries, But dont know how to generate it, But this error occurs: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/talha/ve/lib/python3.8/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/talha/ve/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/talha/ve/lib/python3.8/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
How to Change the Format of a DateTimeField Object when it is Displayed in HTML through Ajax?
models.py class Log(models.Model): source = models.CharField(max_length=1000, default='') date = models.DateTimeField(default=datetime.now, blank = True) views.py The objects in the Log model are filtered so that only those with source names that match a specific account name are considered. The values of these valid objects will then be listed and returned using a JsonResponse. def backlog_list(request): account_name = request.POST['account_name'] access_log = Log.objects.filter(source=account_name) return JsonResponse({"access_log":list(access_log.values())}) dashboard.html This Ajax script is the one that brings back the account name to the views.py. If there are no valid objects, the HTML will be empty; however, it will display it like this otherwise. <h3>You scanned the QR code during these times.</h3> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'POST', url : "/backlog_list", data:{ account_name:$('#account_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(response){ console.log(response); $("#display").empty(); for (var key in response.access_log) { var temp="<div class='container darker'><span class='time-left'>"+response.access_log[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occurred') } }); },1000); }) </script> My goal is to have the Date and time displayed like "Jan. 10, 2000, 9:30:20 A.M." I've tried changing the format directly from the models.py by adding "strftime" but the error response is triggered. -
Adding a custom, non-model attribute to query set in Django?
Newbie to DRF and have a model called posts. And another called user. The post object looks as follows: class Post(models.Model): """ Post model """ title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='forum_posts') parent_post = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) time_stamp = models.DateTimeField(default=timezone.now) objects = models.Manager() The serializer for this model is: class PostSerializer(serializers.ModelSerializer): class Meta: model = models.Post fields = ('id', 'title', 'body', 'parent_post', 'author', 'time_stamp') extra_kwargs = {'id': {'read_only': True}, 'author': {'read_only': True}} When returning data for this model, I want to add an extra attribute to each object within the query set called "author_username". The username should be the username belonging to the post's author id. I also want to do this without modifying the model to add another attribute such as "author_username" since this'll be redundant (already have an FK for author). So, ideally, the json for an object would look like: 'post_id': 1 'post_title': 'Example post' 'post_body': 'Example post' 'author_id': 1 'parent_post_id': null 'time_stamp': '2022' 'author_username': 'testUser' How can I go about doing this? Here's my view: class PostList(generics.ListCreateAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = models.Post.objects.all() serializer_class = serializers.PostSerializer -
How to convert db data into json format using python
database table data as input I have the above type of table data (screenshot) and i wanted to convert it into json dictionary using python. I tried my best but unable to create the hierarchy as per my requirement. I want the following json output. output result as json format -
Django Models: Filter a subset of a query set
I have these two models: class InspectionPoint(models.Model): ... review_check = models.BooleanField(default = 0) flight = models.ForeignKey( Flight, related_name='inspection_points', on_delete=models.CASCADE, null=True, blank=True ) ... class ImageSnapshot(models.Model): ... inspection = models.ForeignKey( InspectionPoint, on_delete=models.CASCADE, related_name = 'snapshots' ) flight = models.ForeignKey( Flight, related_name='snapshots', on_delete=models.CASCADE, null=True, blank=True ) ... I already have snapshots queryset with: snapshots = ImageSnapshots.objects.filter(flight=flight) but that gives me all snapshots. I want to filter snapshots that have only (review_check = True) Any idea? -
Django Channels Channels-redis How can I access the database of redis and how can I use it?
I used Django Channels for the first time and Redis for the first time through Channels. I want to use the data stored in the redis server currently in use by django or save it in the redis server. When listing chat rooms, I want to use channels_layer.receive_count to show the number of people who are accessing the chat room. (Like Twitch) When I access the chat room, I want to list the information of the users there. It would be nice if you could tell me how. Thank you! -
Two django projects with common userbase , authentication and sharing of key functionalities
I'm building a Django v3.2 project that requires merging of 2 projects(social app and ecommerce) - both of which are separate open source django projects. The end goal is to share users, posts and a common user registration and authentication process and keep a common database for both. Project 1 has a 5 docker containers(api backend, worker,scheduler, sql db, redis db) and project 2 has 1 docker container(that has a frontend sandbox ecommerce website). I came across this post while searching which is similar : How to make two django projects share the same database Based on the post share above, My core question is : While I'm using 2 separate projects that run their own docker containers, what changes will I have to make so that Registration, Authentication & Users are common Functionalities are shared. Essentially, I would like to import modules from project1-->project2 and project2-->project1 and design additional functionalities as per need. I initially tried copying files from project 2 into project 1 so that the project1 social app and functionality is just extended. But I'm running into all sorts of problems. Here is the question pertaining to the same : Python3.10:ModuleNotFoundError: No module named 'commerce' -
This code worked yesterday for another project, but its showing some error, I cannot get what the error is
what is the error here this is my models.py code, this code worked for another app, but not working in this. why? -
Adding an additional key-value pair to objects in a list before passing it to a Template - Working, but I'm not sure why
New to Django and I wanted to append a key:value pair to each Job object in a Queryset/list before passing it to a template. Researching on here it says you can't just append a field, but rather need to create a new dict or could possibly add attributes or something, but messing around I got it to work great, but logically it seems it shouldn't work, and I worry I may run into problems or data inconsistency somewhere. My "jobs" view gets all Jobs currently not assigned to a User, filters out Jobs based on the current signed in Users listed skillset(a custom field for my User model), and then the functionatily I'm adding is to check the current Users schedule, and add a value "conflict":True if the schedule conflicts so I can highlight it red when rendering the list of jobs to the screen. views.py (abbreviated): def jobs (request): //get all unassigned jobs, and create a list of only jobs where the user has matching skills available = Job.objects.filter(assigned_to__isnull=True).order_by('start_time').all() available = [job for job in available if request.user.is_skilled(job)] //go through each job, make it a dict, and add "conflict":True to it if scheudle confict for job in available: if … -
applying reverse relations with Foreign Key on two different Django models produces incorrect output
Class Job(Base): . . joining_status = models.BooleanField(default=False) drive = models.ForeignKey(Drive, null=True, blank=True) Class Internship(Base): . . joining_status = models.BooleanField(default=False) drive = models.ForeignKey(Drive, null=True, blank=True) Class Drive(xyz): . . . I'm trying to annotate count of jobs & internship (sum) having joining status true for a specific drive id. Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(internship__joining_status=True), then=1), output_field = IntegerField()))).values('x') output {'x':0} Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(job__joining_status=True), then=1), output_field = IntegerField()))).values('x') output {'x':1} But when I'm combining both together it is producing undesired result. Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(job__joining_status=True) | Q(internship__joining_status=True), then=1), output_field = IntegerField()))).values('x') output: {"x":2} // undesired output it should be {'x':1} I tried using multiple when conditions also, but the result was again undesirable. I'm a bit new in django, need help in writing this query. -
get the two types of sets from a model with condition
I want to get the credits and debits from the model, with condition tried a lot of methods but failed to approach the answer, the model i am working on is class SupplierTrans(models.Model): supplierName = models.ForeignKey(Supplier, on_delete = models.CASCADE) paid = models.BooleanField(default=True) amount = models.IntegerField() remarks = models.CharField(max_length = 200) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.supplierName) @property def paid_purchsased(self): return 'Paid' if self.paid == True else "Purchased" I approach in a methos that is sup = SupplierTrans.objects.annotate( credit = Sum('amount', paid=True), debit= Sum('amount', paid=False)).order_by('supplierName__name') but its not working the out is get the all the sum of the amount in the table if not filtering boolean values but the required is getting by the following method credit_amt = SupplierTrans.objects.filter(paid=True).aggregate(Sum('amount')) debit_amt = SupplierTrans.objects.filter(paid=False).aggregate(Sum('amount')) I wana get the following values in the above condition is there any approach, or should change the table structure -
How can query for group by based on unique value in Django
I want to group by data based on unique value. Eg. country: xyz, city: abc; country: xyz, city: efg; country: wxyz, city: abcde Query Result: xyz:[abc, efg], wxyz: [abcde] I solved this using dictionary**( query_res[country_val].append(city_val) )** , but I want to know if there have better solution. -
My Django Admin input doesn't allow me to add more than one image
I'm trying to make a Django model, with Django Rest Framework. I want this to allow me to load one or more images in the same input. MODELS: from django.db import models from datetime import datetime from apps.category.models import Category from django.conf import settings class Product(models.Model): code = models.CharField(max_length=255, null=True) name = models.CharField(max_length=255) image = models.ImageField(upload_to='photos/%Y/%m/', blank = True, null=True, default='') description = models.TextField() caracteristicas = models.JSONField(default=dict) price = models.DecimalField(max_digits=6, decimal_places=2) compare_price = models.DecimalField(max_digits=6, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) sold = models.IntegerField(default=0) date_created = models.DateTimeField(default=datetime.now) def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name = 'images') image = models.ImageField(upload_to='photos/%Y/%m/', default="", null=True, blank=True) SERIALIZER: from rest_framework import serializers from .models import Product, ProductImage class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ["id", "product", "image"] class ProductSerializer(serializers.ModelSerializer): images = ProductImageSerializer(many=True, read_only=True) uploaded_images = serializers.ListField( child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False), write_only=True ) class Meta: model = Product fields = [ 'id', 'code', 'name', 'description', 'caracteristicas', 'price', 'compare_price', 'category', 'quantity', 'sold', 'date_created', 'images', 'uploaded_images' ] def create(self, validated_data): uploaded_images = validated_data.pop("uploaded_images") product = Product.objects.create(**validated_data) for image in uploaded_images: newproduct_image = ProductImage.objects.create(product=product, image=image) return product I would simply like how to make the … -
How can I get the values of cartItem and make a n order?
How can I get the obj of the the cartItem and place an order? here's how my models.py look like. class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) cart = models.ForeignKey('Cart', on_delete=models.CASCADE) selected = models.BooleanField(default=False) -
How do I hit a Django-allauth login endpoint for automated testing
Context: I am creating some boilerplate automation to essentially login to a website as a restricted user and then verify that when I hit another endpoint, I get an unauthorized response. I don't have much experience with setting up an API automated testing framework from scratch, but I am using Behave and Behave-Django for all other automation. All my test data is coming from a django .env file. My current step to hit the login api as a restricted user is as follows: @given('I log in as a restricted user') def login(context, user): context.url = 'https://myurl.com' context.user_logged_in.send(user) assert context.status_code == 403 I'm pretty green when it comes to django, so if I'm not even close let me know. Thanks!