Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Join two related fields tables of a model using Django's ORM
I have the following models in my Django app where I have common user subscription info as an abstract class that contains a foreign key to my user, and my other free and paid user subscription models that inherit the abstract class and implement the desired behavior: class CommonUserSubscriptionInfo(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="%(class)s") is_active = models.BooleanField(default=True, editable=False) number_of_requests = models.IntegerField(default=0, editable=False) hectares_consumed = models.FloatField(default=0, editable=False) class Meta: abstract = True class FreeUserSubscription(CommonUserSubscriptionInfo): max_free_hectares_allowed = models.FloatField(default=50) max_number_of_requests_allowed = models.FloatField(default=50) class PaidUserSubscription(CommonUserSubscriptionInfo): plan = models.ForeignKey(PaidSubscriptionPackages, on_delete=models.PROTECT, related_name="users_subscriptions") In my user model, in the case where my user has no active subscriptions, how can I join the tables of both related fields to query all the inactive free and paid subscriptions, order them by date and return the newest inactive subscription? something like: class User(AbstractBaseUser, PermissionsMixin): # code def get_last_active_subscription(self): return self.joined_subscriptions?.filter(is_active=False).order_by('-start_subscription_date')[0] I know I can use the related_name to access each table's related rows, and then I can merge both querysets as mentioned in this question, but I was wondering if there's a better or maybe more efficient way to achieve that using Django's ORM -
psycopg2 cant connect to postgres DB psycopg2.OperationalError
my db setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', 'HOST': '127.0.0.1', 'USER': 'postgres', 'PORT': '5432', 'PASSWORD': '1234' } } i try python manage.py migrate but have this error -
function or method for repeated event in python / django
models: from django.db import models class datecrt(models.Model): name=models.CharField(max_length=255) stdate=models.DateField() sttime=models.TimeField() endate=models.DateField() forms: import datetime from xml.dom.minidom import Attr from django import forms from .models import datecrt class dateform(forms.ModelForm): class Meta: model=datecrt fields='__all__' widgets={ 'stdate':forms.DateInput( attrs={'type':'date','class':'form-control'}, format='%D-%m-%yy', ), 'sttime':forms.TimeInput( attrs={'type':'time','class':'form-control'}, format='%H:%M', ), 'endate':forms.DateInput( attrs={'type':'date','class':'form-control'}, format='%D-%m-%yy', ) } def __init__(self,*args,**kwargs): super(dateform,self).__init__(*args,**kwargs) self.fields['stdate'].imput_format=('%D-%m-%yy',) self.fields['sttime'].imput_format=('%H:%M',) self.fields['endate'].imput_format=('%D-%m-%yy',) Views: from unicodedata import name from django.shortcuts import redirect, render from .forms import dateform from .models import datecrt def datecr(request): if request.method=='GET': form=dateform() return render(request, 'date.html', {'form':form}) else: form=dateform(request.POST) if form.is_valid(): form.save() return redirect('/dateview') def dateview(request): context={'dateview':datecrt.objects.all()} return render(request, 'dateview.html',context) When I create this booking on 1st of feb and end date will select as 5th of feb, my challenge is, created booking should display name, date, and time till 5th of feb automatically in dateview template, without me creating same for 2nd of feb, 3rd of feb till 5th of feb manually. -
Modify unique_together contraint on through model
I have a Rate model defined as follow: class Rate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'reviewer': True}) project = models.ForeignKey(Project, on_delete=models.CASCADE) rate = models.IntegerField( default=100, validators=[ MinValueValidator(0), MaxValueValidator(100) ] ) level = models.IntegerField(default=1) objects = RateManager() class Meta: db_table = 'api_project_reviewers' unique_together = ('user', 'project', 'level') It is an intermediate model between my User and my Project model. It's created like this on my project model: reviewers = models.ManyToManyField(User, related_name="review_project", through='Rate') I added the unique_together constraint on the model because I want to be able to have 2 entries as: Entry 1: User 1, Project 1, rate 100, level 1 Entry 2: User 1, Project 1, rate 100, level 2 Basically I want to be able to associate one user to the same project multiple time, changing the level. But when I do it I receive: IntegrityError at /admin/api/user/6/change/ duplicate key value violates unique constraint "api_project_reviewers_project_id_user_id_cd9f7f42_uniq" DETAIL: Key (project_id, user_id)=(1, 6) already exists. which is totally right byt shouldn't raise an error. How can I remove the unique_together constraint on user and project ? Thanks -
Django dynamic form returning only the last data using formset
in this view, I am getting only the last data that a user has filled. Let's suppose a user has entered 3 times Stop name but on the server-side, I am getting only the last which is the 3rd. 1st and 2nd are vanishing This is my template for the form <form method="POST" class="add-new-form" enctype="multipart/form-data"> {{ f_formset.management_form }} {{ ingredient }} <div id="div_testing"> <div class="testing2"> {{ form }} </div> </div> <button type="button" id="add-more-forms" onclick="duplicateForm()"> More Fields </button> This is my add new form function of javascript const xyx = document.getElementById("div_testing"); function duplicateForm() { let forms = xyx.getElementsByClassName("testing2"); let firstForm = forms[0]; let formClone = firstForm.cloneNode(true); xyx.appendChild(formClone); } And this is my Django view def supply_chain(request, id=0): items = SupplyChainStops.objects.all() formset_class = StopsFormSet ingredient_form = SupplyChainIngredientForm(request.POST or None) if request.method == 'POST': form = formset_class(request.POST) if form.is_valid() and ingredient_form.is_valid(): for frm in form: stop_name = frm.cleaned_data.get('stop_name') stop_longitude = frm.cleaned_data['stop_longitude'] stop_latitude = frm.cleaned_data['stop_latitude'] supply_chain_obj = SupplyChainStops(stop_name=stop_name, stop_longitude=stop_longitude, stop_latitude=stop_latitude) supply_chain_obj.save() return redirect('supply-chain') else: form = formset_class() context = { 'form': form, "ingredient": ingredient_form, # "items":items } return render(request, 'ingredients/supply_chain.html', context) This is the image of this HTML, when I will click on the add more button it will add 3 more fields which … -
Creating Custom Django model Function similar to Avg, Sum ,min ,max etc which are imported from django.db.models
I'm trying to create a function similar to the min, max avg, etc offered by django.db.models in Django. I'm stuck and couldn't find any lead and also I don't want to write a function and then perform operation on it, rather I want to perform the operation directly on DB and use a formula to return the value. For example If I want to find the change in a particular field in a given interval. I can do something as below. filtered_obj= modelA.objects.filter(create__range=[start_date,end_date]).values_list('value',flat=True) result= filtered_obj[-1]-filtered_obj[0] But rather then doing this i want to create a function similar to the Avg,min and max. So any help or any guidance or any reference will be a great help -
Is django's .get() faster than .filter()?
Which of the two is faster with big number of objects in a django model???? item1 = Item.objects.get(id=4) item2 = Item.objects.filter(school = request.user.school,id=4) -
Django multipart/form-data pass Dict & File
I want to create a post requests that sends a file along with information in the form of a dictionary. I have the following implementation: # conftest.py import pytest @pytest.fixture def api_client(): from rest_framework.test import APIClient return APIClient() Testing with pytest: # test_dataset.py @pytest.mark.django_db() class TestDatasetEndpoint: def test_dataset_create(self, api_client): data_raw = baker.make(Dataset) serialized_dataset = DatasetSerializer(data_raw).data print(serialized_dataset) file_path = "./Top 250s in IMDB.csv" with open(file_path, "rb") as fp: encoded_data = encode_multipart( BOUNDARY, {"data": serialized_dataset, "file": fp} ) response_post = api_client.post( reverse("datasets-list"), encoded_data, content_type="multipart/form-data; boundary=BOUNDARY", ) assert response_post.status_code == 201 Server side: # views.py class DatasetViewSet(viewsets.ModelViewSet): queryset = Dataset.objects.all() serializer_class = DatasetSerializer def create(self, request, *args, **kwargs) -> Response: data = request.data return Response(request.data["data"], status=status.HTTP_201_CREATED) The response i am getting is a combination of the dict and the file data. How can i handle the data and the file in the server side (views.py)? -
Should django migrations be applied automatically when using docker?
I'm dockerizing a Django app and I saw that some people run the migrations in the docker-compose.yml file but some people don't, what is the best solution? Thanks!! -
malloc_consolidate(): invalid chunk size
This is a strange error I'm having on a server: root@charles:oauthtutorial# /opt/oauthtutorial/venv/bin/python manage.py Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages [...removing more output...] test testserver [sessions] clearsessions malloc_consolidate(): invalid chunk size Aborted If INSTALLED_APPS contains only django.contrib.admin, django.contrib.contenttypes, django.contrib.messages and django.contrib.staticfiles (and my app, which it is a completely empty app created by django-admin), the error doesn't occur. If INSTALLED_APPS contains django.contrib.sessions or django.contrib.auth, then the error occurs. Environment: Debian 11.2 Linux 5.10.0-11-amd64 #1 SMP Debian 5.10.92-1 (2022-01-18) x86_64 GNU/Linux (Debian-packaged) Python 3.9.2 (default, Feb 28 2021, 17:03:44) [GCC 10.2.1 20210110] on linux Django 3.2.12 -
How to save a nested object in a post request correctly?
I am trying to work with a post request were I am first saving a Tag object, which then becomes the tag field of a Tagging object. However, no matter what combinations I have tried, despite the Tag Post method working, when I pass a json object like this: { "user_id": 1, "gameround_id": 2015594866, "resource_id": 2975, "tag": { "name": "TESTTAGGGG2222", "language": "en" }, "score": 0, "origin": "" } I keep getting this message: { "name": [ "This field is required." ], "language": [ "This field is required." ] } However, when I pass a Tag, it works. This is the relevant part from the post method: if tag_serializer.is_valid(raise_exception=True): tag_serializer.save(tag=request.data) if tagging_serializer.is_valid(raise_exception=True): tagging_serializer.save(tagging=request.data, tag=tag_serializer.data) return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED) # else: # return Response({"status": "success", "data": tag_serializer.data},status=status.HTTP_201_CREATED) else: return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) How do I correctly pass the nested object in the post method so that I don't get this error anymore? -
Django rename field and create new one with the same name returns psycopg2 error: DuplicateTable: relation already exists
I have a Django (foreign key) field which I renamed in one migration (automatic detection). Then I realised I actually need one with that name but a different one. Locally I develop on an SQLite DB and this works fine. When I pushed it to our Postgres DB, this returned an error. Migration one operations = [ migrations.RenameField( model_name='modelname', old_name='oldfieldname', new_name='newfieldname', ),] Migration two operations = [ migrations.AddField( model_name='modelname', name='oldfieldname', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='OldFieldName', to='app.othermodel'), ),] When I run this migration I get the following error Applying app.xxx1_previous... OK Applying delight.xxx2_rename_field... OK Applying delight.xxx3_add_field...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DuplicateTable: relation "app_modelname_oldfieldname_id_8c448c6a" already exists Normally this should have been deleted. I found this issue describing a similar issue in Postgress and now I wonder if this is a bug in Django. Could it be that the cleanup from the rename is not done correctly? -
how to override list permission with django-rules
I installed django-rules to my project to define rules for my actions. The list function hast no permission setting per default so you have to add them to the permission_type_map as written here but without an effect. For the other actions i am able to change the behavior if i set it to is_superuser or something else. from django.db import models import rules from rules.contrib.models import RulesModel from rules.contrib.rest_framework import AutoPermissionViewSetMixin from base.models import BaseModel class Company(RulesModel, BaseModel): name = models.CharField(max_length=100) active = models.BooleanField(default=True) permission_type_map = { **AutoPermissionViewSetMixin.permission_type_map, "list": "all", } class Meta: rules_permissions = { # TODO: rules need to be defined "add": rules.always_allow, "view": rules.always_allow, "delete": rules.always_allow, "change": rules.always_allow, "all": rules.is_superuser } What do i miss here? -
django urls error when I import a non-itinerant object
I can't understand why it gives me an error when importing my views. I don't understand where the mistake is. I deleted some apps from the project and views, will it be for that? views from django.shortcuts import render from django.views.generic import ListView from .views import Schede class SchedeListView(ListView): model = Schede template_name = 'test.html' context_object_name = 'schede' devtest urls from django.urls import path from django.views.generic import TemplateView from .views import views urlpatterns = [ path('', TemplateView.as_view(template_name="dash.html"), name="home"), path('test_schede/', views.SchedeListView.as_view(), name="test_schede"), ] url general from django.contrib import admin from django.urls import path, include #sitemap from django.contrib.sitemaps.views import sitemap from .sitemaps import StaticViewSitemap #pdf from pdf.views import testPdfView sitemaps = {'static': StaticViewSitemap} urlpatterns = [ path('admin/', admin.site.urls), path('test/<id>/', testPdfView, name="test_pdf"), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), path('', include('devtest.urls')) ] error C:\Users\dev\Downloads\laragon\www\scheda>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\dev\Downloads\laragon\bin\python\python-3.6.1\lib\site-packages \django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable -
How to recover local uncommited files that accidentally got deleted in Android Studio?
I faced a sudden issue, I have deleted some of my un revisioned files during commit to my android project but I found all of the modified and newly added files were missing from my commit (which I was going to make). I can not just remove or pull again the project from the origin because it will completely remove the VCS cache of the previous one. How do I get my files back? I have also checked this questions and answers but this didn't solve my issue. So, I have found a solution otherwise with new Android Studio update. -
Trying to get \n to work in django/html after using python for script
I created a Python script that retrieves a list of payments that go to my companies email. I thought it would be interesting to do for Cashapp/Venmo payments to compile them. However I really want the site to format the payments/details so that each payment is on a new line. In the python I put final = final + ..... + \n for the string that is to be used in the html. Yet \n will not work in HTML no matter what I try to do. In my views.py I set data=final, then call it here in the HTML. <body> <button onclick="location.href='{% url 'script' %}'" > Check new payments </button> <hr> {% if data %} {{data}} {% endif %} </body> This prints out all the necessary data yet it is in one continuous string and does not include the \n. If I print it in the terminal it includes these. It is likely because html does not recognize \n I assume, I just don't know an alternative for this. -
django-filter not showing filtered items
i used django-filter in a similiar way before and it worked fine, but now when I try to filter my posts it just returns all the items instead of filtering them, can anyone figure what I'm doing wrong? my filters.py class filtering(django_filters.FilterSet): class Meta: model = Cars fields = ['color','body'] and my views: start_date = (datetime.today() - timedelta(30)) end_date = (datetime.today() + timedelta(1)) last_month_records = Cars.objects.filter(datetime__range=(start_date, end_date),car='206') post_list = last_month_records.order_by('-datetime').values() filters = filtering(request.GET,queryset=post_list) post_list = filters.qs.values() -
Ecommerce website in Django, Order is not being saved when the client logged in an account. If not it's working well
I am working on ecommerce website and it's time to make checkout. In my website, when to order product without an account it's saving the order, but if it's with an account, it's going to another page, but not erasing a cart and isn't saving the order. What is the problem? Can you please help me to solve this problem. It's not working only when client is logged in an account. views.py def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) tel = data['shipping']['number'], address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) else: customer, order = guestOrder(request, data) total = float(data['form']['total']) order.transaction_id = transaction_id order.tel= tel order.address=address order.city=city order.state=state if total == order.get_cart_total: order.complete = False order.save() return JsonResponse('Payment submitted..', safe=False) html <form class="form" method="POST" action="#" id="form"> <div class="row"> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Имя<span>*</span></label> <div> <input type="text" name="name" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Фамилия<span>*</span></label><div> <input type="text" name="surname" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Email<span>*</span></label><div> <input type="email" name="email" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info shipping-info"> <div class="form-group"> <label>Номер телефона<span>*</span></label><div> <input type="number" name="number" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" … -
Delete File on S3 bucket before uploading new file with the same name
I have a model, that on save, it uploads my image to my S3 bucket. But I'm having some trouble when I want to reupload an image with the same name. (Example: when a logo updates it needs to be reuploaded) Because the image already exists, Django extends the pathname with it's own generated extention to make it unique. We don't want that, we want to delete the existing image before uploading the new image. That way, the extention is no more. I've tried removing my image first with the pre_save signal, but that just makes my imagefield empty @receiver(pre_save, sender=geo_models.Logo) def remove_file_from_s3(sender, instance, using, **kwargs): instance.png.delete(save=False) Any way of doing this? -
Filter tables contain all value in another table
i have 2 tables Product and user and each table have list of permissions i need to list to the user all product such that user have all the product permissions check the code representation: Product Model: class Product(TimeStampedModel, SoftDeletableModel): title = models.CharField(max_length=255, unique=True) permission = models.ManyToManyField(Permission, related_name="Permissions") and this is the user model: class User(AbstractBaseUser, SoftDeletableModel): display_name = models.CharField(max_length=64, blank=True) permission = models.ManyToManyField(Permission, related_name="Permissions") lets say we have the following data: user1 permissions A1,A2,C1,C2,C3 user2 permissions A1,A2,B1,B2,C1,C2,C3 product has permissions A1,B1,C1 user1 can not see the product "does not have B1 permission" user2 can see the product i tried the following: Products.objects.filter(permission__in=user.permission.values("id")) also tried this sql query: Select * from products p Inner join productspermession pp On p.id = pp.product_id Inner join userpermessions up on pp.permession_id = up.permession_id where up.user_id = 1 -
how to write File Download with django Rest framework?
I have a model with filefield with xls and xlsx and person who uploaded it i need to write api view in DRF that returns download on front end how can my view be? models.py class FileuploaderView(BaseModel): file = models.FileField( upload_to='', validators=[FileExtensionValidator(['xls', 'xlsx'])], ) uploaded_by = models.ForeignKey( 'accounts.Person', related_name= '', null=True, on_delete=models.SET_NULL, ) views.py: def DownloadView(APIView): def get(self, request, id, format=None): queryset = Model.objects.get(id=id) file_handle = queryset.file.path document = open(file_handle, 'rb') response = HttpResponse(FileWrapper(document), content_type='') response['Content-Disposition'] = 'attachment; filename="%s"' % queryset.file.name return response Is it the -
why my code is not going to try block and goes directly to except block in django
Hi there I've created a user login page with built in database in my django project. I've created a login page and make a try block to check if email id already registered in database? if data found in database then it goes to index page other wise gives an error like "ID not registered". I have double check the user id and password field, its correct but still my code goes straight forward to exception block only. what is wrong with my code ? '''def login(request): if request.method=="POST": try: user=User.objects.get( email=request.POST['email'], password=request.POST['password'] ) request.session['email']=user.email request.session['fname']=user.fname return render(request,'index.html') except: msg="Email Or Password Is Incorrect" return render(request,'login.html',{'msg':msg}) else: return render(request,'login.html')''' -
What are the step by step to Host my Django app to IBM cloud
I created a Blog application in Django, and now I decided to hosting it in IBM Cloud, what are the step by step to host it in IBM Cloud, I get confused with the tutorials I follow in YouTube and also some Blog in Google, all i see is the tutorial with Flask. what are the libraries and file do I needs before hosting it in IBM CLOUD. Is some body who can help me ? -
Need to display the hours spent in the date from one model to another
model 1 class Add_Timelog(models.Model): project=models.ManyToManyField(Project) client=models.ManyToManyField(Client) Job=models.ManyToManyField(Add_Job) Date= models.DateField(default = datetime.date.today) Hours=models.TimeField(null=True) def __str__(self): return str(self.Date) model 2 class Consolidated(models.Model): emp_name=models.ManyToManyField(Users,related_name="employee_name+") proj_name=models.ManyToManyField(Project) custom_name=models.ManyToManyField(Client) Cons_date=models.ManyToManyField(Add_Timelog) bill_no_bill=models.ManyToManyField(Users,related_name="billable_and_non_billable+") hours_spent = models.ManyToManyField(Add_Timelog,related_name="Hours+") def __str__(self): return str(self.id) I need to update the value from "Hours" field in Add_Timelog model to display it in the "hours_spent" field in Consolidated model. As I am already doing it for "Date" field I need to do it for this also. But I don't know whether it can be possible, kindly help me with this code. (ex: if I enter a Date as today and Hours as 4 hr's in Add_Timelog model, I need to display it in Consolidated model as for today 4 hr's has been spent by this employee.) -
How can I display image in admin.py and one of my field in employee table is not appearing correct in admin.py?
I am working on creating Employee monitoring system. I have 3 models right now. Here they are class User(models.Model): username= models.CharField(max_length=256, verbose_name='Username') first_name = models.CharField(max_length=256, verbose_name='First Name') last_name = models.CharField(max_length=256, verbose_name='Last Name') email=models.EmailField(max_length=256, verbose_name='Email') def __str__(self): return self.first_name + self.last_name class Departments(models.Model): department_name= models.CharField(max_length=256, verbose_name='Departments') def __str__(self): return self.department_name class Designation(models.Model): department_name= models.ForeignKey(Departments, on_delete=models.CASCADE) designation_name=models.CharField(max_length=256, verbose_name='Designation') def __str__(self): return '{} {}'.format(self.department_name, self.designation_name) class Employee(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,) department_name= models.ForeignKey(Departments, on_delete=models.CASCADE) designation_name= models.ForeignKey(Designation, on_delete=models.CASCADE) salary= models.FloatField(null=False, default=0.0, verbose_name='Salary') image = models.ImageField(upload_to = 'employee_images', null=True, blank=True) def __str__(self): return '{} {} {}'.format(self.user.first_name + self.user.last_name, self.department_name.department_name, self.designation_name.designation_name) def image_tag(self): return mark_safe('<img src="/employee_images/%s" width="150" height="150" />' % (self.image)) image_tag.short_description = 'Image' my return self.first_name +self.last_name in def __str__(self) of employee table is not giving me any gap between these two names. I don't know how to do it. and I have tried every method suggested by everyone on this website to display image on admin.py but I am unable to display them. Here is my admin.py admin.py @admin.register(Employee) class EmployeeAdmin(admin.ModelAdmin): list_display= ('first_name', 'last_name', 'designation_name', 'department', 'salary', 'image_tag') def first_name(self, obj): return obj.user.first_name def last_name(self, obj): return obj.user.last_name def designation_name(self, obj): return obj.designation.designation_name def department(self, obj): return obj.department_name.department_name and one last thing my designation_name …