Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering Django JSONB items in list
I have a Django data JSONField with the following data in { "title": "Some Title", "projects": [ {"name": "Project 1", "score": "5"}, {"name": "Project 2", "score": "10"}, {"name": "Project 3", "score": "2"}, ] } And I need to filter rows by project scores (numeric type), i.e. where project -> score <= 5 Django ORM provides the basics of filtering and working with a Postgres JSONB field. That is, I can do Model.objects.filter(data__title="Some Title") But it is not so straight forward when having a list of items in the JSON culumn, i.e. I can't do Model.objects.filter(data__projects__score__lte=5) Only way I can reach the `score` in Django ORM is to use the array index, i.e. Model.objects.filter(data__projects__0__score__lte=5) But that doesn't really work now, I'm interested in all items in that list, which can be however many Where I am currently: I've joined that list to the queryset as a jsonb_array_elements queryset.query.join(join=join_cfg) Which appended the following sql to the QUERY LEFT JOIN LATERAL jsonb_array_elements("my_table"."data" -> 'projects') projects ON TRUE Now, in Raw SQL, I can do something like this to filter that list WHERE (projects->>'score')::numeric < 5 Problem is I can't get this to play nicely with the Django ORM Currently, I'm adding this WHERE … -
Django Tenant Querying another tenant data inside public tenant
I want to fetch all users from specific tenant. Querying another tenant data is not working from public. class ClientDetailView(DetailView): model = Client def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['users'] = None with schema_context(self.object.schema_name): context['users'] = User.objects.all() return context -
Passing multiple parameters to hotel offers search in Amadeus python SDK
I am trying to pass multiple parameters to hotel offers using the Amadeus Python SDK but I am getting a 400 error code. How can I include checkInDate and checkOutDate in the request? here's the code : amadeus = Client( client_id = clientID, client_secret = ClientSecret ) try: hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode=citycode,checkInDate=checkindate,checkOutDate=checkoutdate,adults=adults,roomQuantity=rooms) k = hotels_by_city.data print(k) -
I have an issue with the new_defect method with the 1 to many relationship between Inspection and Defect
I am doing another fun project in Django that involves two classes, Inspections and Defects, which can be created once an Inspection is created. The goal of the new_defect method in views.py is to create a new defect within an Inspection report When I submitted the form with valid information, I got an IntegrityError at inspections/1/new with NOT NULL constraint failed. The result I wanted was a new Defect in an Inspection class. Here is my views.py that I used from django.shortcuts import render,get_object_or_404 from .forms import NewDefectForm from .models import Inspection # Create your views here. def home(request): inspections = Inspection.objects.all() return render(request, 'home.html', {'inspections': inspections}) def inspection_topics(request, pk): inspection = get_object_or_404(Inspection, pk=pk) return render(request, 'topics.html', {'inspection': inspection}) def new_defect(request, pk): -> integrityError occurs at inspections/1/new inspection = get_object_or_404(Inspection, pk=pk) if (request.method == 'POST'): form = NewDefectForm(request.POST) if form.is_valid(): defect = form.save(commit=False) defect.name = inspection defect.location = inspection form.save() return redirect('inspection_topics', pk=Inspection.pk) else: form = NewDefectForm() return render(request, 'new_defect.html', {'inspection': inspection, 'form': form}) Here is my new_defect.html that I used {% extends 'base.html' %} {% block title %}Start a New Defect{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Inspections</a></li> <li class="breadcrumb-item"><a href="{% url 'inspection_topics' inspection.pk … -
Origin null on POST request form
I'm currently trying to integrate a payment gateway into my website, the payment gateway have already whitelisted my domain but it's currently rejecting my post request due to Origin "null" in my request header. The request header is as such: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Cache-Control: max-age=0 Connection: keep-alive Content-Length: 363 Content-Type: application/x-www-form-urlencoded Host: payment.ipay88.com.my Origin: null Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: cross-site Sec-Fetch-User: ?1 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 The cross domain posting did not result in any Access control allow origin error and the form is just submitting a navigation to another page with some posted fields as such: <form action="https://payment.ipay88.com.my/epayment/entry.asp" method="POST"> <input type="hidden" name="MerchantCode" value="xx"> <input type="hidden" name="PaymentId" value="xx"> <input type="hidden" name="RefNo" value="xx""> <input type="hidden" name="Amount" value="xx"> <input type="hidden" name="Currency" value="xx"> <input type="hidden" name="ProdDesc" value="xx"> <input type="hidden" name="UserName" value="xx"> <input type="hidden" name="UserEmail" value="xx"> <input type="hidden" name="UserContact" value="xx"> <input type="hidden" name="Remark" value=""> <input type="hidden" name="Lang" value="xx"> <input type="hidden" name="SignatureType" value="xx"> <input type="hidden" name="Signature" value="xx"> <input type="hidden" name="ResponseURL" value="xx"> <input type="hidden" name="BackEndURL" value="xx"> <input id="submit" type="submit" class="btn-lg btn-danger" value="Submit" /> </form> How do i get the origin to display the domain of the request for cross … -
How to allow blank password via django-rest-api user create
In my case, I need to have one user group which email and password will not be set on user creation. They will not require to auth themselves either. I managed to do custom user with a nullable email, but I cannot find a way to allow blank password in API call or Django admin forms. I do not really care much about forms, but I need to have it working via API. How could I allow to create a new custom user with a blank password and maybe set it to something meaningful if it comes blank (like set_unusable_password())? Thanks! -
Django using select options in registration forms.py
Django using select options in registration forms.py I put some teams in my models.py in this way: class Account(AbstractBaseUser): TEAM = (('python', 'python'), ('php', 'php')) ... username = models.CharField(max_length=16, unique=True) first_name = models.CharField(max_length=16, unique=True) last_name = models.CharField(max_length=16, unique=True) member_of = models.CharField(max_length=20, choices=TEAM, default=TEAM[0][0]) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = AccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True and my forms.py is like: class RegistrationForm(UserCreationForm): #email = forms.EmailField(max_length=50) class Meta: model = Account #fields = '__all__' fields = ['username', 'first_name', 'last_name', 'password1', 'password2', 'member_of'] So when I want to use it in my registration.html I am not able to create account: <div class="group text-left"> <label for="exampleFormControlInput1">team</label> <select name="status" class="form-control" id="exampleFormControlSelect2"> {% for team in registration_form.member_of %} {{team}} {% endfor %} </select> </div> and also it is not important to use registration_form.member_of. If I only put member_of in my forms.py I can't register new users. -
How to set redirect route for django viewflow end?
How can I specify custom url where the user is redirected when flow ends in flow.End()? I tried to pass custom views with overridden get_success_url() to End node, but it was not working. flows.py end = flow.End( cancel_view=views.WeightTicketEndCancelView, detail_view=views.WeightTicketEndDetailView, undo_view=views.WeightTicketEndUndoView, perform_view=views.WeightTicketEndPerformView, view_or_class=views.WeightTicketEndView, ) views.py class WeightTicketEndPerformView(PerformTaskView): def get_success_url(self): return "/test/" -
React Fullstack: not able to fetch item details from Rest API
Im working on a fullstack django and react application, which for now just fetches the data from the django api, also im able to fetch the detail page of the first item present on the react list page but cannot do the same for the second item. It shows following error when i try to fetch the second item from django (strange but it works fine with the first item of id = 1 and not for id = 2 or 3). Also, I pushed my whole code on bitbucket. You can debug both frontend and backend here https://bitbucket.org/Yash-Marmat/react-django-blog/src/master/ thanks in advance. -
Calculate the time difference based on the hour between the present time and the time of the last update
I want to identify objects that have been updated for 24 hours. my model class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) image = models.ImageField(upload_to='products/%Y/%m/%d/') description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) my view: def home(request): products = Product.objects.filter(available=True) return render(request, 'shop_app/home.html', {'products': products}) -
How to add suffix url in Django Rest Framework?
How to add suffix url in ModelViewSet Serializer class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' def update(self, instance, validated_data): ... ... ModelViewSet I'm doing a custom partial update class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer http_method_names = ['get', 'patch', 'head', 'options'] def partial_update(self, request, *args, **kwargs): super(CommentViewSet, self).partial_update( request, *args, **kwargs) return Response({ "data": request.data, ... ... }) Urls router = routers.DefaultRouter() router.register( "comments", CommentViewSet ) urlpatterns = [ path('api/v1/', include(router.urls)) ] Currently have this, but I want to add a suffix url: http://localhost:8000/api/v1/comments/{id} I want to do something like this url: http://localhost:8000/api/v1/comments/{id}/update_or_whatever -
How to post to HyperlinkedRelatedField in Django Rest Framework?
Here I have two models called PostComment and AnswerComment separately to handle comments in my web application. Now I need to have voting option for both Post and Answer comments. Therefore I though using Django GenericRelations here would be a good idea to continue. I have implemented all the parts and I can't use Django Rest Framework to post data with Django HyperlinkedRelatedField. I'm using rest-framework-generic-relations (link) app as DRF documentation has recommended it. It gives me following error when I try to post data. Followings are my implementations, Post and Answer Models, class PostComment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) owner = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class AnswerComment(models.Model): answer = models.ForeignKey(Answer, on_delete=models.CASCADE) owner = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Comment Model, class VoteType(models.TextChoices): EMPTY = 'EMPTY' LIKE = 'LIKE' DISLIKE = 'DISLIKE' class CommentVote(models.Model): voteType = models.CharField(max_length=10, choices=VoteType.choices, default=VoteType.EMPTY) owner = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() voted_object = GenericForeignKey('content_type', 'object_id') Serializer for vote (as implemented in the documentation), class CommentVoteSerializer(serializers.ModelSerializer): voted_object = GenericRelatedField({ AnswerComment: serializers.HyperlinkedRelatedField( queryset=AnswerComment.objects.all(), view_name='answercomment-detail' ), PostComment: serializers.HyperlinkedRelatedField( queryset=PostComment.objects.all(), view_name='postcomment-detail' ), }) class Meta: model = CommentVote fields = … -
Issues with Django and VSCode
I am trying to practice building a website with Django and run into an issue trying to save my VSCode work and update my local browser, but only some things change. When I delete some code in my css file, the vscode is save but the elements in Google Chrome stay the same. When I inspect the element in the developer tools, the code that was deleted in vscode is still in the elements of the developer after the page is refreshed. Does anyone have any suggestions as to what could be causing this issue? Any help would be greatly appreciated -
django.db.utils.ProgrammingError: relation "client_apps_externalkeys" does not exist
I was trying to save stripe api keys to db and use, managed to save the keys to db, but when I call it in views getting the above error. How I can call it in views without this error, what I tried is follows class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True and when I call it in views stripe.api_key = str(ExternalKeys.objects.first().public) instead of normal way stripe.api_key = settings.STRIPE_SECRET_KEY getting the above error, is there any other way of storing api keys so that the client can edit it in future without the help of developer -
Django: How to hide all language prefix from urls while using i18n patterns
Currently, I am using i18n patterns. It can hide the default language prefix but do not hide another language prefix. Is there any other way to hide all the prefixes of languages and our local middleware will get the current language from currently set cookies? -
Django_filters to display the required filtered query
I want to filter and display only the generated value performed by the query set for the table. But instead of giving me the output for that query which is calling from a model it takes from another model and giving me a long list of values and some are repeated. I want to get only major_cd from my models to display it. My codes are views.py: def display_majorheads(request): myFilter = ProcessedOutputsFilter(request.GET, queryset=ProcessedOutputs.objects.all()) outputs = myFilter.qs year = outputs.first().finyear.finyear be_year = int(year.split('_')[1]) p_majors = ProcessedOutputs.objects.only('major_cd') majors = Major.objects.only('description').filter(major_cd__in=p_majors.values_list('major_cd', flat=True)).distinct().order_by("pk") processed_outputs = zip(majors,outputs) context = { 'processed_outputs':processed_outputs, 'be_year':be_year, 'myFilter':myFilter, } return render(request, 'website/mhead.html', context ) filters.py: import django_filters from django_filters import filters from .models import ProcessedOutputs class ProcessedOutputsFilter(django_filters.FilterSet): class Meta: model = ProcessedOutputs fields = '__all__' exclude = ['finyear', 'ag_salary'] models.py class ProcessedOutputs(models.Model): major_cd = models.OneToOneField(Major, models.DO_NOTHING, db_column='major_cd', primary_key=True) finyear = models.ForeignKey(Finyear, models.DO_NOTHING, db_column='finyear') ag_salary = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'processed_outputs' unique_together = (('major_cd', 'finyear'),) mhead.html: <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> -
Django Tenants Get another tenant data from public
Creating an app using Django Tenants with postgresql All are working fine. I need to get another tenant data. Like Tenant Name Users Groups tenant1 5 1 tenant2 8 2 Is there any way to achieve this. -
loop through objects in django using template tags is not working
I have model called Operation class Operation(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=120, default='Medicine') author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() img = models.ImageField(upload_to='media', null = True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('home') and views.py that looks like this def Operation(request): return render(request, 'operation.html') class OperationView(ListView): object_context_name = 'operation' model = Operation template_name = 'operation.html' class OperationDetailView(DetailView): model = Operation template_name= 'operation_details.html' the html page that renders the Listview of all the operations is as follows {% for operation in object_list %} <article> <a href="{% url 'operation-detail' operation.pk %}" class="image"><img src="{{post.image}}" alt="" /></a> <h3>{{operation.title}}</h3> <br> <h6> {{operation.author}}</h6> <br> <p>{{operation.body | slice:":200"}}</p> <ul class="actions"> <li><a href="{% url 'operation-detail' operation.pk %}" class="button">More</a></li> </ul> </article> {% endfor %} However it's not working or rendering any operation articles on the page. Any help? -
How to test django-basicauth or how to exempt (skip) a decorator
In my Django project, we have dual authentication one is from the standard login_required decorator and another from @basic_auth_required decorator which comes from django-basicauth. I can test the standard login_required decorator without any issues but for the second one @basic_auth_required I am having trouble and that's why I am getting status_code 401 every time, I have tried test Client, RequestFactory, and most of the available solutions. I have attached an image of how it looks like during website loading (it ask for user information in the alert box). This is how we are adding allowed users in a dictionary of basic-auth. BASICAUTH_USERS = {"username": "password"} This is how we are adding a decorator to a view @basic_auth_required def dashboard(request): #some code nothing to do with authentication return (request, 'template',data) If there is any way to skip the decorator from testing this will be a better Idea also. Thanks in Advance. -
Saving in django model
I am building a word counter website using. A user will input an URL, the backend will crawl that webpage and find the 10 most frequently used words and save it in the database. If another user enters the same URL, it is rendered from the database. If it doesn't exist in the database it will crawl and find the words. I need help in creating the model. How do I create such model which can save those words? What can be the most efficient way? -
Upload audio blob using xmlhttprequest in django
I have recorded the user audio using js and now i want to send the blob to Django server and save it as a .wav file. I use the following ajax code to send my blob to server: function sendData(data) { var request = new XMLHttpRequest(); request.open('POST', ''); request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); request.send(data); } and this successfully reach to server. in the Django views: def main(request): if request.method == "POST": data= request.Files fs = FileSystemStorage() filename = fs.save('test.wav', data) and the console shows server internal problem. I checked and found that the problem is with the save line of the code. Actually, my goal is just to save the .wav file in server, and my clear questions are: does the part of sending data is correct and the blob file is sent? In the server part how can i access the blob? and how can i save it? -
File uploading using AJAX is not working in Django
I'm trying to upload file using onchange event and AJAX but it is not working. I'm getting file path on backend not actual file. I want to modify this code such that when pdf file selected the file automatically get uploaded and can be use in views.py. a.html: <html> <head> <title> Django image and file upload using ajax </title> </head> <body> <form enctype="multipart/form-data" id="id_ajax_upload_form" method="POST" novalidate=""> {%csrf_token%} <input type="file" id="resumes" onchange="funct()" name="resumes"> <span>File</span> <input type="file" id="file" name="file" size="10"/> <input id="uploadbutton" type="button" value="Upload"/> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function(){ $("#file").change(function(){ var filename = $("#file").val(); $.ajax({ type: "POST", … -
Django dynamically retrieve ImageField.url from different Storages
I am very new to Django, so bear with me. Originally, my DEFAULT_FILE_STORAGE was hosted on GCS, and now it is on S3. I want to change DEFAULT_FILE_STORAGE to S3, but my model has ImageField items that are still referencing GCS. As a result of this, I cannot retrieve the .url property properly if I change the default file storage. What can I do to check if the url was initialized with GCS and retrieve from there instead of from DEFAULT_FILE_STORAGE (which in my case would be S3). -
save api keys in django database
how I can save api keys to django db and use it in application? I have tried saving it but when I call it in application it throws error "django.db.utils.ProgrammingError: relation “client_apps_externalkeys” does not exist" class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True) public_key = ExternalKeys.objects.first().public secret_key = ExternalKeys.objects.first().secret webhook_secret_key = ExternalKeys.objects.first().webhook_secret print(public_key) print(secret_key) print(webhook_secret_key) -
Django how to get name of Foreign Key in serializer?
Author is a Foreign Key relation in the model Book I currently get the output of GET request { book:"book1" author: 1 } But I want to get the name of the author in JSON { book:"book1" author: "author" }