Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" } -
Django: How do I update my inventory in the database of only the boxes that are checked?
I am creating a web application that will serve as a grocery store. I want it to work in a way so that when customers click on the checkbox and click submit, then the database will subtract the inventory quantity by 1. I am having trouble being able to capture the information from the checkboxes and then using that to subtract 1 from the inventory. models.py class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'Price', 'Sale', 'quantity', 'category',] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): Post = self.get_object() #editor = self.get_object() if self.request.user == Post.author: return True return False home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} {% if post.quantity > 0 %} <input type="checkbox" name="product[]" id=" {{ post.id }} "> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.category }}</a> </div> <h2><a class="article-title" … -
template doesnot exist errror in django
Hi I am beginner and I am trying to do a sign up login and logout pages but I am getting template doesnot exist error my views.py is from django.shortcuts import render,redirect from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: User.objects.get(username = request.POST['username']) return render (request,'templates/accounts/signup.html', {'error':'Username is already taken!'}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'],password=request.POST['password1']) auth.login(request,user) return redirect('home') else: return render (request,'templates/accounts/signup.html', {'error':'Password does not match!'}) else: return render(request,'templates/accounts/signup.html') def login(request): if request.method == 'POST': user = auth.authenticate(username=request.POST['username'],password = request.POST['password']) if user is not None: auth.login(request,user) return redirect('home') else: return render (request,'templates/accounts/login.html', {'error':'Username or password is incorrect!'}) else: return render(request,'templates/accounts/login.html') def logout(request): if request.method == 'POST': auth.logout(request) return redirect('home') my folder structure project name : -mysite -accounts(app name) - templates - accounts -base.html -login.html -signup.html please help me out thanks in advance error: TemplateDoesNotExist at /accounts/signup/ templates/accounts/signup.html my template configuration in setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Elastic Search 7 Python-Django Find the percentage matching the text
I have installed elastic-search 7. With Python3 and Django2. For the Django part i have used Elasticsearch DSL. What i want is to find the text is duplicate or matching over 90%. e.g : Data : ['Hi Jon Show', 'Hi Night King', 'Hi tyrion', 'Hi Josep'] Search text : Hi Jon ES Output : {'Hi Jon Show', 'Hi Josep',.... all other Hi'ss] I want to find how many percentage text matched. from elasticsearch_dsl import Search q = 'Hi Jon' fl = { 'match': { 'name': { 'query': q, "fuzziness":"AUTO", "minimum_should_match":"90%" } } } c = Search() c = c.filter(fl) x = c.execute() -
Unable to Install Pandas on Cents 7 Linux Server
I have a Centos7 linux server, on that i have deployed Django application, now i have to use pandas in the application, but post installing the pandas by using pip3.6 command and i am getting below error, please someone help ImportError at / Unable to import required dependencies: numpy: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: The Python version is: Python3.6 from "/usr/local/bin/python3" The NumPy version is: "1.19.4" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: /var/www/project/venv/lib/python3.6/site-packages/numpy/core/_multiarray_umath.cpython-36m-x86_64-linux-gnu.so: failed to map segment from shared object: Permission denied Request Method: GET Request URL: http://192.168.225.45/ Django Version: 3.1 Exception Type: ImportError Exception Value: Unable to import required dependencies: numpy: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how … -
Django how to GET data from two tables and combine data in GET request in views
These are the django models that I currently have: class Desgn_Mast(models.Model): desgn_mast_id = models.AutoField(primary_key=True) desgn_name_short = models.CharField(max_length=10) class Desgn_Trans(models.Model): desgn_trans_id = models.AutoField(primary_key=True) emp_mast_id = models.ForeignKey("app.Emp_Mast",on_delete=models.CASCADE) desgn_mast = models.ForeignKey("app.Desgn_Mast",on_delete=models.CASCADE) created = models.DateField() class Emp_Mast(models.Model): emp_mast_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) The Desgn_Trans table mantains the history of all the designations an employee has ever had. Now in the view of Emp_Mast, in the GET request I want to also obtain the desgn of the employee The example of the view is: class Desgn_Mast_ListView(APIView): permission_classes = [DjangoCustomModelPermissions] queryset = Task_Mast.objects.none() # TO define a dummy queryset for the purpose of the above permission class def get(self, request, format=None): db_data = Emp_Mast.objects.all() serializer = Emp_Mast_Serializer(db_data, many=True) return Response(serializer.data) I want the following output for the GET request, how to do it? { { emp_mast_id: 1, first_name: "Test", last_name: "User", desgn_mast: 1 (primary key of the respective desgn), }, {...}, {...}, } -
Django Images in row view
I have created a model in Django where I can upload the picture in the admin site and later it will be displayed in the homepage. *.html file <!-- templates/home.html --> <h1>Django Image Uploading</h1> <ul> {% for post in object_list %} <h2>{{ post.title }}</h2> <img src="{{ post.cover.url}}" alt="{{ post.title }}"> {% endfor %} </ul> How can I display all pictures in a row view ? instead of column ? (image-gallery kind of page I wanted to built) Thanks in Advance -
How to change what Django model returns as a value?
I'm trying to get my Product kind as what I declared It's name, instead I get number. Let me be more clear: This below is my Product Kinds; PRODUCT_KINDS = ( ("1","Electronic"), ("2","Furniture"), ("3", "Bedroom"), ("4","Dining") ) And this image below is my django-admin panel which everything seems perfect because I can get every single of my kinds. However, when I try to get this data from api/products url I get this data [ { "image": null, "name": "Headphones", "kind": "1", "price": 250.99, "description": "No description for this item.", "is_featured": true }, { "image": null, "name": "Watch", "kind": "3", "price": 12.5, "description": "No description for this item.", "is_featured": true }, { "image": null, "name": "T-shirt", "kind": "2", "price": 12.99, "description": "No description for this item.", "is_featured": true }, { "image": null, "name": "Ali Ziya ÇEVİK", "kind": "1", "price": 1212.0, "description": "No description for this item.", "is_featured": false } ] as you can see In my django-admin panel I get the name of kind but In the API I get It's index. This below is my serializer: from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): #kind = serializers.CharField(source = 'kind') #print(kind) class Meta: model = Product fields = ['image', …